PackageManagerService.java revision c80b3b75df6b3840e173d1653ddbf6854954a626
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_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
106
107import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
108
109import android.Manifest;
110import android.annotation.IntDef;
111import android.annotation.NonNull;
112import android.annotation.Nullable;
113import android.app.ActivityManager;
114import android.app.AppOpsManager;
115import android.app.IActivityManager;
116import android.app.ResourcesManager;
117import android.app.admin.IDevicePolicyManager;
118import android.app.admin.SecurityLog;
119import android.app.backup.IBackupManager;
120import android.content.BroadcastReceiver;
121import android.content.ComponentName;
122import android.content.ContentResolver;
123import android.content.Context;
124import android.content.IIntentReceiver;
125import android.content.Intent;
126import android.content.IntentFilter;
127import android.content.IntentSender;
128import android.content.IntentSender.SendIntentException;
129import android.content.ServiceConnection;
130import android.content.pm.ActivityInfo;
131import android.content.pm.ApplicationInfo;
132import android.content.pm.AppsQueryHelper;
133import android.content.pm.AuxiliaryResolveInfo;
134import android.content.pm.ChangedPackages;
135import android.content.pm.ComponentInfo;
136import android.content.pm.FallbackCategoryProvider;
137import android.content.pm.FeatureInfo;
138import android.content.pm.IDexModuleRegisterCallback;
139import android.content.pm.IOnPermissionsChangeListener;
140import android.content.pm.IPackageDataObserver;
141import android.content.pm.IPackageDeleteObserver;
142import android.content.pm.IPackageDeleteObserver2;
143import android.content.pm.IPackageInstallObserver2;
144import android.content.pm.IPackageInstaller;
145import android.content.pm.IPackageManager;
146import android.content.pm.IPackageManagerNative;
147import android.content.pm.IPackageMoveObserver;
148import android.content.pm.IPackageStatsObserver;
149import android.content.pm.InstantAppInfo;
150import android.content.pm.InstantAppRequest;
151import android.content.pm.InstantAppResolveInfo;
152import android.content.pm.InstrumentationInfo;
153import android.content.pm.IntentFilterVerificationInfo;
154import android.content.pm.KeySet;
155import android.content.pm.PackageCleanItem;
156import android.content.pm.PackageInfo;
157import android.content.pm.PackageInfoLite;
158import android.content.pm.PackageInstaller;
159import android.content.pm.PackageManager;
160import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
161import android.content.pm.PackageManagerInternal;
162import android.content.pm.PackageParser;
163import android.content.pm.PackageParser.ActivityIntentInfo;
164import android.content.pm.PackageParser.PackageLite;
165import android.content.pm.PackageParser.PackageParserException;
166import android.content.pm.PackageStats;
167import android.content.pm.PackageUserState;
168import android.content.pm.ParceledListSlice;
169import android.content.pm.PermissionGroupInfo;
170import android.content.pm.PermissionInfo;
171import android.content.pm.ProviderInfo;
172import android.content.pm.ResolveInfo;
173import android.content.pm.ServiceInfo;
174import android.content.pm.SharedLibraryInfo;
175import android.content.pm.Signature;
176import android.content.pm.UserInfo;
177import android.content.pm.VerifierDeviceIdentity;
178import android.content.pm.VerifierInfo;
179import android.content.pm.VersionedPackage;
180import android.content.res.Resources;
181import android.database.ContentObserver;
182import android.graphics.Bitmap;
183import android.hardware.display.DisplayManager;
184import android.net.Uri;
185import android.os.Binder;
186import android.os.Build;
187import android.os.Bundle;
188import android.os.Debug;
189import android.os.Environment;
190import android.os.Environment.UserEnvironment;
191import android.os.FileUtils;
192import android.os.Handler;
193import android.os.IBinder;
194import android.os.Looper;
195import android.os.Message;
196import android.os.Parcel;
197import android.os.ParcelFileDescriptor;
198import android.os.PatternMatcher;
199import android.os.Process;
200import android.os.RemoteCallbackList;
201import android.os.RemoteException;
202import android.os.ResultReceiver;
203import android.os.SELinux;
204import android.os.ServiceManager;
205import android.os.ShellCallback;
206import android.os.SystemClock;
207import android.os.SystemProperties;
208import android.os.Trace;
209import android.os.UserHandle;
210import android.os.UserManager;
211import android.os.UserManagerInternal;
212import android.os.storage.IStorageManager;
213import android.os.storage.StorageEventListener;
214import android.os.storage.StorageManager;
215import android.os.storage.StorageManagerInternal;
216import android.os.storage.VolumeInfo;
217import android.os.storage.VolumeRecord;
218import android.provider.Settings.Global;
219import android.provider.Settings.Secure;
220import android.security.KeyStore;
221import android.security.SystemKeyStore;
222import android.service.pm.PackageServiceDumpProto;
223import android.system.ErrnoException;
224import android.system.Os;
225import android.text.TextUtils;
226import android.text.format.DateUtils;
227import android.util.ArrayMap;
228import android.util.ArraySet;
229import android.util.Base64;
230import android.util.BootTimingsTraceLog;
231import android.util.DisplayMetrics;
232import android.util.EventLog;
233import android.util.ExceptionUtils;
234import android.util.Log;
235import android.util.LogPrinter;
236import android.util.MathUtils;
237import android.util.PackageUtils;
238import android.util.Pair;
239import android.util.PrintStreamPrinter;
240import android.util.Slog;
241import android.util.SparseArray;
242import android.util.SparseBooleanArray;
243import android.util.SparseIntArray;
244import android.util.Xml;
245import android.util.jar.StrictJarFile;
246import android.util.proto.ProtoOutputStream;
247import android.view.Display;
248
249import com.android.internal.R;
250import com.android.internal.annotations.GuardedBy;
251import com.android.internal.app.IMediaContainerService;
252import com.android.internal.app.ResolverActivity;
253import com.android.internal.content.NativeLibraryHelper;
254import com.android.internal.content.PackageHelper;
255import com.android.internal.logging.MetricsLogger;
256import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
257import com.android.internal.os.IParcelFileDescriptorFactory;
258import com.android.internal.os.RoSystemProperties;
259import com.android.internal.os.SomeArgs;
260import com.android.internal.os.Zygote;
261import com.android.internal.telephony.CarrierAppUtils;
262import com.android.internal.util.ArrayUtils;
263import com.android.internal.util.ConcurrentUtils;
264import com.android.internal.util.DumpUtils;
265import com.android.internal.util.FastPrintWriter;
266import com.android.internal.util.FastXmlSerializer;
267import com.android.internal.util.IndentingPrintWriter;
268import com.android.internal.util.Preconditions;
269import com.android.internal.util.XmlUtils;
270import com.android.server.AttributeCache;
271import com.android.server.DeviceIdleController;
272import com.android.server.EventLogTags;
273import com.android.server.FgThread;
274import com.android.server.IntentResolver;
275import com.android.server.LocalServices;
276import com.android.server.LockGuard;
277import com.android.server.ServiceThread;
278import com.android.server.SystemConfig;
279import com.android.server.SystemServerInitThreadPool;
280import com.android.server.Watchdog;
281import com.android.server.net.NetworkPolicyManagerInternal;
282import com.android.server.pm.Installer.InstallerException;
283import com.android.server.pm.PermissionsState.PermissionState;
284import com.android.server.pm.Settings.DatabaseVersion;
285import com.android.server.pm.Settings.VersionInfo;
286import com.android.server.pm.dex.DexManager;
287import com.android.server.pm.dex.DexoptOptions;
288import com.android.server.pm.dex.PackageDexUsage;
289import com.android.server.storage.DeviceStorageMonitorInternal;
290
291import dalvik.system.CloseGuard;
292import dalvik.system.DexFile;
293import dalvik.system.VMRuntime;
294
295import libcore.io.IoUtils;
296import libcore.io.Streams;
297import libcore.util.EmptyArray;
298
299import org.xmlpull.v1.XmlPullParser;
300import org.xmlpull.v1.XmlPullParserException;
301import org.xmlpull.v1.XmlSerializer;
302
303import java.io.BufferedOutputStream;
304import java.io.BufferedReader;
305import java.io.ByteArrayInputStream;
306import java.io.ByteArrayOutputStream;
307import java.io.File;
308import java.io.FileDescriptor;
309import java.io.FileInputStream;
310import java.io.FileOutputStream;
311import java.io.FileReader;
312import java.io.FilenameFilter;
313import java.io.IOException;
314import java.io.InputStream;
315import java.io.OutputStream;
316import java.io.PrintWriter;
317import java.lang.annotation.Retention;
318import java.lang.annotation.RetentionPolicy;
319import java.nio.charset.StandardCharsets;
320import java.security.DigestInputStream;
321import java.security.MessageDigest;
322import java.security.NoSuchAlgorithmException;
323import java.security.PublicKey;
324import java.security.SecureRandom;
325import java.security.cert.Certificate;
326import java.security.cert.CertificateEncodingException;
327import java.security.cert.CertificateException;
328import java.text.SimpleDateFormat;
329import java.util.ArrayList;
330import java.util.Arrays;
331import java.util.Collection;
332import java.util.Collections;
333import java.util.Comparator;
334import java.util.Date;
335import java.util.HashMap;
336import java.util.HashSet;
337import java.util.Iterator;
338import java.util.List;
339import java.util.Map;
340import java.util.Objects;
341import java.util.Set;
342import java.util.concurrent.CountDownLatch;
343import java.util.concurrent.Future;
344import java.util.concurrent.TimeUnit;
345import java.util.concurrent.atomic.AtomicBoolean;
346import java.util.concurrent.atomic.AtomicInteger;
347import java.util.zip.GZIPInputStream;
348
349/**
350 * Keep track of all those APKs everywhere.
351 * <p>
352 * Internally there are two important locks:
353 * <ul>
354 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
355 * and other related state. It is a fine-grained lock that should only be held
356 * momentarily, as it's one of the most contended locks in the system.
357 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
358 * operations typically involve heavy lifting of application data on disk. Since
359 * {@code installd} is single-threaded, and it's operations can often be slow,
360 * this lock should never be acquired while already holding {@link #mPackages}.
361 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
362 * holding {@link #mInstallLock}.
363 * </ul>
364 * Many internal methods rely on the caller to hold the appropriate locks, and
365 * this contract is expressed through method name suffixes:
366 * <ul>
367 * <li>fooLI(): the caller must hold {@link #mInstallLock}
368 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
369 * being modified must be frozen
370 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
371 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
372 * </ul>
373 * <p>
374 * Because this class is very central to the platform's security; please run all
375 * CTS and unit tests whenever making modifications:
376 *
377 * <pre>
378 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
379 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
380 * </pre>
381 */
382public class PackageManagerService extends IPackageManager.Stub
383        implements PackageSender {
384    static final String TAG = "PackageManager";
385    static final boolean DEBUG_SETTINGS = false;
386    static final boolean DEBUG_PREFERRED = false;
387    static final boolean DEBUG_UPGRADE = false;
388    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
389    private static final boolean DEBUG_BACKUP = false;
390    private static final boolean DEBUG_INSTALL = false;
391    private static final boolean DEBUG_REMOVE = false;
392    private static final boolean DEBUG_BROADCASTS = false;
393    private static final boolean DEBUG_SHOW_INFO = false;
394    private static final boolean DEBUG_PACKAGE_INFO = false;
395    private static final boolean DEBUG_INTENT_MATCHING = false;
396    private static final boolean DEBUG_PACKAGE_SCANNING = false;
397    private static final boolean DEBUG_VERIFY = false;
398    private static final boolean DEBUG_FILTERS = false;
399    private static final boolean DEBUG_PERMISSIONS = false;
400    private static final boolean DEBUG_SHARED_LIBRARIES = false;
401    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
402
403    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
404    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
405    // user, but by default initialize to this.
406    public static final boolean DEBUG_DEXOPT = false;
407
408    private static final boolean DEBUG_ABI_SELECTION = false;
409    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
410    private static final boolean DEBUG_TRIAGED_MISSING = false;
411    private static final boolean DEBUG_APP_DATA = false;
412
413    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
414    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
415
416    private static final boolean HIDE_EPHEMERAL_APIS = false;
417
418    private static final boolean ENABLE_FREE_CACHE_V2 =
419            SystemProperties.getBoolean("fw.free_cache_v2", true);
420
421    private static final int RADIO_UID = Process.PHONE_UID;
422    private static final int LOG_UID = Process.LOG_UID;
423    private static final int NFC_UID = Process.NFC_UID;
424    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
425    private static final int SHELL_UID = Process.SHELL_UID;
426
427    // Cap the size of permission trees that 3rd party apps can define
428    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
429
430    // Suffix used during package installation when copying/moving
431    // package apks to install directory.
432    private static final String INSTALL_PACKAGE_SUFFIX = "-";
433
434    static final int SCAN_NO_DEX = 1<<1;
435    static final int SCAN_FORCE_DEX = 1<<2;
436    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
437    static final int SCAN_NEW_INSTALL = 1<<4;
438    static final int SCAN_UPDATE_TIME = 1<<5;
439    static final int SCAN_BOOTING = 1<<6;
440    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
441    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
442    static final int SCAN_REPLACING = 1<<9;
443    static final int SCAN_REQUIRE_KNOWN = 1<<10;
444    static final int SCAN_MOVE = 1<<11;
445    static final int SCAN_INITIAL = 1<<12;
446    static final int SCAN_CHECK_ONLY = 1<<13;
447    static final int SCAN_DONT_KILL_APP = 1<<14;
448    static final int SCAN_IGNORE_FROZEN = 1<<15;
449    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
450    static final int SCAN_AS_INSTANT_APP = 1<<17;
451    static final int SCAN_AS_FULL_APP = 1<<18;
452    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
453    /** Should not be with the scan flags */
454    static final int FLAGS_REMOVE_CHATTY = 1<<31;
455
456    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
457    /** Extension of the compressed packages */
458    private final static String COMPRESSED_EXTENSION = ".gz";
459
460    private static final int[] EMPTY_INT_ARRAY = new int[0];
461
462    private static final int TYPE_UNKNOWN = 0;
463    private static final int TYPE_ACTIVITY = 1;
464    private static final int TYPE_RECEIVER = 2;
465    private static final int TYPE_SERVICE = 3;
466    private static final int TYPE_PROVIDER = 4;
467    @IntDef(prefix = { "TYPE_" }, value = {
468            TYPE_UNKNOWN,
469            TYPE_ACTIVITY,
470            TYPE_RECEIVER,
471            TYPE_SERVICE,
472            TYPE_PROVIDER,
473    })
474    @Retention(RetentionPolicy.SOURCE)
475    public @interface ComponentType {}
476
477    /**
478     * Timeout (in milliseconds) after which the watchdog should declare that
479     * our handler thread is wedged.  The usual default for such things is one
480     * minute but we sometimes do very lengthy I/O operations on this thread,
481     * such as installing multi-gigabyte applications, so ours needs to be longer.
482     */
483    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
484
485    /**
486     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
487     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
488     * settings entry if available, otherwise we use the hardcoded default.  If it's been
489     * more than this long since the last fstrim, we force one during the boot sequence.
490     *
491     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
492     * one gets run at the next available charging+idle time.  This final mandatory
493     * no-fstrim check kicks in only of the other scheduling criteria is never met.
494     */
495    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
496
497    /**
498     * Whether verification is enabled by default.
499     */
500    private static final boolean DEFAULT_VERIFY_ENABLE = true;
501
502    /**
503     * The default maximum time to wait for the verification agent to return in
504     * milliseconds.
505     */
506    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
507
508    /**
509     * The default response for package verification timeout.
510     *
511     * This can be either PackageManager.VERIFICATION_ALLOW or
512     * PackageManager.VERIFICATION_REJECT.
513     */
514    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
515
516    static final String PLATFORM_PACKAGE_NAME = "android";
517
518    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
519
520    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
521            DEFAULT_CONTAINER_PACKAGE,
522            "com.android.defcontainer.DefaultContainerService");
523
524    private static final String KILL_APP_REASON_GIDS_CHANGED =
525            "permission grant or revoke changed gids";
526
527    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
528            "permissions revoked";
529
530    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
531
532    private static final String PACKAGE_SCHEME = "package";
533
534    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
535
536    /** Permission grant: not grant the permission. */
537    private static final int GRANT_DENIED = 1;
538
539    /** Permission grant: grant the permission as an install permission. */
540    private static final int GRANT_INSTALL = 2;
541
542    /** Permission grant: grant the permission as a runtime one. */
543    private static final int GRANT_RUNTIME = 3;
544
545    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
546    private static final int GRANT_UPGRADE = 4;
547
548    /** Canonical intent used to identify what counts as a "web browser" app */
549    private static final Intent sBrowserIntent;
550    static {
551        sBrowserIntent = new Intent();
552        sBrowserIntent.setAction(Intent.ACTION_VIEW);
553        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
554        sBrowserIntent.setData(Uri.parse("http:"));
555    }
556
557    /**
558     * The set of all protected actions [i.e. those actions for which a high priority
559     * intent filter is disallowed].
560     */
561    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
562    static {
563        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
564        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
565        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
566        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
567    }
568
569    // Compilation reasons.
570    public static final int REASON_FIRST_BOOT = 0;
571    public static final int REASON_BOOT = 1;
572    public static final int REASON_INSTALL = 2;
573    public static final int REASON_BACKGROUND_DEXOPT = 3;
574    public static final int REASON_AB_OTA = 4;
575    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
576
577    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
578
579    /** All dangerous permission names in the same order as the events in MetricsEvent */
580    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
581            Manifest.permission.READ_CALENDAR,
582            Manifest.permission.WRITE_CALENDAR,
583            Manifest.permission.CAMERA,
584            Manifest.permission.READ_CONTACTS,
585            Manifest.permission.WRITE_CONTACTS,
586            Manifest.permission.GET_ACCOUNTS,
587            Manifest.permission.ACCESS_FINE_LOCATION,
588            Manifest.permission.ACCESS_COARSE_LOCATION,
589            Manifest.permission.RECORD_AUDIO,
590            Manifest.permission.READ_PHONE_STATE,
591            Manifest.permission.CALL_PHONE,
592            Manifest.permission.READ_CALL_LOG,
593            Manifest.permission.WRITE_CALL_LOG,
594            Manifest.permission.ADD_VOICEMAIL,
595            Manifest.permission.USE_SIP,
596            Manifest.permission.PROCESS_OUTGOING_CALLS,
597            Manifest.permission.READ_CELL_BROADCASTS,
598            Manifest.permission.BODY_SENSORS,
599            Manifest.permission.SEND_SMS,
600            Manifest.permission.RECEIVE_SMS,
601            Manifest.permission.READ_SMS,
602            Manifest.permission.RECEIVE_WAP_PUSH,
603            Manifest.permission.RECEIVE_MMS,
604            Manifest.permission.READ_EXTERNAL_STORAGE,
605            Manifest.permission.WRITE_EXTERNAL_STORAGE,
606            Manifest.permission.READ_PHONE_NUMBERS,
607            Manifest.permission.ANSWER_PHONE_CALLS);
608
609
610    /**
611     * Version number for the package parser cache. Increment this whenever the format or
612     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
613     */
614    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
615
616    /**
617     * Whether the package parser cache is enabled.
618     */
619    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
620
621    final ServiceThread mHandlerThread;
622
623    final PackageHandler mHandler;
624
625    private final ProcessLoggingHandler mProcessLoggingHandler;
626
627    /**
628     * Messages for {@link #mHandler} that need to wait for system ready before
629     * being dispatched.
630     */
631    private ArrayList<Message> mPostSystemReadyMessages;
632
633    final int mSdkVersion = Build.VERSION.SDK_INT;
634
635    final Context mContext;
636    final boolean mFactoryTest;
637    final boolean mOnlyCore;
638    final DisplayMetrics mMetrics;
639    final int mDefParseFlags;
640    final String[] mSeparateProcesses;
641    final boolean mIsUpgrade;
642    final boolean mIsPreNUpgrade;
643    final boolean mIsPreNMR1Upgrade;
644
645    // Have we told the Activity Manager to whitelist the default container service by uid yet?
646    @GuardedBy("mPackages")
647    boolean mDefaultContainerWhitelisted = false;
648
649    @GuardedBy("mPackages")
650    private boolean mDexOptDialogShown;
651
652    /** The location for ASEC container files on internal storage. */
653    final String mAsecInternalPath;
654
655    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
656    // LOCK HELD.  Can be called with mInstallLock held.
657    @GuardedBy("mInstallLock")
658    final Installer mInstaller;
659
660    /** Directory where installed third-party apps stored */
661    final File mAppInstallDir;
662
663    /**
664     * Directory to which applications installed internally have their
665     * 32 bit native libraries copied.
666     */
667    private File mAppLib32InstallDir;
668
669    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
670    // apps.
671    final File mDrmAppPrivateInstallDir;
672
673    // ----------------------------------------------------------------
674
675    // Lock for state used when installing and doing other long running
676    // operations.  Methods that must be called with this lock held have
677    // the suffix "LI".
678    final Object mInstallLock = new Object();
679
680    // ----------------------------------------------------------------
681
682    // Keys are String (package name), values are Package.  This also serves
683    // as the lock for the global state.  Methods that must be called with
684    // this lock held have the prefix "LP".
685    @GuardedBy("mPackages")
686    final ArrayMap<String, PackageParser.Package> mPackages =
687            new ArrayMap<String, PackageParser.Package>();
688
689    final ArrayMap<String, Set<String>> mKnownCodebase =
690            new ArrayMap<String, Set<String>>();
691
692    // Keys are isolated uids and values are the uid of the application
693    // that created the isolated proccess.
694    @GuardedBy("mPackages")
695    final SparseIntArray mIsolatedOwners = new SparseIntArray();
696
697    /**
698     * Tracks new system packages [received in an OTA] that we expect to
699     * find updated user-installed versions. Keys are package name, values
700     * are package location.
701     */
702    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
703    /**
704     * Tracks high priority intent filters for protected actions. During boot, certain
705     * filter actions are protected and should never be allowed to have a high priority
706     * intent filter for them. However, there is one, and only one exception -- the
707     * setup wizard. It must be able to define a high priority intent filter for these
708     * actions to ensure there are no escapes from the wizard. We need to delay processing
709     * of these during boot as we need to look at all of the system packages in order
710     * to know which component is the setup wizard.
711     */
712    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
713    /**
714     * Whether or not processing protected filters should be deferred.
715     */
716    private boolean mDeferProtectedFilters = true;
717
718    /**
719     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
720     */
721    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
722    /**
723     * Whether or not system app permissions should be promoted from install to runtime.
724     */
725    boolean mPromoteSystemApps;
726
727    @GuardedBy("mPackages")
728    final Settings mSettings;
729
730    /**
731     * Set of package names that are currently "frozen", which means active
732     * surgery is being done on the code/data for that package. The platform
733     * will refuse to launch frozen packages to avoid race conditions.
734     *
735     * @see PackageFreezer
736     */
737    @GuardedBy("mPackages")
738    final ArraySet<String> mFrozenPackages = new ArraySet<>();
739
740    final ProtectedPackages mProtectedPackages;
741
742    @GuardedBy("mLoadedVolumes")
743    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
744
745    boolean mFirstBoot;
746
747    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
748
749    // System configuration read by SystemConfig.
750    final int[] mGlobalGids;
751    final SparseArray<ArraySet<String>> mSystemPermissions;
752    @GuardedBy("mAvailableFeatures")
753    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
754
755    // If mac_permissions.xml was found for seinfo labeling.
756    boolean mFoundPolicyFile;
757
758    private final InstantAppRegistry mInstantAppRegistry;
759
760    @GuardedBy("mPackages")
761    int mChangedPackagesSequenceNumber;
762    /**
763     * List of changed [installed, removed or updated] packages.
764     * mapping from user id -> sequence number -> package name
765     */
766    @GuardedBy("mPackages")
767    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
768    /**
769     * The sequence number of the last change to a package.
770     * mapping from user id -> package name -> sequence number
771     */
772    @GuardedBy("mPackages")
773    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
774
775    class PackageParserCallback implements PackageParser.Callback {
776        @Override public final boolean hasFeature(String feature) {
777            return PackageManagerService.this.hasSystemFeature(feature, 0);
778        }
779
780        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
781                Collection<PackageParser.Package> allPackages, String targetPackageName) {
782            List<PackageParser.Package> overlayPackages = null;
783            for (PackageParser.Package p : allPackages) {
784                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
785                    if (overlayPackages == null) {
786                        overlayPackages = new ArrayList<PackageParser.Package>();
787                    }
788                    overlayPackages.add(p);
789                }
790            }
791            if (overlayPackages != null) {
792                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
793                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
794                        return p1.mOverlayPriority - p2.mOverlayPriority;
795                    }
796                };
797                Collections.sort(overlayPackages, cmp);
798            }
799            return overlayPackages;
800        }
801
802        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
803                String targetPackageName, String targetPath) {
804            if ("android".equals(targetPackageName)) {
805                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
806                // native AssetManager.
807                return null;
808            }
809            List<PackageParser.Package> overlayPackages =
810                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
811            if (overlayPackages == null || overlayPackages.isEmpty()) {
812                return null;
813            }
814            List<String> overlayPathList = null;
815            for (PackageParser.Package overlayPackage : overlayPackages) {
816                if (targetPath == null) {
817                    if (overlayPathList == null) {
818                        overlayPathList = new ArrayList<String>();
819                    }
820                    overlayPathList.add(overlayPackage.baseCodePath);
821                    continue;
822                }
823
824                try {
825                    // Creates idmaps for system to parse correctly the Android manifest of the
826                    // target package.
827                    //
828                    // OverlayManagerService will update each of them with a correct gid from its
829                    // target package app id.
830                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
831                            UserHandle.getSharedAppGid(
832                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
833                    if (overlayPathList == null) {
834                        overlayPathList = new ArrayList<String>();
835                    }
836                    overlayPathList.add(overlayPackage.baseCodePath);
837                } catch (InstallerException e) {
838                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
839                            overlayPackage.baseCodePath);
840                }
841            }
842            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
843        }
844
845        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
846            synchronized (mPackages) {
847                return getStaticOverlayPathsLocked(
848                        mPackages.values(), targetPackageName, targetPath);
849            }
850        }
851
852        @Override public final String[] getOverlayApks(String targetPackageName) {
853            return getStaticOverlayPaths(targetPackageName, null);
854        }
855
856        @Override public final String[] getOverlayPaths(String targetPackageName,
857                String targetPath) {
858            return getStaticOverlayPaths(targetPackageName, targetPath);
859        }
860    };
861
862    class ParallelPackageParserCallback extends PackageParserCallback {
863        List<PackageParser.Package> mOverlayPackages = null;
864
865        void findStaticOverlayPackages() {
866            synchronized (mPackages) {
867                for (PackageParser.Package p : mPackages.values()) {
868                    if (p.mIsStaticOverlay) {
869                        if (mOverlayPackages == null) {
870                            mOverlayPackages = new ArrayList<PackageParser.Package>();
871                        }
872                        mOverlayPackages.add(p);
873                    }
874                }
875            }
876        }
877
878        @Override
879        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
880            // We can trust mOverlayPackages without holding mPackages because package uninstall
881            // can't happen while running parallel parsing.
882            // Moreover holding mPackages on each parsing thread causes dead-lock.
883            return mOverlayPackages == null ? null :
884                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
885        }
886    }
887
888    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
889    final ParallelPackageParserCallback mParallelPackageParserCallback =
890            new ParallelPackageParserCallback();
891
892    public static final class SharedLibraryEntry {
893        public final @Nullable String path;
894        public final @Nullable String apk;
895        public final @NonNull SharedLibraryInfo info;
896
897        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
898                String declaringPackageName, int declaringPackageVersionCode) {
899            path = _path;
900            apk = _apk;
901            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
902                    declaringPackageName, declaringPackageVersionCode), null);
903        }
904    }
905
906    // Currently known shared libraries.
907    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
908    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
909            new ArrayMap<>();
910
911    // All available activities, for your resolving pleasure.
912    final ActivityIntentResolver mActivities =
913            new ActivityIntentResolver();
914
915    // All available receivers, for your resolving pleasure.
916    final ActivityIntentResolver mReceivers =
917            new ActivityIntentResolver();
918
919    // All available services, for your resolving pleasure.
920    final ServiceIntentResolver mServices = new ServiceIntentResolver();
921
922    // All available providers, for your resolving pleasure.
923    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
924
925    // Mapping from provider base names (first directory in content URI codePath)
926    // to the provider information.
927    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
928            new ArrayMap<String, PackageParser.Provider>();
929
930    // Mapping from instrumentation class names to info about them.
931    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
932            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
933
934    // Mapping from permission names to info about them.
935    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
936            new ArrayMap<String, PackageParser.PermissionGroup>();
937
938    // Packages whose data we have transfered into another package, thus
939    // should no longer exist.
940    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
941
942    // Broadcast actions that are only available to the system.
943    @GuardedBy("mProtectedBroadcasts")
944    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
945
946    /** List of packages waiting for verification. */
947    final SparseArray<PackageVerificationState> mPendingVerification
948            = new SparseArray<PackageVerificationState>();
949
950    /** Set of packages associated with each app op permission. */
951    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
952
953    final PackageInstallerService mInstallerService;
954
955    private final PackageDexOptimizer mPackageDexOptimizer;
956    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
957    // is used by other apps).
958    private final DexManager mDexManager;
959
960    private AtomicInteger mNextMoveId = new AtomicInteger();
961    private final MoveCallbacks mMoveCallbacks;
962
963    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
964
965    // Cache of users who need badging.
966    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
967
968    /** Token for keys in mPendingVerification. */
969    private int mPendingVerificationToken = 0;
970
971    volatile boolean mSystemReady;
972    volatile boolean mSafeMode;
973    volatile boolean mHasSystemUidErrors;
974    private volatile boolean mEphemeralAppsDisabled;
975
976    ApplicationInfo mAndroidApplication;
977    final ActivityInfo mResolveActivity = new ActivityInfo();
978    final ResolveInfo mResolveInfo = new ResolveInfo();
979    ComponentName mResolveComponentName;
980    PackageParser.Package mPlatformPackage;
981    ComponentName mCustomResolverComponentName;
982
983    boolean mResolverReplaced = false;
984
985    private final @Nullable ComponentName mIntentFilterVerifierComponent;
986    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
987
988    private int mIntentFilterVerificationToken = 0;
989
990    /** The service connection to the ephemeral resolver */
991    final EphemeralResolverConnection mInstantAppResolverConnection;
992    /** Component used to show resolver settings for Instant Apps */
993    final ComponentName mInstantAppResolverSettingsComponent;
994
995    /** Activity used to install instant applications */
996    ActivityInfo mInstantAppInstallerActivity;
997    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
998
999    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1000            = new SparseArray<IntentFilterVerificationState>();
1001
1002    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1003
1004    // List of packages names to keep cached, even if they are uninstalled for all users
1005    private List<String> mKeepUninstalledPackages;
1006
1007    private UserManagerInternal mUserManagerInternal;
1008
1009    private DeviceIdleController.LocalService mDeviceIdleController;
1010
1011    private File mCacheDir;
1012
1013    private ArraySet<String> mPrivappPermissionsViolations;
1014
1015    private Future<?> mPrepareAppDataFuture;
1016
1017    private static class IFVerificationParams {
1018        PackageParser.Package pkg;
1019        boolean replacing;
1020        int userId;
1021        int verifierUid;
1022
1023        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1024                int _userId, int _verifierUid) {
1025            pkg = _pkg;
1026            replacing = _replacing;
1027            userId = _userId;
1028            replacing = _replacing;
1029            verifierUid = _verifierUid;
1030        }
1031    }
1032
1033    private interface IntentFilterVerifier<T extends IntentFilter> {
1034        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1035                                               T filter, String packageName);
1036        void startVerifications(int userId);
1037        void receiveVerificationResponse(int verificationId);
1038    }
1039
1040    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1041        private Context mContext;
1042        private ComponentName mIntentFilterVerifierComponent;
1043        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1044
1045        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1046            mContext = context;
1047            mIntentFilterVerifierComponent = verifierComponent;
1048        }
1049
1050        private String getDefaultScheme() {
1051            return IntentFilter.SCHEME_HTTPS;
1052        }
1053
1054        @Override
1055        public void startVerifications(int userId) {
1056            // Launch verifications requests
1057            int count = mCurrentIntentFilterVerifications.size();
1058            for (int n=0; n<count; n++) {
1059                int verificationId = mCurrentIntentFilterVerifications.get(n);
1060                final IntentFilterVerificationState ivs =
1061                        mIntentFilterVerificationStates.get(verificationId);
1062
1063                String packageName = ivs.getPackageName();
1064
1065                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1066                final int filterCount = filters.size();
1067                ArraySet<String> domainsSet = new ArraySet<>();
1068                for (int m=0; m<filterCount; m++) {
1069                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1070                    domainsSet.addAll(filter.getHostsList());
1071                }
1072                synchronized (mPackages) {
1073                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1074                            packageName, domainsSet) != null) {
1075                        scheduleWriteSettingsLocked();
1076                    }
1077                }
1078                sendVerificationRequest(verificationId, ivs);
1079            }
1080            mCurrentIntentFilterVerifications.clear();
1081        }
1082
1083        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1084            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1085            verificationIntent.putExtra(
1086                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1087                    verificationId);
1088            verificationIntent.putExtra(
1089                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1090                    getDefaultScheme());
1091            verificationIntent.putExtra(
1092                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1093                    ivs.getHostsString());
1094            verificationIntent.putExtra(
1095                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1096                    ivs.getPackageName());
1097            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1098            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1099
1100            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1101            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1102                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1103                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1104
1105            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1106            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1107                    "Sending IntentFilter verification broadcast");
1108        }
1109
1110        public void receiveVerificationResponse(int verificationId) {
1111            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1112
1113            final boolean verified = ivs.isVerified();
1114
1115            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1116            final int count = filters.size();
1117            if (DEBUG_DOMAIN_VERIFICATION) {
1118                Slog.i(TAG, "Received verification response " + verificationId
1119                        + " for " + count + " filters, verified=" + verified);
1120            }
1121            for (int n=0; n<count; n++) {
1122                PackageParser.ActivityIntentInfo filter = filters.get(n);
1123                filter.setVerified(verified);
1124
1125                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1126                        + " verified with result:" + verified + " and hosts:"
1127                        + ivs.getHostsString());
1128            }
1129
1130            mIntentFilterVerificationStates.remove(verificationId);
1131
1132            final String packageName = ivs.getPackageName();
1133            IntentFilterVerificationInfo ivi = null;
1134
1135            synchronized (mPackages) {
1136                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1137            }
1138            if (ivi == null) {
1139                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1140                        + verificationId + " packageName:" + packageName);
1141                return;
1142            }
1143            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1144                    "Updating IntentFilterVerificationInfo for package " + packageName
1145                            +" verificationId:" + verificationId);
1146
1147            synchronized (mPackages) {
1148                if (verified) {
1149                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1150                } else {
1151                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1152                }
1153                scheduleWriteSettingsLocked();
1154
1155                final int userId = ivs.getUserId();
1156                if (userId != UserHandle.USER_ALL) {
1157                    final int userStatus =
1158                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1159
1160                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1161                    boolean needUpdate = false;
1162
1163                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1164                    // already been set by the User thru the Disambiguation dialog
1165                    switch (userStatus) {
1166                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1167                            if (verified) {
1168                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1169                            } else {
1170                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1171                            }
1172                            needUpdate = true;
1173                            break;
1174
1175                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1176                            if (verified) {
1177                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1178                                needUpdate = true;
1179                            }
1180                            break;
1181
1182                        default:
1183                            // Nothing to do
1184                    }
1185
1186                    if (needUpdate) {
1187                        mSettings.updateIntentFilterVerificationStatusLPw(
1188                                packageName, updatedStatus, userId);
1189                        scheduleWritePackageRestrictionsLocked(userId);
1190                    }
1191                }
1192            }
1193        }
1194
1195        @Override
1196        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1197                    ActivityIntentInfo filter, String packageName) {
1198            if (!hasValidDomains(filter)) {
1199                return false;
1200            }
1201            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1202            if (ivs == null) {
1203                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1204                        packageName);
1205            }
1206            if (DEBUG_DOMAIN_VERIFICATION) {
1207                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1208            }
1209            ivs.addFilter(filter);
1210            return true;
1211        }
1212
1213        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1214                int userId, int verificationId, String packageName) {
1215            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1216                    verifierUid, userId, packageName);
1217            ivs.setPendingState();
1218            synchronized (mPackages) {
1219                mIntentFilterVerificationStates.append(verificationId, ivs);
1220                mCurrentIntentFilterVerifications.add(verificationId);
1221            }
1222            return ivs;
1223        }
1224    }
1225
1226    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1227        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1228                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1229                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1230    }
1231
1232    // Set of pending broadcasts for aggregating enable/disable of components.
1233    static class PendingPackageBroadcasts {
1234        // for each user id, a map of <package name -> components within that package>
1235        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1236
1237        public PendingPackageBroadcasts() {
1238            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1239        }
1240
1241        public ArrayList<String> get(int userId, String packageName) {
1242            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1243            return packages.get(packageName);
1244        }
1245
1246        public void put(int userId, String packageName, ArrayList<String> components) {
1247            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1248            packages.put(packageName, components);
1249        }
1250
1251        public void remove(int userId, String packageName) {
1252            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1253            if (packages != null) {
1254                packages.remove(packageName);
1255            }
1256        }
1257
1258        public void remove(int userId) {
1259            mUidMap.remove(userId);
1260        }
1261
1262        public int userIdCount() {
1263            return mUidMap.size();
1264        }
1265
1266        public int userIdAt(int n) {
1267            return mUidMap.keyAt(n);
1268        }
1269
1270        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1271            return mUidMap.get(userId);
1272        }
1273
1274        public int size() {
1275            // total number of pending broadcast entries across all userIds
1276            int num = 0;
1277            for (int i = 0; i< mUidMap.size(); i++) {
1278                num += mUidMap.valueAt(i).size();
1279            }
1280            return num;
1281        }
1282
1283        public void clear() {
1284            mUidMap.clear();
1285        }
1286
1287        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1288            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1289            if (map == null) {
1290                map = new ArrayMap<String, ArrayList<String>>();
1291                mUidMap.put(userId, map);
1292            }
1293            return map;
1294        }
1295    }
1296    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1297
1298    // Service Connection to remote media container service to copy
1299    // package uri's from external media onto secure containers
1300    // or internal storage.
1301    private IMediaContainerService mContainerService = null;
1302
1303    static final int SEND_PENDING_BROADCAST = 1;
1304    static final int MCS_BOUND = 3;
1305    static final int END_COPY = 4;
1306    static final int INIT_COPY = 5;
1307    static final int MCS_UNBIND = 6;
1308    static final int START_CLEANING_PACKAGE = 7;
1309    static final int FIND_INSTALL_LOC = 8;
1310    static final int POST_INSTALL = 9;
1311    static final int MCS_RECONNECT = 10;
1312    static final int MCS_GIVE_UP = 11;
1313    static final int UPDATED_MEDIA_STATUS = 12;
1314    static final int WRITE_SETTINGS = 13;
1315    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1316    static final int PACKAGE_VERIFIED = 15;
1317    static final int CHECK_PENDING_VERIFICATION = 16;
1318    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1319    static final int INTENT_FILTER_VERIFIED = 18;
1320    static final int WRITE_PACKAGE_LIST = 19;
1321    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1322
1323    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1324
1325    // Delay time in millisecs
1326    static final int BROADCAST_DELAY = 10 * 1000;
1327
1328    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1329            2 * 60 * 60 * 1000L; /* two hours */
1330
1331    static UserManagerService sUserManager;
1332
1333    // Stores a list of users whose package restrictions file needs to be updated
1334    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1335
1336    final private DefaultContainerConnection mDefContainerConn =
1337            new DefaultContainerConnection();
1338    class DefaultContainerConnection implements ServiceConnection {
1339        public void onServiceConnected(ComponentName name, IBinder service) {
1340            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1341            final IMediaContainerService imcs = IMediaContainerService.Stub
1342                    .asInterface(Binder.allowBlocking(service));
1343            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1344        }
1345
1346        public void onServiceDisconnected(ComponentName name) {
1347            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1348        }
1349    }
1350
1351    // Recordkeeping of restore-after-install operations that are currently in flight
1352    // between the Package Manager and the Backup Manager
1353    static class PostInstallData {
1354        public InstallArgs args;
1355        public PackageInstalledInfo res;
1356
1357        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1358            args = _a;
1359            res = _r;
1360        }
1361    }
1362
1363    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1364    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1365
1366    // XML tags for backup/restore of various bits of state
1367    private static final String TAG_PREFERRED_BACKUP = "pa";
1368    private static final String TAG_DEFAULT_APPS = "da";
1369    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1370
1371    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1372    private static final String TAG_ALL_GRANTS = "rt-grants";
1373    private static final String TAG_GRANT = "grant";
1374    private static final String ATTR_PACKAGE_NAME = "pkg";
1375
1376    private static final String TAG_PERMISSION = "perm";
1377    private static final String ATTR_PERMISSION_NAME = "name";
1378    private static final String ATTR_IS_GRANTED = "g";
1379    private static final String ATTR_USER_SET = "set";
1380    private static final String ATTR_USER_FIXED = "fixed";
1381    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1382
1383    // System/policy permission grants are not backed up
1384    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1385            FLAG_PERMISSION_POLICY_FIXED
1386            | FLAG_PERMISSION_SYSTEM_FIXED
1387            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1388
1389    // And we back up these user-adjusted states
1390    private static final int USER_RUNTIME_GRANT_MASK =
1391            FLAG_PERMISSION_USER_SET
1392            | FLAG_PERMISSION_USER_FIXED
1393            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1394
1395    final @Nullable String mRequiredVerifierPackage;
1396    final @NonNull String mRequiredInstallerPackage;
1397    final @NonNull String mRequiredUninstallerPackage;
1398    final @Nullable String mSetupWizardPackage;
1399    final @Nullable String mStorageManagerPackage;
1400    final @NonNull String mServicesSystemSharedLibraryPackageName;
1401    final @NonNull String mSharedSystemSharedLibraryPackageName;
1402
1403    final boolean mPermissionReviewRequired;
1404
1405    private final PackageUsage mPackageUsage = new PackageUsage();
1406    private final CompilerStats mCompilerStats = new CompilerStats();
1407
1408    class PackageHandler extends Handler {
1409        private boolean mBound = false;
1410        final ArrayList<HandlerParams> mPendingInstalls =
1411            new ArrayList<HandlerParams>();
1412
1413        private boolean connectToService() {
1414            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1415                    " DefaultContainerService");
1416            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1417            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1418            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1419                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1420                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1421                mBound = true;
1422                return true;
1423            }
1424            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1425            return false;
1426        }
1427
1428        private void disconnectService() {
1429            mContainerService = null;
1430            mBound = false;
1431            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1432            mContext.unbindService(mDefContainerConn);
1433            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1434        }
1435
1436        PackageHandler(Looper looper) {
1437            super(looper);
1438        }
1439
1440        public void handleMessage(Message msg) {
1441            try {
1442                doHandleMessage(msg);
1443            } finally {
1444                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1445            }
1446        }
1447
1448        void doHandleMessage(Message msg) {
1449            switch (msg.what) {
1450                case INIT_COPY: {
1451                    HandlerParams params = (HandlerParams) msg.obj;
1452                    int idx = mPendingInstalls.size();
1453                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1454                    // If a bind was already initiated we dont really
1455                    // need to do anything. The pending install
1456                    // will be processed later on.
1457                    if (!mBound) {
1458                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1459                                System.identityHashCode(mHandler));
1460                        // If this is the only one pending we might
1461                        // have to bind to the service again.
1462                        if (!connectToService()) {
1463                            Slog.e(TAG, "Failed to bind to media container service");
1464                            params.serviceError();
1465                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1466                                    System.identityHashCode(mHandler));
1467                            if (params.traceMethod != null) {
1468                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1469                                        params.traceCookie);
1470                            }
1471                            return;
1472                        } else {
1473                            // Once we bind to the service, the first
1474                            // pending request will be processed.
1475                            mPendingInstalls.add(idx, params);
1476                        }
1477                    } else {
1478                        mPendingInstalls.add(idx, params);
1479                        // Already bound to the service. Just make
1480                        // sure we trigger off processing the first request.
1481                        if (idx == 0) {
1482                            mHandler.sendEmptyMessage(MCS_BOUND);
1483                        }
1484                    }
1485                    break;
1486                }
1487                case MCS_BOUND: {
1488                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1489                    if (msg.obj != null) {
1490                        mContainerService = (IMediaContainerService) msg.obj;
1491                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1492                                System.identityHashCode(mHandler));
1493                    }
1494                    if (mContainerService == null) {
1495                        if (!mBound) {
1496                            // Something seriously wrong since we are not bound and we are not
1497                            // waiting for connection. Bail out.
1498                            Slog.e(TAG, "Cannot bind to media container service");
1499                            for (HandlerParams params : mPendingInstalls) {
1500                                // Indicate service bind error
1501                                params.serviceError();
1502                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1503                                        System.identityHashCode(params));
1504                                if (params.traceMethod != null) {
1505                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1506                                            params.traceMethod, params.traceCookie);
1507                                }
1508                                return;
1509                            }
1510                            mPendingInstalls.clear();
1511                        } else {
1512                            Slog.w(TAG, "Waiting to connect to media container service");
1513                        }
1514                    } else if (mPendingInstalls.size() > 0) {
1515                        HandlerParams params = mPendingInstalls.get(0);
1516                        if (params != null) {
1517                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1518                                    System.identityHashCode(params));
1519                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1520                            if (params.startCopy()) {
1521                                // We are done...  look for more work or to
1522                                // go idle.
1523                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1524                                        "Checking for more work or unbind...");
1525                                // Delete pending install
1526                                if (mPendingInstalls.size() > 0) {
1527                                    mPendingInstalls.remove(0);
1528                                }
1529                                if (mPendingInstalls.size() == 0) {
1530                                    if (mBound) {
1531                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1532                                                "Posting delayed MCS_UNBIND");
1533                                        removeMessages(MCS_UNBIND);
1534                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1535                                        // Unbind after a little delay, to avoid
1536                                        // continual thrashing.
1537                                        sendMessageDelayed(ubmsg, 10000);
1538                                    }
1539                                } else {
1540                                    // There are more pending requests in queue.
1541                                    // Just post MCS_BOUND message to trigger processing
1542                                    // of next pending install.
1543                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1544                                            "Posting MCS_BOUND for next work");
1545                                    mHandler.sendEmptyMessage(MCS_BOUND);
1546                                }
1547                            }
1548                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1549                        }
1550                    } else {
1551                        // Should never happen ideally.
1552                        Slog.w(TAG, "Empty queue");
1553                    }
1554                    break;
1555                }
1556                case MCS_RECONNECT: {
1557                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1558                    if (mPendingInstalls.size() > 0) {
1559                        if (mBound) {
1560                            disconnectService();
1561                        }
1562                        if (!connectToService()) {
1563                            Slog.e(TAG, "Failed to bind to media container service");
1564                            for (HandlerParams params : mPendingInstalls) {
1565                                // Indicate service bind error
1566                                params.serviceError();
1567                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1568                                        System.identityHashCode(params));
1569                            }
1570                            mPendingInstalls.clear();
1571                        }
1572                    }
1573                    break;
1574                }
1575                case MCS_UNBIND: {
1576                    // If there is no actual work left, then time to unbind.
1577                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1578
1579                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1580                        if (mBound) {
1581                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1582
1583                            disconnectService();
1584                        }
1585                    } else if (mPendingInstalls.size() > 0) {
1586                        // There are more pending requests in queue.
1587                        // Just post MCS_BOUND message to trigger processing
1588                        // of next pending install.
1589                        mHandler.sendEmptyMessage(MCS_BOUND);
1590                    }
1591
1592                    break;
1593                }
1594                case MCS_GIVE_UP: {
1595                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1596                    HandlerParams params = mPendingInstalls.remove(0);
1597                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1598                            System.identityHashCode(params));
1599                    break;
1600                }
1601                case SEND_PENDING_BROADCAST: {
1602                    String packages[];
1603                    ArrayList<String> components[];
1604                    int size = 0;
1605                    int uids[];
1606                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1607                    synchronized (mPackages) {
1608                        if (mPendingBroadcasts == null) {
1609                            return;
1610                        }
1611                        size = mPendingBroadcasts.size();
1612                        if (size <= 0) {
1613                            // Nothing to be done. Just return
1614                            return;
1615                        }
1616                        packages = new String[size];
1617                        components = new ArrayList[size];
1618                        uids = new int[size];
1619                        int i = 0;  // filling out the above arrays
1620
1621                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1622                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1623                            Iterator<Map.Entry<String, ArrayList<String>>> it
1624                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1625                                            .entrySet().iterator();
1626                            while (it.hasNext() && i < size) {
1627                                Map.Entry<String, ArrayList<String>> ent = it.next();
1628                                packages[i] = ent.getKey();
1629                                components[i] = ent.getValue();
1630                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1631                                uids[i] = (ps != null)
1632                                        ? UserHandle.getUid(packageUserId, ps.appId)
1633                                        : -1;
1634                                i++;
1635                            }
1636                        }
1637                        size = i;
1638                        mPendingBroadcasts.clear();
1639                    }
1640                    // Send broadcasts
1641                    for (int i = 0; i < size; i++) {
1642                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1643                    }
1644                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1645                    break;
1646                }
1647                case START_CLEANING_PACKAGE: {
1648                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1649                    final String packageName = (String)msg.obj;
1650                    final int userId = msg.arg1;
1651                    final boolean andCode = msg.arg2 != 0;
1652                    synchronized (mPackages) {
1653                        if (userId == UserHandle.USER_ALL) {
1654                            int[] users = sUserManager.getUserIds();
1655                            for (int user : users) {
1656                                mSettings.addPackageToCleanLPw(
1657                                        new PackageCleanItem(user, packageName, andCode));
1658                            }
1659                        } else {
1660                            mSettings.addPackageToCleanLPw(
1661                                    new PackageCleanItem(userId, packageName, andCode));
1662                        }
1663                    }
1664                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1665                    startCleaningPackages();
1666                } break;
1667                case POST_INSTALL: {
1668                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1669
1670                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1671                    final boolean didRestore = (msg.arg2 != 0);
1672                    mRunningInstalls.delete(msg.arg1);
1673
1674                    if (data != null) {
1675                        InstallArgs args = data.args;
1676                        PackageInstalledInfo parentRes = data.res;
1677
1678                        final boolean grantPermissions = (args.installFlags
1679                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1680                        final boolean killApp = (args.installFlags
1681                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1682                        final boolean virtualPreload = ((args.installFlags
1683                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1684                        final String[] grantedPermissions = args.installGrantPermissions;
1685
1686                        // Handle the parent package
1687                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1688                                virtualPreload, grantedPermissions, didRestore,
1689                                args.installerPackageName, args.observer);
1690
1691                        // Handle the child packages
1692                        final int childCount = (parentRes.addedChildPackages != null)
1693                                ? parentRes.addedChildPackages.size() : 0;
1694                        for (int i = 0; i < childCount; i++) {
1695                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1696                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1697                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1698                                    args.installerPackageName, args.observer);
1699                        }
1700
1701                        // Log tracing if needed
1702                        if (args.traceMethod != null) {
1703                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1704                                    args.traceCookie);
1705                        }
1706                    } else {
1707                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1708                    }
1709
1710                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1711                } break;
1712                case UPDATED_MEDIA_STATUS: {
1713                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1714                    boolean reportStatus = msg.arg1 == 1;
1715                    boolean doGc = msg.arg2 == 1;
1716                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1717                    if (doGc) {
1718                        // Force a gc to clear up stale containers.
1719                        Runtime.getRuntime().gc();
1720                    }
1721                    if (msg.obj != null) {
1722                        @SuppressWarnings("unchecked")
1723                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1724                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1725                        // Unload containers
1726                        unloadAllContainers(args);
1727                    }
1728                    if (reportStatus) {
1729                        try {
1730                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1731                                    "Invoking StorageManagerService call back");
1732                            PackageHelper.getStorageManager().finishMediaUpdate();
1733                        } catch (RemoteException e) {
1734                            Log.e(TAG, "StorageManagerService not running?");
1735                        }
1736                    }
1737                } break;
1738                case WRITE_SETTINGS: {
1739                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1740                    synchronized (mPackages) {
1741                        removeMessages(WRITE_SETTINGS);
1742                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1743                        mSettings.writeLPr();
1744                        mDirtyUsers.clear();
1745                    }
1746                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1747                } break;
1748                case WRITE_PACKAGE_RESTRICTIONS: {
1749                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1750                    synchronized (mPackages) {
1751                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1752                        for (int userId : mDirtyUsers) {
1753                            mSettings.writePackageRestrictionsLPr(userId);
1754                        }
1755                        mDirtyUsers.clear();
1756                    }
1757                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1758                } break;
1759                case WRITE_PACKAGE_LIST: {
1760                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1761                    synchronized (mPackages) {
1762                        removeMessages(WRITE_PACKAGE_LIST);
1763                        mSettings.writePackageListLPr(msg.arg1);
1764                    }
1765                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1766                } break;
1767                case CHECK_PENDING_VERIFICATION: {
1768                    final int verificationId = msg.arg1;
1769                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1770
1771                    if ((state != null) && !state.timeoutExtended()) {
1772                        final InstallArgs args = state.getInstallArgs();
1773                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1774
1775                        Slog.i(TAG, "Verification timed out for " + originUri);
1776                        mPendingVerification.remove(verificationId);
1777
1778                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1779
1780                        final UserHandle user = args.getUser();
1781                        if (getDefaultVerificationResponse(user)
1782                                == PackageManager.VERIFICATION_ALLOW) {
1783                            Slog.i(TAG, "Continuing with installation of " + originUri);
1784                            state.setVerifierResponse(Binder.getCallingUid(),
1785                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1786                            broadcastPackageVerified(verificationId, originUri,
1787                                    PackageManager.VERIFICATION_ALLOW, user);
1788                            try {
1789                                ret = args.copyApk(mContainerService, true);
1790                            } catch (RemoteException e) {
1791                                Slog.e(TAG, "Could not contact the ContainerService");
1792                            }
1793                        } else {
1794                            broadcastPackageVerified(verificationId, originUri,
1795                                    PackageManager.VERIFICATION_REJECT, user);
1796                        }
1797
1798                        Trace.asyncTraceEnd(
1799                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1800
1801                        processPendingInstall(args, ret);
1802                        mHandler.sendEmptyMessage(MCS_UNBIND);
1803                    }
1804                    break;
1805                }
1806                case PACKAGE_VERIFIED: {
1807                    final int verificationId = msg.arg1;
1808
1809                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1810                    if (state == null) {
1811                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1812                        break;
1813                    }
1814
1815                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1816
1817                    state.setVerifierResponse(response.callerUid, response.code);
1818
1819                    if (state.isVerificationComplete()) {
1820                        mPendingVerification.remove(verificationId);
1821
1822                        final InstallArgs args = state.getInstallArgs();
1823                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1824
1825                        int ret;
1826                        if (state.isInstallAllowed()) {
1827                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1828                            broadcastPackageVerified(verificationId, originUri,
1829                                    response.code, state.getInstallArgs().getUser());
1830                            try {
1831                                ret = args.copyApk(mContainerService, true);
1832                            } catch (RemoteException e) {
1833                                Slog.e(TAG, "Could not contact the ContainerService");
1834                            }
1835                        } else {
1836                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1837                        }
1838
1839                        Trace.asyncTraceEnd(
1840                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1841
1842                        processPendingInstall(args, ret);
1843                        mHandler.sendEmptyMessage(MCS_UNBIND);
1844                    }
1845
1846                    break;
1847                }
1848                case START_INTENT_FILTER_VERIFICATIONS: {
1849                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1850                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1851                            params.replacing, params.pkg);
1852                    break;
1853                }
1854                case INTENT_FILTER_VERIFIED: {
1855                    final int verificationId = msg.arg1;
1856
1857                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1858                            verificationId);
1859                    if (state == null) {
1860                        Slog.w(TAG, "Invalid IntentFilter verification token "
1861                                + verificationId + " received");
1862                        break;
1863                    }
1864
1865                    final int userId = state.getUserId();
1866
1867                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1868                            "Processing IntentFilter verification with token:"
1869                            + verificationId + " and userId:" + userId);
1870
1871                    final IntentFilterVerificationResponse response =
1872                            (IntentFilterVerificationResponse) msg.obj;
1873
1874                    state.setVerifierResponse(response.callerUid, response.code);
1875
1876                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1877                            "IntentFilter verification with token:" + verificationId
1878                            + " and userId:" + userId
1879                            + " is settings verifier response with response code:"
1880                            + response.code);
1881
1882                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1883                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1884                                + response.getFailedDomainsString());
1885                    }
1886
1887                    if (state.isVerificationComplete()) {
1888                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1889                    } else {
1890                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1891                                "IntentFilter verification with token:" + verificationId
1892                                + " was not said to be complete");
1893                    }
1894
1895                    break;
1896                }
1897                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1898                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1899                            mInstantAppResolverConnection,
1900                            (InstantAppRequest) msg.obj,
1901                            mInstantAppInstallerActivity,
1902                            mHandler);
1903                }
1904            }
1905        }
1906    }
1907
1908    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1909            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1910            boolean launchedForRestore, String installerPackage,
1911            IPackageInstallObserver2 installObserver) {
1912        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1913            // Send the removed broadcasts
1914            if (res.removedInfo != null) {
1915                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1916            }
1917
1918            // Now that we successfully installed the package, grant runtime
1919            // permissions if requested before broadcasting the install. Also
1920            // for legacy apps in permission review mode we clear the permission
1921            // review flag which is used to emulate runtime permissions for
1922            // legacy apps.
1923            if (grantPermissions) {
1924                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1925            }
1926
1927            final boolean update = res.removedInfo != null
1928                    && res.removedInfo.removedPackage != null;
1929            final String origInstallerPackageName = res.removedInfo != null
1930                    ? res.removedInfo.installerPackageName : null;
1931
1932            // If this is the first time we have child packages for a disabled privileged
1933            // app that had no children, we grant requested runtime permissions to the new
1934            // children if the parent on the system image had them already granted.
1935            if (res.pkg.parentPackage != null) {
1936                synchronized (mPackages) {
1937                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1938                }
1939            }
1940
1941            synchronized (mPackages) {
1942                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1943            }
1944
1945            final String packageName = res.pkg.applicationInfo.packageName;
1946
1947            // Determine the set of users who are adding this package for
1948            // the first time vs. those who are seeing an update.
1949            int[] firstUsers = EMPTY_INT_ARRAY;
1950            int[] updateUsers = EMPTY_INT_ARRAY;
1951            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1952            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1953            for (int newUser : res.newUsers) {
1954                if (ps.getInstantApp(newUser)) {
1955                    continue;
1956                }
1957                if (allNewUsers) {
1958                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1959                    continue;
1960                }
1961                boolean isNew = true;
1962                for (int origUser : res.origUsers) {
1963                    if (origUser == newUser) {
1964                        isNew = false;
1965                        break;
1966                    }
1967                }
1968                if (isNew) {
1969                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1970                } else {
1971                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1972                }
1973            }
1974
1975            // Send installed broadcasts if the package is not a static shared lib.
1976            if (res.pkg.staticSharedLibName == null) {
1977                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1978
1979                // Send added for users that see the package for the first time
1980                // sendPackageAddedForNewUsers also deals with system apps
1981                int appId = UserHandle.getAppId(res.uid);
1982                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1983                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1984                        virtualPreload /*startReceiver*/, appId, firstUsers);
1985
1986                // Send added for users that don't see the package for the first time
1987                Bundle extras = new Bundle(1);
1988                extras.putInt(Intent.EXTRA_UID, res.uid);
1989                if (update) {
1990                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1991                }
1992                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1993                        extras, 0 /*flags*/,
1994                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1995                if (origInstallerPackageName != null) {
1996                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1997                            extras, 0 /*flags*/,
1998                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1999                }
2000
2001                // Send replaced for users that don't see the package for the first time
2002                if (update) {
2003                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2004                            packageName, extras, 0 /*flags*/,
2005                            null /*targetPackage*/, null /*finishedReceiver*/,
2006                            updateUsers);
2007                    if (origInstallerPackageName != null) {
2008                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2009                                extras, 0 /*flags*/,
2010                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
2011                    }
2012                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2013                            null /*package*/, null /*extras*/, 0 /*flags*/,
2014                            packageName /*targetPackage*/,
2015                            null /*finishedReceiver*/, updateUsers);
2016                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2017                    // First-install and we did a restore, so we're responsible for the
2018                    // first-launch broadcast.
2019                    if (DEBUG_BACKUP) {
2020                        Slog.i(TAG, "Post-restore of " + packageName
2021                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2022                    }
2023                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2024                }
2025
2026                // Send broadcast package appeared if forward locked/external for all users
2027                // treat asec-hosted packages like removable media on upgrade
2028                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2029                    if (DEBUG_INSTALL) {
2030                        Slog.i(TAG, "upgrading pkg " + res.pkg
2031                                + " is ASEC-hosted -> AVAILABLE");
2032                    }
2033                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2034                    ArrayList<String> pkgList = new ArrayList<>(1);
2035                    pkgList.add(packageName);
2036                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2037                }
2038            }
2039
2040            // Work that needs to happen on first install within each user
2041            if (firstUsers != null && firstUsers.length > 0) {
2042                synchronized (mPackages) {
2043                    for (int userId : firstUsers) {
2044                        // If this app is a browser and it's newly-installed for some
2045                        // users, clear any default-browser state in those users. The
2046                        // app's nature doesn't depend on the user, so we can just check
2047                        // its browser nature in any user and generalize.
2048                        if (packageIsBrowser(packageName, userId)) {
2049                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2050                        }
2051
2052                        // We may also need to apply pending (restored) runtime
2053                        // permission grants within these users.
2054                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2055                    }
2056                }
2057            }
2058
2059            // Log current value of "unknown sources" setting
2060            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2061                    getUnknownSourcesSettings());
2062
2063            // Remove the replaced package's older resources safely now
2064            // We delete after a gc for applications  on sdcard.
2065            if (res.removedInfo != null && res.removedInfo.args != null) {
2066                Runtime.getRuntime().gc();
2067                synchronized (mInstallLock) {
2068                    res.removedInfo.args.doPostDeleteLI(true);
2069                }
2070            } else {
2071                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2072                // and not block here.
2073                VMRuntime.getRuntime().requestConcurrentGC();
2074            }
2075
2076            // Notify DexManager that the package was installed for new users.
2077            // The updated users should already be indexed and the package code paths
2078            // should not change.
2079            // Don't notify the manager for ephemeral apps as they are not expected to
2080            // survive long enough to benefit of background optimizations.
2081            for (int userId : firstUsers) {
2082                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2083                // There's a race currently where some install events may interleave with an uninstall.
2084                // This can lead to package info being null (b/36642664).
2085                if (info != null) {
2086                    mDexManager.notifyPackageInstalled(info, userId);
2087                }
2088            }
2089        }
2090
2091        // If someone is watching installs - notify them
2092        if (installObserver != null) {
2093            try {
2094                Bundle extras = extrasForInstallResult(res);
2095                installObserver.onPackageInstalled(res.name, res.returnCode,
2096                        res.returnMsg, extras);
2097            } catch (RemoteException e) {
2098                Slog.i(TAG, "Observer no longer exists.");
2099            }
2100        }
2101    }
2102
2103    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2104            PackageParser.Package pkg) {
2105        if (pkg.parentPackage == null) {
2106            return;
2107        }
2108        if (pkg.requestedPermissions == null) {
2109            return;
2110        }
2111        final PackageSetting disabledSysParentPs = mSettings
2112                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2113        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2114                || !disabledSysParentPs.isPrivileged()
2115                || (disabledSysParentPs.childPackageNames != null
2116                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2117            return;
2118        }
2119        final int[] allUserIds = sUserManager.getUserIds();
2120        final int permCount = pkg.requestedPermissions.size();
2121        for (int i = 0; i < permCount; i++) {
2122            String permission = pkg.requestedPermissions.get(i);
2123            BasePermission bp = mSettings.mPermissions.get(permission);
2124            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2125                continue;
2126            }
2127            for (int userId : allUserIds) {
2128                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2129                        permission, userId)) {
2130                    grantRuntimePermission(pkg.packageName, permission, userId);
2131                }
2132            }
2133        }
2134    }
2135
2136    private StorageEventListener mStorageListener = new StorageEventListener() {
2137        @Override
2138        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2139            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2140                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2141                    final String volumeUuid = vol.getFsUuid();
2142
2143                    // Clean up any users or apps that were removed or recreated
2144                    // while this volume was missing
2145                    sUserManager.reconcileUsers(volumeUuid);
2146                    reconcileApps(volumeUuid);
2147
2148                    // Clean up any install sessions that expired or were
2149                    // cancelled while this volume was missing
2150                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2151
2152                    loadPrivatePackages(vol);
2153
2154                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2155                    unloadPrivatePackages(vol);
2156                }
2157            }
2158
2159            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2160                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2161                    updateExternalMediaStatus(true, false);
2162                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2163                    updateExternalMediaStatus(false, false);
2164                }
2165            }
2166        }
2167
2168        @Override
2169        public void onVolumeForgotten(String fsUuid) {
2170            if (TextUtils.isEmpty(fsUuid)) {
2171                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2172                return;
2173            }
2174
2175            // Remove any apps installed on the forgotten volume
2176            synchronized (mPackages) {
2177                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2178                for (PackageSetting ps : packages) {
2179                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2180                    deletePackageVersioned(new VersionedPackage(ps.name,
2181                            PackageManager.VERSION_CODE_HIGHEST),
2182                            new LegacyPackageDeleteObserver(null).getBinder(),
2183                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2184                    // Try very hard to release any references to this package
2185                    // so we don't risk the system server being killed due to
2186                    // open FDs
2187                    AttributeCache.instance().removePackage(ps.name);
2188                }
2189
2190                mSettings.onVolumeForgotten(fsUuid);
2191                mSettings.writeLPr();
2192            }
2193        }
2194    };
2195
2196    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2197            String[] grantedPermissions) {
2198        for (int userId : userIds) {
2199            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2200        }
2201    }
2202
2203    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2204            String[] grantedPermissions) {
2205        PackageSetting ps = (PackageSetting) pkg.mExtras;
2206        if (ps == null) {
2207            return;
2208        }
2209
2210        PermissionsState permissionsState = ps.getPermissionsState();
2211
2212        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2213                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2214
2215        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2216                >= Build.VERSION_CODES.M;
2217
2218        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2219
2220        for (String permission : pkg.requestedPermissions) {
2221            final BasePermission bp;
2222            synchronized (mPackages) {
2223                bp = mSettings.mPermissions.get(permission);
2224            }
2225            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2226                    && (!instantApp || bp.isInstant())
2227                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2228                    && (grantedPermissions == null
2229                           || ArrayUtils.contains(grantedPermissions, permission))) {
2230                final int flags = permissionsState.getPermissionFlags(permission, userId);
2231                if (supportsRuntimePermissions) {
2232                    // Installer cannot change immutable permissions.
2233                    if ((flags & immutableFlags) == 0) {
2234                        grantRuntimePermission(pkg.packageName, permission, userId);
2235                    }
2236                } else if (mPermissionReviewRequired) {
2237                    // In permission review mode we clear the review flag when we
2238                    // are asked to install the app with all permissions granted.
2239                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2240                        updatePermissionFlags(permission, pkg.packageName,
2241                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2242                    }
2243                }
2244            }
2245        }
2246    }
2247
2248    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2249        Bundle extras = null;
2250        switch (res.returnCode) {
2251            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2252                extras = new Bundle();
2253                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2254                        res.origPermission);
2255                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2256                        res.origPackage);
2257                break;
2258            }
2259            case PackageManager.INSTALL_SUCCEEDED: {
2260                extras = new Bundle();
2261                extras.putBoolean(Intent.EXTRA_REPLACING,
2262                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2263                break;
2264            }
2265        }
2266        return extras;
2267    }
2268
2269    void scheduleWriteSettingsLocked() {
2270        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2271            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2272        }
2273    }
2274
2275    void scheduleWritePackageListLocked(int userId) {
2276        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2277            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2278            msg.arg1 = userId;
2279            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2280        }
2281    }
2282
2283    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2284        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2285        scheduleWritePackageRestrictionsLocked(userId);
2286    }
2287
2288    void scheduleWritePackageRestrictionsLocked(int userId) {
2289        final int[] userIds = (userId == UserHandle.USER_ALL)
2290                ? sUserManager.getUserIds() : new int[]{userId};
2291        for (int nextUserId : userIds) {
2292            if (!sUserManager.exists(nextUserId)) return;
2293            mDirtyUsers.add(nextUserId);
2294            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2295                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2296            }
2297        }
2298    }
2299
2300    public static PackageManagerService main(Context context, Installer installer,
2301            boolean factoryTest, boolean onlyCore) {
2302        // Self-check for initial settings.
2303        PackageManagerServiceCompilerMapping.checkProperties();
2304
2305        PackageManagerService m = new PackageManagerService(context, installer,
2306                factoryTest, onlyCore);
2307        m.enableSystemUserPackages();
2308        ServiceManager.addService("package", m);
2309        final PackageManagerNative pmn = m.new PackageManagerNative();
2310        ServiceManager.addService("package_native", pmn);
2311        return m;
2312    }
2313
2314    private void enableSystemUserPackages() {
2315        if (!UserManager.isSplitSystemUser()) {
2316            return;
2317        }
2318        // For system user, enable apps based on the following conditions:
2319        // - app is whitelisted or belong to one of these groups:
2320        //   -- system app which has no launcher icons
2321        //   -- system app which has INTERACT_ACROSS_USERS permission
2322        //   -- system IME app
2323        // - app is not in the blacklist
2324        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2325        Set<String> enableApps = new ArraySet<>();
2326        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2327                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2328                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2329        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2330        enableApps.addAll(wlApps);
2331        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2332                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2333        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2334        enableApps.removeAll(blApps);
2335        Log.i(TAG, "Applications installed for system user: " + enableApps);
2336        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2337                UserHandle.SYSTEM);
2338        final int allAppsSize = allAps.size();
2339        synchronized (mPackages) {
2340            for (int i = 0; i < allAppsSize; i++) {
2341                String pName = allAps.get(i);
2342                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2343                // Should not happen, but we shouldn't be failing if it does
2344                if (pkgSetting == null) {
2345                    continue;
2346                }
2347                boolean install = enableApps.contains(pName);
2348                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2349                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2350                            + " for system user");
2351                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2352                }
2353            }
2354            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2355        }
2356    }
2357
2358    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2359        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2360                Context.DISPLAY_SERVICE);
2361        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2362    }
2363
2364    /**
2365     * Requests that files preopted on a secondary system partition be copied to the data partition
2366     * if possible.  Note that the actual copying of the files is accomplished by init for security
2367     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2368     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2369     */
2370    private static void requestCopyPreoptedFiles() {
2371        final int WAIT_TIME_MS = 100;
2372        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2373        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2374            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2375            // We will wait for up to 100 seconds.
2376            final long timeStart = SystemClock.uptimeMillis();
2377            final long timeEnd = timeStart + 100 * 1000;
2378            long timeNow = timeStart;
2379            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2380                try {
2381                    Thread.sleep(WAIT_TIME_MS);
2382                } catch (InterruptedException e) {
2383                    // Do nothing
2384                }
2385                timeNow = SystemClock.uptimeMillis();
2386                if (timeNow > timeEnd) {
2387                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2388                    Slog.wtf(TAG, "cppreopt did not finish!");
2389                    break;
2390                }
2391            }
2392
2393            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2394        }
2395    }
2396
2397    public PackageManagerService(Context context, Installer installer,
2398            boolean factoryTest, boolean onlyCore) {
2399        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2400        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2401        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2402                SystemClock.uptimeMillis());
2403
2404        if (mSdkVersion <= 0) {
2405            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2406        }
2407
2408        mContext = context;
2409
2410        mPermissionReviewRequired = context.getResources().getBoolean(
2411                R.bool.config_permissionReviewRequired);
2412
2413        mFactoryTest = factoryTest;
2414        mOnlyCore = onlyCore;
2415        mMetrics = new DisplayMetrics();
2416        mSettings = new Settings(mPackages);
2417        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2418                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2419        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2420                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2421        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2422                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2423        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2424                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2425        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2426                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2427        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2428                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2429
2430        String separateProcesses = SystemProperties.get("debug.separate_processes");
2431        if (separateProcesses != null && separateProcesses.length() > 0) {
2432            if ("*".equals(separateProcesses)) {
2433                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2434                mSeparateProcesses = null;
2435                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2436            } else {
2437                mDefParseFlags = 0;
2438                mSeparateProcesses = separateProcesses.split(",");
2439                Slog.w(TAG, "Running with debug.separate_processes: "
2440                        + separateProcesses);
2441            }
2442        } else {
2443            mDefParseFlags = 0;
2444            mSeparateProcesses = null;
2445        }
2446
2447        mInstaller = installer;
2448        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2449                "*dexopt*");
2450        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2451        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2452
2453        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2454                FgThread.get().getLooper());
2455
2456        getDefaultDisplayMetrics(context, mMetrics);
2457
2458        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2459        SystemConfig systemConfig = SystemConfig.getInstance();
2460        mGlobalGids = systemConfig.getGlobalGids();
2461        mSystemPermissions = systemConfig.getSystemPermissions();
2462        mAvailableFeatures = systemConfig.getAvailableFeatures();
2463        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2464
2465        mProtectedPackages = new ProtectedPackages(mContext);
2466
2467        synchronized (mInstallLock) {
2468        // writer
2469        synchronized (mPackages) {
2470            mHandlerThread = new ServiceThread(TAG,
2471                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2472            mHandlerThread.start();
2473            mHandler = new PackageHandler(mHandlerThread.getLooper());
2474            mProcessLoggingHandler = new ProcessLoggingHandler();
2475            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2476
2477            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2478            mInstantAppRegistry = new InstantAppRegistry(this);
2479
2480            File dataDir = Environment.getDataDirectory();
2481            mAppInstallDir = new File(dataDir, "app");
2482            mAppLib32InstallDir = new File(dataDir, "app-lib");
2483            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2484            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2485            sUserManager = new UserManagerService(context, this,
2486                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2487
2488            // Propagate permission configuration in to package manager.
2489            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2490                    = systemConfig.getPermissions();
2491            for (int i=0; i<permConfig.size(); i++) {
2492                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2493                BasePermission bp = mSettings.mPermissions.get(perm.name);
2494                if (bp == null) {
2495                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2496                    mSettings.mPermissions.put(perm.name, bp);
2497                }
2498                if (perm.gids != null) {
2499                    bp.setGids(perm.gids, perm.perUser);
2500                }
2501            }
2502
2503            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2504            final int builtInLibCount = libConfig.size();
2505            for (int i = 0; i < builtInLibCount; i++) {
2506                String name = libConfig.keyAt(i);
2507                String path = libConfig.valueAt(i);
2508                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2509                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2510            }
2511
2512            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2513
2514            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2515            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2516            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2517
2518            // Clean up orphaned packages for which the code path doesn't exist
2519            // and they are an update to a system app - caused by bug/32321269
2520            final int packageSettingCount = mSettings.mPackages.size();
2521            for (int i = packageSettingCount - 1; i >= 0; i--) {
2522                PackageSetting ps = mSettings.mPackages.valueAt(i);
2523                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2524                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2525                    mSettings.mPackages.removeAt(i);
2526                    mSettings.enableSystemPackageLPw(ps.name);
2527                }
2528            }
2529
2530            if (mFirstBoot) {
2531                requestCopyPreoptedFiles();
2532            }
2533
2534            String customResolverActivity = Resources.getSystem().getString(
2535                    R.string.config_customResolverActivity);
2536            if (TextUtils.isEmpty(customResolverActivity)) {
2537                customResolverActivity = null;
2538            } else {
2539                mCustomResolverComponentName = ComponentName.unflattenFromString(
2540                        customResolverActivity);
2541            }
2542
2543            long startTime = SystemClock.uptimeMillis();
2544
2545            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2546                    startTime);
2547
2548            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2549            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2550
2551            if (bootClassPath == null) {
2552                Slog.w(TAG, "No BOOTCLASSPATH found!");
2553            }
2554
2555            if (systemServerClassPath == null) {
2556                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2557            }
2558
2559            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2560
2561            final VersionInfo ver = mSettings.getInternalVersion();
2562            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2563            if (mIsUpgrade) {
2564                logCriticalInfo(Log.INFO,
2565                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2566            }
2567
2568            // when upgrading from pre-M, promote system app permissions from install to runtime
2569            mPromoteSystemApps =
2570                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2571
2572            // When upgrading from pre-N, we need to handle package extraction like first boot,
2573            // as there is no profiling data available.
2574            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2575
2576            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2577
2578            // save off the names of pre-existing system packages prior to scanning; we don't
2579            // want to automatically grant runtime permissions for new system apps
2580            if (mPromoteSystemApps) {
2581                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2582                while (pkgSettingIter.hasNext()) {
2583                    PackageSetting ps = pkgSettingIter.next();
2584                    if (isSystemApp(ps)) {
2585                        mExistingSystemPackages.add(ps.name);
2586                    }
2587                }
2588            }
2589
2590            mCacheDir = preparePackageParserCache(mIsUpgrade);
2591
2592            // Set flag to monitor and not change apk file paths when
2593            // scanning install directories.
2594            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2595
2596            if (mIsUpgrade || mFirstBoot) {
2597                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2598            }
2599
2600            // Collect vendor overlay packages. (Do this before scanning any apps.)
2601            // For security and version matching reason, only consider
2602            // overlay packages if they reside in the right directory.
2603            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2604                    | PackageParser.PARSE_IS_SYSTEM
2605                    | PackageParser.PARSE_IS_SYSTEM_DIR
2606                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2607
2608            mParallelPackageParserCallback.findStaticOverlayPackages();
2609
2610            // Find base frameworks (resource packages without code).
2611            scanDirTracedLI(frameworkDir, mDefParseFlags
2612                    | PackageParser.PARSE_IS_SYSTEM
2613                    | PackageParser.PARSE_IS_SYSTEM_DIR
2614                    | PackageParser.PARSE_IS_PRIVILEGED,
2615                    scanFlags | SCAN_NO_DEX, 0);
2616
2617            // Collected privileged system packages.
2618            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2619            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2620                    | PackageParser.PARSE_IS_SYSTEM
2621                    | PackageParser.PARSE_IS_SYSTEM_DIR
2622                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2623
2624            // Collect ordinary system packages.
2625            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2626            scanDirTracedLI(systemAppDir, mDefParseFlags
2627                    | PackageParser.PARSE_IS_SYSTEM
2628                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2629
2630            // Collect all vendor packages.
2631            File vendorAppDir = new File("/vendor/app");
2632            try {
2633                vendorAppDir = vendorAppDir.getCanonicalFile();
2634            } catch (IOException e) {
2635                // failed to look up canonical path, continue with original one
2636            }
2637            scanDirTracedLI(vendorAppDir, mDefParseFlags
2638                    | PackageParser.PARSE_IS_SYSTEM
2639                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2640
2641            // Collect all OEM packages.
2642            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2643            scanDirTracedLI(oemAppDir, mDefParseFlags
2644                    | PackageParser.PARSE_IS_SYSTEM
2645                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2646
2647            // Prune any system packages that no longer exist.
2648            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2649            // Stub packages must either be replaced with full versions in the /data
2650            // partition or be disabled.
2651            final List<String> stubSystemApps = new ArrayList<>();
2652            if (!mOnlyCore) {
2653                // do this first before mucking with mPackages for the "expecting better" case
2654                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2655                while (pkgIterator.hasNext()) {
2656                    final PackageParser.Package pkg = pkgIterator.next();
2657                    if (pkg.isStub) {
2658                        stubSystemApps.add(pkg.packageName);
2659                    }
2660                }
2661
2662                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2663                while (psit.hasNext()) {
2664                    PackageSetting ps = psit.next();
2665
2666                    /*
2667                     * If this is not a system app, it can't be a
2668                     * disable system app.
2669                     */
2670                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2671                        continue;
2672                    }
2673
2674                    /*
2675                     * If the package is scanned, it's not erased.
2676                     */
2677                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2678                    if (scannedPkg != null) {
2679                        /*
2680                         * If the system app is both scanned and in the
2681                         * disabled packages list, then it must have been
2682                         * added via OTA. Remove it from the currently
2683                         * scanned package so the previously user-installed
2684                         * application can be scanned.
2685                         */
2686                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2687                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2688                                    + ps.name + "; removing system app.  Last known codePath="
2689                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2690                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2691                                    + scannedPkg.mVersionCode);
2692                            removePackageLI(scannedPkg, true);
2693                            mExpectingBetter.put(ps.name, ps.codePath);
2694                        }
2695
2696                        continue;
2697                    }
2698
2699                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2700                        psit.remove();
2701                        logCriticalInfo(Log.WARN, "System package " + ps.name
2702                                + " no longer exists; it's data will be wiped");
2703                        // Actual deletion of code and data will be handled by later
2704                        // reconciliation step
2705                    } else {
2706                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2707                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2708                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2709                        }
2710                    }
2711                }
2712            }
2713
2714            //look for any incomplete package installations
2715            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2716            for (int i = 0; i < deletePkgsList.size(); i++) {
2717                // Actual deletion of code and data will be handled by later
2718                // reconciliation step
2719                final String packageName = deletePkgsList.get(i).name;
2720                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2721                synchronized (mPackages) {
2722                    mSettings.removePackageLPw(packageName);
2723                }
2724            }
2725
2726            //delete tmp files
2727            deleteTempPackageFiles();
2728
2729            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2730
2731            // Remove any shared userIDs that have no associated packages
2732            mSettings.pruneSharedUsersLPw();
2733            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2734            final int systemPackagesCount = mPackages.size();
2735            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2736                    + " ms, packageCount: " + systemPackagesCount
2737                    + " , timePerPackage: "
2738                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2739                    + " , cached: " + cachedSystemApps);
2740            if (mIsUpgrade && systemPackagesCount > 0) {
2741                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2742                        ((int) systemScanTime) / systemPackagesCount);
2743            }
2744            if (!mOnlyCore) {
2745                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2746                        SystemClock.uptimeMillis());
2747                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2748
2749                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2750                        | PackageParser.PARSE_FORWARD_LOCK,
2751                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2752
2753                // Remove disable package settings for updated system apps that were
2754                // removed via an OTA. If the update is no longer present, remove the
2755                // app completely. Otherwise, revoke their system privileges.
2756                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2757                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2758                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2759
2760                    final String msg;
2761                    if (deletedPkg == null) {
2762                        // should have found an update, but, we didn't; remove everything
2763                        msg = "Updated system package " + deletedAppName
2764                                + " no longer exists; removing its data";
2765                        // Actual deletion of code and data will be handled by later
2766                        // reconciliation step
2767                    } else {
2768                        // found an update; revoke system privileges
2769                        msg = "Updated system package + " + deletedAppName
2770                                + " no longer exists; revoking system privileges";
2771
2772                        // Don't do anything if a stub is removed from the system image. If
2773                        // we were to remove the uncompressed version from the /data partition,
2774                        // this is where it'd be done.
2775
2776                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2777                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2778                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2779                    }
2780                    logCriticalInfo(Log.WARN, msg);
2781                }
2782
2783                /*
2784                 * Make sure all system apps that we expected to appear on
2785                 * the userdata partition actually showed up. If they never
2786                 * appeared, crawl back and revive the system version.
2787                 */
2788                for (int i = 0; i < mExpectingBetter.size(); i++) {
2789                    final String packageName = mExpectingBetter.keyAt(i);
2790                    if (!mPackages.containsKey(packageName)) {
2791                        final File scanFile = mExpectingBetter.valueAt(i);
2792
2793                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2794                                + " but never showed up; reverting to system");
2795
2796                        int reparseFlags = mDefParseFlags;
2797                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2798                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2799                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2800                                    | PackageParser.PARSE_IS_PRIVILEGED;
2801                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2802                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2803                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2804                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2805                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2806                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2807                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2808                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2809                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2810                        } else {
2811                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2812                            continue;
2813                        }
2814
2815                        mSettings.enableSystemPackageLPw(packageName);
2816
2817                        try {
2818                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2819                        } catch (PackageManagerException e) {
2820                            Slog.e(TAG, "Failed to parse original system package: "
2821                                    + e.getMessage());
2822                        }
2823                    }
2824                }
2825
2826                // Uncompress and install any stubbed system applications.
2827                // This must be done last to ensure all stubs are replaced or disabled.
2828                decompressSystemApplications(stubSystemApps, scanFlags);
2829
2830                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2831                                - cachedSystemApps;
2832
2833                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2834                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2835                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2836                        + " ms, packageCount: " + dataPackagesCount
2837                        + " , timePerPackage: "
2838                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2839                        + " , cached: " + cachedNonSystemApps);
2840                if (mIsUpgrade && dataPackagesCount > 0) {
2841                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2842                            ((int) dataScanTime) / dataPackagesCount);
2843                }
2844            }
2845            mExpectingBetter.clear();
2846
2847            // Resolve the storage manager.
2848            mStorageManagerPackage = getStorageManagerPackageName();
2849
2850            // Resolve protected action filters. Only the setup wizard is allowed to
2851            // have a high priority filter for these actions.
2852            mSetupWizardPackage = getSetupWizardPackageName();
2853            if (mProtectedFilters.size() > 0) {
2854                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2855                    Slog.i(TAG, "No setup wizard;"
2856                        + " All protected intents capped to priority 0");
2857                }
2858                for (ActivityIntentInfo filter : mProtectedFilters) {
2859                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2860                        if (DEBUG_FILTERS) {
2861                            Slog.i(TAG, "Found setup wizard;"
2862                                + " allow priority " + filter.getPriority() + ";"
2863                                + " package: " + filter.activity.info.packageName
2864                                + " activity: " + filter.activity.className
2865                                + " priority: " + filter.getPriority());
2866                        }
2867                        // skip setup wizard; allow it to keep the high priority filter
2868                        continue;
2869                    }
2870                    if (DEBUG_FILTERS) {
2871                        Slog.i(TAG, "Protected action; cap priority to 0;"
2872                                + " package: " + filter.activity.info.packageName
2873                                + " activity: " + filter.activity.className
2874                                + " origPrio: " + filter.getPriority());
2875                    }
2876                    filter.setPriority(0);
2877                }
2878            }
2879            mDeferProtectedFilters = false;
2880            mProtectedFilters.clear();
2881
2882            // Now that we know all of the shared libraries, update all clients to have
2883            // the correct library paths.
2884            updateAllSharedLibrariesLPw(null);
2885
2886            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2887                // NOTE: We ignore potential failures here during a system scan (like
2888                // the rest of the commands above) because there's precious little we
2889                // can do about it. A settings error is reported, though.
2890                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2891            }
2892
2893            // Now that we know all the packages we are keeping,
2894            // read and update their last usage times.
2895            mPackageUsage.read(mPackages);
2896            mCompilerStats.read();
2897
2898            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2899                    SystemClock.uptimeMillis());
2900            Slog.i(TAG, "Time to scan packages: "
2901                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2902                    + " seconds");
2903
2904            // If the platform SDK has changed since the last time we booted,
2905            // we need to re-grant app permission to catch any new ones that
2906            // appear.  This is really a hack, and means that apps can in some
2907            // cases get permissions that the user didn't initially explicitly
2908            // allow...  it would be nice to have some better way to handle
2909            // this situation.
2910            int updateFlags = UPDATE_PERMISSIONS_ALL;
2911            if (ver.sdkVersion != mSdkVersion) {
2912                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2913                        + mSdkVersion + "; regranting permissions for internal storage");
2914                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2915            }
2916            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2917            ver.sdkVersion = mSdkVersion;
2918
2919            // If this is the first boot or an update from pre-M, and it is a normal
2920            // boot, then we need to initialize the default preferred apps across
2921            // all defined users.
2922            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2923                for (UserInfo user : sUserManager.getUsers(true)) {
2924                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2925                    applyFactoryDefaultBrowserLPw(user.id);
2926                    primeDomainVerificationsLPw(user.id);
2927                }
2928            }
2929
2930            // Prepare storage for system user really early during boot,
2931            // since core system apps like SettingsProvider and SystemUI
2932            // can't wait for user to start
2933            final int storageFlags;
2934            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2935                storageFlags = StorageManager.FLAG_STORAGE_DE;
2936            } else {
2937                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2938            }
2939            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2940                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2941                    true /* onlyCoreApps */);
2942            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2943                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2944                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2945                traceLog.traceBegin("AppDataFixup");
2946                try {
2947                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2948                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2949                } catch (InstallerException e) {
2950                    Slog.w(TAG, "Trouble fixing GIDs", e);
2951                }
2952                traceLog.traceEnd();
2953
2954                traceLog.traceBegin("AppDataPrepare");
2955                if (deferPackages == null || deferPackages.isEmpty()) {
2956                    return;
2957                }
2958                int count = 0;
2959                for (String pkgName : deferPackages) {
2960                    PackageParser.Package pkg = null;
2961                    synchronized (mPackages) {
2962                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2963                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2964                            pkg = ps.pkg;
2965                        }
2966                    }
2967                    if (pkg != null) {
2968                        synchronized (mInstallLock) {
2969                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2970                                    true /* maybeMigrateAppData */);
2971                        }
2972                        count++;
2973                    }
2974                }
2975                traceLog.traceEnd();
2976                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2977            }, "prepareAppData");
2978
2979            // If this is first boot after an OTA, and a normal boot, then
2980            // we need to clear code cache directories.
2981            // Note that we do *not* clear the application profiles. These remain valid
2982            // across OTAs and are used to drive profile verification (post OTA) and
2983            // profile compilation (without waiting to collect a fresh set of profiles).
2984            if (mIsUpgrade && !onlyCore) {
2985                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2986                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2987                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2988                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2989                        // No apps are running this early, so no need to freeze
2990                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2991                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2992                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2993                    }
2994                }
2995                ver.fingerprint = Build.FINGERPRINT;
2996            }
2997
2998            checkDefaultBrowser();
2999
3000            // clear only after permissions and other defaults have been updated
3001            mExistingSystemPackages.clear();
3002            mPromoteSystemApps = false;
3003
3004            // All the changes are done during package scanning.
3005            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3006
3007            // can downgrade to reader
3008            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3009            mSettings.writeLPr();
3010            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3011            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3012                    SystemClock.uptimeMillis());
3013
3014            if (!mOnlyCore) {
3015                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3016                mRequiredInstallerPackage = getRequiredInstallerLPr();
3017                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3018                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3019                if (mIntentFilterVerifierComponent != null) {
3020                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3021                            mIntentFilterVerifierComponent);
3022                } else {
3023                    mIntentFilterVerifier = null;
3024                }
3025                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3026                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3027                        SharedLibraryInfo.VERSION_UNDEFINED);
3028                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3029                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3030                        SharedLibraryInfo.VERSION_UNDEFINED);
3031            } else {
3032                mRequiredVerifierPackage = null;
3033                mRequiredInstallerPackage = null;
3034                mRequiredUninstallerPackage = null;
3035                mIntentFilterVerifierComponent = null;
3036                mIntentFilterVerifier = null;
3037                mServicesSystemSharedLibraryPackageName = null;
3038                mSharedSystemSharedLibraryPackageName = null;
3039            }
3040
3041            mInstallerService = new PackageInstallerService(context, this);
3042            final Pair<ComponentName, String> instantAppResolverComponent =
3043                    getInstantAppResolverLPr();
3044            if (instantAppResolverComponent != null) {
3045                if (DEBUG_EPHEMERAL) {
3046                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3047                }
3048                mInstantAppResolverConnection = new EphemeralResolverConnection(
3049                        mContext, instantAppResolverComponent.first,
3050                        instantAppResolverComponent.second);
3051                mInstantAppResolverSettingsComponent =
3052                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3053            } else {
3054                mInstantAppResolverConnection = null;
3055                mInstantAppResolverSettingsComponent = null;
3056            }
3057            updateInstantAppInstallerLocked(null);
3058
3059            // Read and update the usage of dex files.
3060            // Do this at the end of PM init so that all the packages have their
3061            // data directory reconciled.
3062            // At this point we know the code paths of the packages, so we can validate
3063            // the disk file and build the internal cache.
3064            // The usage file is expected to be small so loading and verifying it
3065            // should take a fairly small time compare to the other activities (e.g. package
3066            // scanning).
3067            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3068            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3069            for (int userId : currentUserIds) {
3070                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3071            }
3072            mDexManager.load(userPackages);
3073            if (mIsUpgrade) {
3074                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3075                        (int) (SystemClock.uptimeMillis() - startTime));
3076            }
3077        } // synchronized (mPackages)
3078        } // synchronized (mInstallLock)
3079
3080        // Now after opening every single application zip, make sure they
3081        // are all flushed.  Not really needed, but keeps things nice and
3082        // tidy.
3083        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3084        Runtime.getRuntime().gc();
3085        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3086
3087        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3088        FallbackCategoryProvider.loadFallbacks();
3089        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3090
3091        // The initial scanning above does many calls into installd while
3092        // holding the mPackages lock, but we're mostly interested in yelling
3093        // once we have a booted system.
3094        mInstaller.setWarnIfHeld(mPackages);
3095
3096        // Expose private service for system components to use.
3097        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3098        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3099    }
3100
3101    /**
3102     * Uncompress and install stub applications.
3103     * <p>In order to save space on the system partition, some applications are shipped in a
3104     * compressed form. In addition the compressed bits for the full application, the
3105     * system image contains a tiny stub comprised of only the Android manifest.
3106     * <p>During the first boot, attempt to uncompress and install the full application. If
3107     * the application can't be installed for any reason, disable the stub and prevent
3108     * uncompressing the full application during future boots.
3109     * <p>In order to forcefully attempt an installation of a full application, go to app
3110     * settings and enable the application.
3111     */
3112    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3113        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3114            final String pkgName = stubSystemApps.get(i);
3115            // skip if the system package is already disabled
3116            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3117                stubSystemApps.remove(i);
3118                continue;
3119            }
3120            // skip if the package isn't installed (?!); this should never happen
3121            final PackageParser.Package pkg = mPackages.get(pkgName);
3122            if (pkg == null) {
3123                stubSystemApps.remove(i);
3124                continue;
3125            }
3126            // skip if the package has been disabled by the user
3127            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3128            if (ps != null) {
3129                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3130                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3131                    stubSystemApps.remove(i);
3132                    continue;
3133                }
3134            }
3135
3136            if (DEBUG_COMPRESSION) {
3137                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3138            }
3139
3140            // uncompress the binary to its eventual destination on /data
3141            final File scanFile = decompressPackage(pkg);
3142            if (scanFile == null) {
3143                continue;
3144            }
3145
3146            // install the package to replace the stub on /system
3147            try {
3148                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3149                removePackageLI(pkg, true /*chatty*/);
3150                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3151                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3152                        UserHandle.USER_SYSTEM, "android");
3153                stubSystemApps.remove(i);
3154                continue;
3155            } catch (PackageManagerException e) {
3156                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3157            }
3158
3159            // any failed attempt to install the package will be cleaned up later
3160        }
3161
3162        // disable any stub still left; these failed to install the full application
3163        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3164            final String pkgName = stubSystemApps.get(i);
3165            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3166            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3167                    UserHandle.USER_SYSTEM, "android");
3168            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3169        }
3170    }
3171
3172    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3173        if (DEBUG_COMPRESSION) {
3174            Slog.i(TAG, "Decompress file"
3175                    + "; src: " + srcFile.getAbsolutePath()
3176                    + ", dst: " + dstFile.getAbsolutePath());
3177        }
3178        try (
3179                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3180                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3181        ) {
3182            Streams.copy(fileIn, fileOut);
3183            Os.chmod(dstFile.getAbsolutePath(), 0644);
3184            return PackageManager.INSTALL_SUCCEEDED;
3185        } catch (IOException e) {
3186            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3187                    + "; src: " + srcFile.getAbsolutePath()
3188                    + ", dst: " + dstFile.getAbsolutePath());
3189        }
3190        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3191    }
3192
3193    private File[] getCompressedFiles(String codePath) {
3194        return new File(codePath).listFiles(new FilenameFilter() {
3195            @Override
3196            public boolean accept(File dir, String name) {
3197                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3198            }
3199        });
3200    }
3201
3202    private boolean compressedFileExists(String codePath) {
3203        final File[] compressedFiles = getCompressedFiles(codePath);
3204        return compressedFiles != null && compressedFiles.length > 0;
3205    }
3206
3207    /**
3208     * Decompresses the given package on the system image onto
3209     * the /data partition.
3210     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3211     */
3212    private File decompressPackage(PackageParser.Package pkg) {
3213        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3214        if (compressedFiles == null || compressedFiles.length == 0) {
3215            if (DEBUG_COMPRESSION) {
3216                Slog.i(TAG, "No files to decompress");
3217            }
3218            return null;
3219        }
3220        final File dstCodePath =
3221                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3222        int ret = PackageManager.INSTALL_SUCCEEDED;
3223        try {
3224            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3225            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3226            for (File srcFile : compressedFiles) {
3227                final String srcFileName = srcFile.getName();
3228                final String dstFileName = srcFileName.substring(
3229                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3230                final File dstFile = new File(dstCodePath, dstFileName);
3231                ret = decompressFile(srcFile, dstFile);
3232                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3233                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3234                            + "; pkg: " + pkg.packageName
3235                            + ", file: " + dstFileName);
3236                    break;
3237                }
3238            }
3239        } catch (ErrnoException e) {
3240            logCriticalInfo(Log.ERROR, "Failed to decompress"
3241                    + "; pkg: " + pkg.packageName
3242                    + ", err: " + e.errno);
3243        }
3244        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3245            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3246            NativeLibraryHelper.Handle handle = null;
3247            try {
3248                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3249                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3250                        null /*abiOverride*/);
3251            } catch (IOException e) {
3252                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3253                        + "; pkg: " + pkg.packageName);
3254                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3255            } finally {
3256                IoUtils.closeQuietly(handle);
3257            }
3258        }
3259        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3260            if (dstCodePath == null || !dstCodePath.exists()) {
3261                return null;
3262            }
3263            removeCodePathLI(dstCodePath);
3264            return null;
3265        }
3266        return dstCodePath;
3267    }
3268
3269    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3270        // we're only interested in updating the installer appliction when 1) it's not
3271        // already set or 2) the modified package is the installer
3272        if (mInstantAppInstallerActivity != null
3273                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3274                        .equals(modifiedPackage)) {
3275            return;
3276        }
3277        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3278    }
3279
3280    private static File preparePackageParserCache(boolean isUpgrade) {
3281        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3282            return null;
3283        }
3284
3285        // Disable package parsing on eng builds to allow for faster incremental development.
3286        if (Build.IS_ENG) {
3287            return null;
3288        }
3289
3290        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3291            Slog.i(TAG, "Disabling package parser cache due to system property.");
3292            return null;
3293        }
3294
3295        // The base directory for the package parser cache lives under /data/system/.
3296        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3297                "package_cache");
3298        if (cacheBaseDir == null) {
3299            return null;
3300        }
3301
3302        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3303        // This also serves to "GC" unused entries when the package cache version changes (which
3304        // can only happen during upgrades).
3305        if (isUpgrade) {
3306            FileUtils.deleteContents(cacheBaseDir);
3307        }
3308
3309
3310        // Return the versioned package cache directory. This is something like
3311        // "/data/system/package_cache/1"
3312        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3313
3314        // The following is a workaround to aid development on non-numbered userdebug
3315        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3316        // the system partition is newer.
3317        //
3318        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3319        // that starts with "eng." to signify that this is an engineering build and not
3320        // destined for release.
3321        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3322            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3323
3324            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3325            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3326            // in general and should not be used for production changes. In this specific case,
3327            // we know that they will work.
3328            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3329            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3330                FileUtils.deleteContents(cacheBaseDir);
3331                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3332            }
3333        }
3334
3335        return cacheDir;
3336    }
3337
3338    @Override
3339    public boolean isFirstBoot() {
3340        // allow instant applications
3341        return mFirstBoot;
3342    }
3343
3344    @Override
3345    public boolean isOnlyCoreApps() {
3346        // allow instant applications
3347        return mOnlyCore;
3348    }
3349
3350    @Override
3351    public boolean isUpgrade() {
3352        // allow instant applications
3353        return mIsUpgrade;
3354    }
3355
3356    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3357        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3358
3359        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3360                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3361                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3362        if (matches.size() == 1) {
3363            return matches.get(0).getComponentInfo().packageName;
3364        } else if (matches.size() == 0) {
3365            Log.e(TAG, "There should probably be a verifier, but, none were found");
3366            return null;
3367        }
3368        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3369    }
3370
3371    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3372        synchronized (mPackages) {
3373            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3374            if (libraryEntry == null) {
3375                throw new IllegalStateException("Missing required shared library:" + name);
3376            }
3377            return libraryEntry.apk;
3378        }
3379    }
3380
3381    private @NonNull String getRequiredInstallerLPr() {
3382        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3383        intent.addCategory(Intent.CATEGORY_DEFAULT);
3384        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3385
3386        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3387                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3388                UserHandle.USER_SYSTEM);
3389        if (matches.size() == 1) {
3390            ResolveInfo resolveInfo = matches.get(0);
3391            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3392                throw new RuntimeException("The installer must be a privileged app");
3393            }
3394            return matches.get(0).getComponentInfo().packageName;
3395        } else {
3396            throw new RuntimeException("There must be exactly one installer; found " + matches);
3397        }
3398    }
3399
3400    private @NonNull String getRequiredUninstallerLPr() {
3401        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3402        intent.addCategory(Intent.CATEGORY_DEFAULT);
3403        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3404
3405        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3406                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3407                UserHandle.USER_SYSTEM);
3408        if (resolveInfo == null ||
3409                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3410            throw new RuntimeException("There must be exactly one uninstaller; found "
3411                    + resolveInfo);
3412        }
3413        return resolveInfo.getComponentInfo().packageName;
3414    }
3415
3416    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3417        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3418
3419        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3420                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3421                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3422        ResolveInfo best = null;
3423        final int N = matches.size();
3424        for (int i = 0; i < N; i++) {
3425            final ResolveInfo cur = matches.get(i);
3426            final String packageName = cur.getComponentInfo().packageName;
3427            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3428                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3429                continue;
3430            }
3431
3432            if (best == null || cur.priority > best.priority) {
3433                best = cur;
3434            }
3435        }
3436
3437        if (best != null) {
3438            return best.getComponentInfo().getComponentName();
3439        }
3440        Slog.w(TAG, "Intent filter verifier not found");
3441        return null;
3442    }
3443
3444    @Override
3445    public @Nullable ComponentName getInstantAppResolverComponent() {
3446        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3447            return null;
3448        }
3449        synchronized (mPackages) {
3450            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3451            if (instantAppResolver == null) {
3452                return null;
3453            }
3454            return instantAppResolver.first;
3455        }
3456    }
3457
3458    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3459        final String[] packageArray =
3460                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3461        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3462            if (DEBUG_EPHEMERAL) {
3463                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3464            }
3465            return null;
3466        }
3467
3468        final int callingUid = Binder.getCallingUid();
3469        final int resolveFlags =
3470                MATCH_DIRECT_BOOT_AWARE
3471                | MATCH_DIRECT_BOOT_UNAWARE
3472                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3473        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3474        final Intent resolverIntent = new Intent(actionName);
3475        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3476                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3477        // temporarily look for the old action
3478        if (resolvers.size() == 0) {
3479            if (DEBUG_EPHEMERAL) {
3480                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3481            }
3482            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3483            resolverIntent.setAction(actionName);
3484            resolvers = queryIntentServicesInternal(resolverIntent, null,
3485                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3486        }
3487        final int N = resolvers.size();
3488        if (N == 0) {
3489            if (DEBUG_EPHEMERAL) {
3490                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3491            }
3492            return null;
3493        }
3494
3495        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3496        for (int i = 0; i < N; i++) {
3497            final ResolveInfo info = resolvers.get(i);
3498
3499            if (info.serviceInfo == null) {
3500                continue;
3501            }
3502
3503            final String packageName = info.serviceInfo.packageName;
3504            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3505                if (DEBUG_EPHEMERAL) {
3506                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3507                            + " pkg: " + packageName + ", info:" + info);
3508                }
3509                continue;
3510            }
3511
3512            if (DEBUG_EPHEMERAL) {
3513                Slog.v(TAG, "Ephemeral resolver found;"
3514                        + " pkg: " + packageName + ", info:" + info);
3515            }
3516            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3517        }
3518        if (DEBUG_EPHEMERAL) {
3519            Slog.v(TAG, "Ephemeral resolver NOT found");
3520        }
3521        return null;
3522    }
3523
3524    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3525        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3526        intent.addCategory(Intent.CATEGORY_DEFAULT);
3527        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3528
3529        final int resolveFlags =
3530                MATCH_DIRECT_BOOT_AWARE
3531                | MATCH_DIRECT_BOOT_UNAWARE
3532                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3533        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3534                resolveFlags, UserHandle.USER_SYSTEM);
3535        // temporarily look for the old action
3536        if (matches.isEmpty()) {
3537            if (DEBUG_EPHEMERAL) {
3538                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3539            }
3540            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3541            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3542                    resolveFlags, UserHandle.USER_SYSTEM);
3543        }
3544        Iterator<ResolveInfo> iter = matches.iterator();
3545        while (iter.hasNext()) {
3546            final ResolveInfo rInfo = iter.next();
3547            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3548            if (ps != null) {
3549                final PermissionsState permissionsState = ps.getPermissionsState();
3550                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3551                    continue;
3552                }
3553            }
3554            iter.remove();
3555        }
3556        if (matches.size() == 0) {
3557            return null;
3558        } else if (matches.size() == 1) {
3559            return (ActivityInfo) matches.get(0).getComponentInfo();
3560        } else {
3561            throw new RuntimeException(
3562                    "There must be at most one ephemeral installer; found " + matches);
3563        }
3564    }
3565
3566    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3567            @NonNull ComponentName resolver) {
3568        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3569                .addCategory(Intent.CATEGORY_DEFAULT)
3570                .setPackage(resolver.getPackageName());
3571        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3572        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3573                UserHandle.USER_SYSTEM);
3574        // temporarily look for the old action
3575        if (matches.isEmpty()) {
3576            if (DEBUG_EPHEMERAL) {
3577                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3578            }
3579            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3580            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3581                    UserHandle.USER_SYSTEM);
3582        }
3583        if (matches.isEmpty()) {
3584            return null;
3585        }
3586        return matches.get(0).getComponentInfo().getComponentName();
3587    }
3588
3589    private void primeDomainVerificationsLPw(int userId) {
3590        if (DEBUG_DOMAIN_VERIFICATION) {
3591            Slog.d(TAG, "Priming domain verifications in user " + userId);
3592        }
3593
3594        SystemConfig systemConfig = SystemConfig.getInstance();
3595        ArraySet<String> packages = systemConfig.getLinkedApps();
3596
3597        for (String packageName : packages) {
3598            PackageParser.Package pkg = mPackages.get(packageName);
3599            if (pkg != null) {
3600                if (!pkg.isSystemApp()) {
3601                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3602                    continue;
3603                }
3604
3605                ArraySet<String> domains = null;
3606                for (PackageParser.Activity a : pkg.activities) {
3607                    for (ActivityIntentInfo filter : a.intents) {
3608                        if (hasValidDomains(filter)) {
3609                            if (domains == null) {
3610                                domains = new ArraySet<String>();
3611                            }
3612                            domains.addAll(filter.getHostsList());
3613                        }
3614                    }
3615                }
3616
3617                if (domains != null && domains.size() > 0) {
3618                    if (DEBUG_DOMAIN_VERIFICATION) {
3619                        Slog.v(TAG, "      + " + packageName);
3620                    }
3621                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3622                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3623                    // and then 'always' in the per-user state actually used for intent resolution.
3624                    final IntentFilterVerificationInfo ivi;
3625                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3626                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3627                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3628                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3629                } else {
3630                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3631                            + "' does not handle web links");
3632                }
3633            } else {
3634                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3635            }
3636        }
3637
3638        scheduleWritePackageRestrictionsLocked(userId);
3639        scheduleWriteSettingsLocked();
3640    }
3641
3642    private void applyFactoryDefaultBrowserLPw(int userId) {
3643        // The default browser app's package name is stored in a string resource,
3644        // with a product-specific overlay used for vendor customization.
3645        String browserPkg = mContext.getResources().getString(
3646                com.android.internal.R.string.default_browser);
3647        if (!TextUtils.isEmpty(browserPkg)) {
3648            // non-empty string => required to be a known package
3649            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3650            if (ps == null) {
3651                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3652                browserPkg = null;
3653            } else {
3654                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3655            }
3656        }
3657
3658        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3659        // default.  If there's more than one, just leave everything alone.
3660        if (browserPkg == null) {
3661            calculateDefaultBrowserLPw(userId);
3662        }
3663    }
3664
3665    private void calculateDefaultBrowserLPw(int userId) {
3666        List<String> allBrowsers = resolveAllBrowserApps(userId);
3667        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3668        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3669    }
3670
3671    private List<String> resolveAllBrowserApps(int userId) {
3672        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3673        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3674                PackageManager.MATCH_ALL, userId);
3675
3676        final int count = list.size();
3677        List<String> result = new ArrayList<String>(count);
3678        for (int i=0; i<count; i++) {
3679            ResolveInfo info = list.get(i);
3680            if (info.activityInfo == null
3681                    || !info.handleAllWebDataURI
3682                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3683                    || result.contains(info.activityInfo.packageName)) {
3684                continue;
3685            }
3686            result.add(info.activityInfo.packageName);
3687        }
3688
3689        return result;
3690    }
3691
3692    private boolean packageIsBrowser(String packageName, int userId) {
3693        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3694                PackageManager.MATCH_ALL, userId);
3695        final int N = list.size();
3696        for (int i = 0; i < N; i++) {
3697            ResolveInfo info = list.get(i);
3698            if (packageName.equals(info.activityInfo.packageName)) {
3699                return true;
3700            }
3701        }
3702        return false;
3703    }
3704
3705    private void checkDefaultBrowser() {
3706        final int myUserId = UserHandle.myUserId();
3707        final String packageName = getDefaultBrowserPackageName(myUserId);
3708        if (packageName != null) {
3709            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3710            if (info == null) {
3711                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3712                synchronized (mPackages) {
3713                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3714                }
3715            }
3716        }
3717    }
3718
3719    @Override
3720    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3721            throws RemoteException {
3722        try {
3723            return super.onTransact(code, data, reply, flags);
3724        } catch (RuntimeException e) {
3725            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3726                Slog.wtf(TAG, "Package Manager Crash", e);
3727            }
3728            throw e;
3729        }
3730    }
3731
3732    static int[] appendInts(int[] cur, int[] add) {
3733        if (add == null) return cur;
3734        if (cur == null) return add;
3735        final int N = add.length;
3736        for (int i=0; i<N; i++) {
3737            cur = appendInt(cur, add[i]);
3738        }
3739        return cur;
3740    }
3741
3742    /**
3743     * Returns whether or not a full application can see an instant application.
3744     * <p>
3745     * Currently, there are three cases in which this can occur:
3746     * <ol>
3747     * <li>The calling application is a "special" process. The special
3748     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3749     *     and {@code 0}</li>
3750     * <li>The calling application has the permission
3751     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3752     * <li>The calling application is the default launcher on the
3753     *     system partition.</li>
3754     * </ol>
3755     */
3756    private boolean canViewInstantApps(int callingUid, int userId) {
3757        if (callingUid == Process.SYSTEM_UID
3758                || callingUid == Process.SHELL_UID
3759                || callingUid == Process.ROOT_UID) {
3760            return true;
3761        }
3762        if (mContext.checkCallingOrSelfPermission(
3763                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3764            return true;
3765        }
3766        if (mContext.checkCallingOrSelfPermission(
3767                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3768            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3769            if (homeComponent != null
3770                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3771                return true;
3772            }
3773        }
3774        return false;
3775    }
3776
3777    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3778        if (!sUserManager.exists(userId)) return null;
3779        if (ps == null) {
3780            return null;
3781        }
3782        PackageParser.Package p = ps.pkg;
3783        if (p == null) {
3784            return null;
3785        }
3786        final int callingUid = Binder.getCallingUid();
3787        // Filter out ephemeral app metadata:
3788        //   * The system/shell/root can see metadata for any app
3789        //   * An installed app can see metadata for 1) other installed apps
3790        //     and 2) ephemeral apps that have explicitly interacted with it
3791        //   * Ephemeral apps can only see their own data and exposed installed apps
3792        //   * Holding a signature permission allows seeing instant apps
3793        if (filterAppAccessLPr(ps, callingUid, userId)) {
3794            return null;
3795        }
3796
3797        final PermissionsState permissionsState = ps.getPermissionsState();
3798
3799        // Compute GIDs only if requested
3800        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3801                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3802        // Compute granted permissions only if package has requested permissions
3803        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3804                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3805        final PackageUserState state = ps.readUserState(userId);
3806
3807        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3808                && ps.isSystem()) {
3809            flags |= MATCH_ANY_USER;
3810        }
3811
3812        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3813                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3814
3815        if (packageInfo == null) {
3816            return null;
3817        }
3818
3819        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3820                resolveExternalPackageNameLPr(p);
3821
3822        return packageInfo;
3823    }
3824
3825    @Override
3826    public void checkPackageStartable(String packageName, int userId) {
3827        final int callingUid = Binder.getCallingUid();
3828        if (getInstantAppPackageName(callingUid) != null) {
3829            throw new SecurityException("Instant applications don't have access to this method");
3830        }
3831        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3832        synchronized (mPackages) {
3833            final PackageSetting ps = mSettings.mPackages.get(packageName);
3834            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3835                throw new SecurityException("Package " + packageName + " was not found!");
3836            }
3837
3838            if (!ps.getInstalled(userId)) {
3839                throw new SecurityException(
3840                        "Package " + packageName + " was not installed for user " + userId + "!");
3841            }
3842
3843            if (mSafeMode && !ps.isSystem()) {
3844                throw new SecurityException("Package " + packageName + " not a system app!");
3845            }
3846
3847            if (mFrozenPackages.contains(packageName)) {
3848                throw new SecurityException("Package " + packageName + " is currently frozen!");
3849            }
3850
3851            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3852                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3853                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3854            }
3855        }
3856    }
3857
3858    @Override
3859    public boolean isPackageAvailable(String packageName, int userId) {
3860        if (!sUserManager.exists(userId)) return false;
3861        final int callingUid = Binder.getCallingUid();
3862        enforceCrossUserPermission(callingUid, userId,
3863                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3864        synchronized (mPackages) {
3865            PackageParser.Package p = mPackages.get(packageName);
3866            if (p != null) {
3867                final PackageSetting ps = (PackageSetting) p.mExtras;
3868                if (filterAppAccessLPr(ps, callingUid, userId)) {
3869                    return false;
3870                }
3871                if (ps != null) {
3872                    final PackageUserState state = ps.readUserState(userId);
3873                    if (state != null) {
3874                        return PackageParser.isAvailable(state);
3875                    }
3876                }
3877            }
3878        }
3879        return false;
3880    }
3881
3882    @Override
3883    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3884        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3885                flags, Binder.getCallingUid(), userId);
3886    }
3887
3888    @Override
3889    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3890            int flags, int userId) {
3891        return getPackageInfoInternal(versionedPackage.getPackageName(),
3892                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3893    }
3894
3895    /**
3896     * Important: The provided filterCallingUid is used exclusively to filter out packages
3897     * that can be seen based on user state. It's typically the original caller uid prior
3898     * to clearing. Because it can only be provided by trusted code, it's value can be
3899     * trusted and will be used as-is; unlike userId which will be validated by this method.
3900     */
3901    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3902            int flags, int filterCallingUid, int userId) {
3903        if (!sUserManager.exists(userId)) return null;
3904        flags = updateFlagsForPackage(flags, userId, packageName);
3905        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3906                false /* requireFullPermission */, false /* checkShell */, "get package info");
3907
3908        // reader
3909        synchronized (mPackages) {
3910            // Normalize package name to handle renamed packages and static libs
3911            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3912
3913            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3914            if (matchFactoryOnly) {
3915                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3916                if (ps != null) {
3917                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3918                        return null;
3919                    }
3920                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3921                        return null;
3922                    }
3923                    return generatePackageInfo(ps, flags, userId);
3924                }
3925            }
3926
3927            PackageParser.Package p = mPackages.get(packageName);
3928            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3929                return null;
3930            }
3931            if (DEBUG_PACKAGE_INFO)
3932                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3933            if (p != null) {
3934                final PackageSetting ps = (PackageSetting) p.mExtras;
3935                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3936                    return null;
3937                }
3938                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3939                    return null;
3940                }
3941                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3942            }
3943            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3944                final PackageSetting ps = mSettings.mPackages.get(packageName);
3945                if (ps == null) return null;
3946                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3947                    return null;
3948                }
3949                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3950                    return null;
3951                }
3952                return generatePackageInfo(ps, flags, userId);
3953            }
3954        }
3955        return null;
3956    }
3957
3958    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3959        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3960            return true;
3961        }
3962        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3963            return true;
3964        }
3965        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3966            return true;
3967        }
3968        return false;
3969    }
3970
3971    private boolean isComponentVisibleToInstantApp(
3972            @Nullable ComponentName component, @ComponentType int type) {
3973        if (type == TYPE_ACTIVITY) {
3974            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3975            return activity != null
3976                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3977                    : false;
3978        } else if (type == TYPE_RECEIVER) {
3979            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3980            return activity != null
3981                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3982                    : false;
3983        } else if (type == TYPE_SERVICE) {
3984            final PackageParser.Service service = mServices.mServices.get(component);
3985            return service != null
3986                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3987                    : false;
3988        } else if (type == TYPE_PROVIDER) {
3989            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3990            return provider != null
3991                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3992                    : false;
3993        } else if (type == TYPE_UNKNOWN) {
3994            return isComponentVisibleToInstantApp(component);
3995        }
3996        return false;
3997    }
3998
3999    /**
4000     * Returns whether or not access to the application should be filtered.
4001     * <p>
4002     * Access may be limited based upon whether the calling or target applications
4003     * are instant applications.
4004     *
4005     * @see #canAccessInstantApps(int)
4006     */
4007    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4008            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4009        // if we're in an isolated process, get the real calling UID
4010        if (Process.isIsolated(callingUid)) {
4011            callingUid = mIsolatedOwners.get(callingUid);
4012        }
4013        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4014        final boolean callerIsInstantApp = instantAppPkgName != null;
4015        if (ps == null) {
4016            if (callerIsInstantApp) {
4017                // pretend the application exists, but, needs to be filtered
4018                return true;
4019            }
4020            return false;
4021        }
4022        // if the target and caller are the same application, don't filter
4023        if (isCallerSameApp(ps.name, callingUid)) {
4024            return false;
4025        }
4026        if (callerIsInstantApp) {
4027            // request for a specific component; if it hasn't been explicitly exposed, filter
4028            if (component != null) {
4029                return !isComponentVisibleToInstantApp(component, componentType);
4030            }
4031            // request for application; if no components have been explicitly exposed, filter
4032            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4033        }
4034        if (ps.getInstantApp(userId)) {
4035            // caller can see all components of all instant applications, don't filter
4036            if (canViewInstantApps(callingUid, userId)) {
4037                return false;
4038            }
4039            // request for a specific instant application component, filter
4040            if (component != null) {
4041                return true;
4042            }
4043            // request for an instant application; if the caller hasn't been granted access, filter
4044            return !mInstantAppRegistry.isInstantAccessGranted(
4045                    userId, UserHandle.getAppId(callingUid), ps.appId);
4046        }
4047        return false;
4048    }
4049
4050    /**
4051     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4052     */
4053    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4054        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4055    }
4056
4057    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4058            int flags) {
4059        // Callers can access only the libs they depend on, otherwise they need to explicitly
4060        // ask for the shared libraries given the caller is allowed to access all static libs.
4061        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4062            // System/shell/root get to see all static libs
4063            final int appId = UserHandle.getAppId(uid);
4064            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4065                    || appId == Process.ROOT_UID) {
4066                return false;
4067            }
4068        }
4069
4070        // No package means no static lib as it is always on internal storage
4071        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4072            return false;
4073        }
4074
4075        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4076                ps.pkg.staticSharedLibVersion);
4077        if (libEntry == null) {
4078            return false;
4079        }
4080
4081        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4082        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4083        if (uidPackageNames == null) {
4084            return true;
4085        }
4086
4087        for (String uidPackageName : uidPackageNames) {
4088            if (ps.name.equals(uidPackageName)) {
4089                return false;
4090            }
4091            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4092            if (uidPs != null) {
4093                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4094                        libEntry.info.getName());
4095                if (index < 0) {
4096                    continue;
4097                }
4098                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4099                    return false;
4100                }
4101            }
4102        }
4103        return true;
4104    }
4105
4106    @Override
4107    public String[] currentToCanonicalPackageNames(String[] names) {
4108        final int callingUid = Binder.getCallingUid();
4109        if (getInstantAppPackageName(callingUid) != null) {
4110            return names;
4111        }
4112        final String[] out = new String[names.length];
4113        // reader
4114        synchronized (mPackages) {
4115            final int callingUserId = UserHandle.getUserId(callingUid);
4116            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4117            for (int i=names.length-1; i>=0; i--) {
4118                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4119                boolean translateName = false;
4120                if (ps != null && ps.realName != null) {
4121                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4122                    translateName = !targetIsInstantApp
4123                            || canViewInstantApps
4124                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4125                                    UserHandle.getAppId(callingUid), ps.appId);
4126                }
4127                out[i] = translateName ? ps.realName : names[i];
4128            }
4129        }
4130        return out;
4131    }
4132
4133    @Override
4134    public String[] canonicalToCurrentPackageNames(String[] names) {
4135        final int callingUid = Binder.getCallingUid();
4136        if (getInstantAppPackageName(callingUid) != null) {
4137            return names;
4138        }
4139        final String[] out = new String[names.length];
4140        // reader
4141        synchronized (mPackages) {
4142            final int callingUserId = UserHandle.getUserId(callingUid);
4143            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4144            for (int i=names.length-1; i>=0; i--) {
4145                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4146                boolean translateName = false;
4147                if (cur != null) {
4148                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4149                    final boolean targetIsInstantApp =
4150                            ps != null && ps.getInstantApp(callingUserId);
4151                    translateName = !targetIsInstantApp
4152                            || canViewInstantApps
4153                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4154                                    UserHandle.getAppId(callingUid), ps.appId);
4155                }
4156                out[i] = translateName ? cur : names[i];
4157            }
4158        }
4159        return out;
4160    }
4161
4162    @Override
4163    public int getPackageUid(String packageName, int flags, int userId) {
4164        if (!sUserManager.exists(userId)) return -1;
4165        final int callingUid = Binder.getCallingUid();
4166        flags = updateFlagsForPackage(flags, userId, packageName);
4167        enforceCrossUserPermission(callingUid, userId,
4168                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4169
4170        // reader
4171        synchronized (mPackages) {
4172            final PackageParser.Package p = mPackages.get(packageName);
4173            if (p != null && p.isMatch(flags)) {
4174                PackageSetting ps = (PackageSetting) p.mExtras;
4175                if (filterAppAccessLPr(ps, callingUid, userId)) {
4176                    return -1;
4177                }
4178                return UserHandle.getUid(userId, p.applicationInfo.uid);
4179            }
4180            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4181                final PackageSetting ps = mSettings.mPackages.get(packageName);
4182                if (ps != null && ps.isMatch(flags)
4183                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4184                    return UserHandle.getUid(userId, ps.appId);
4185                }
4186            }
4187        }
4188
4189        return -1;
4190    }
4191
4192    @Override
4193    public int[] getPackageGids(String packageName, int flags, int userId) {
4194        if (!sUserManager.exists(userId)) return null;
4195        final int callingUid = Binder.getCallingUid();
4196        flags = updateFlagsForPackage(flags, userId, packageName);
4197        enforceCrossUserPermission(callingUid, userId,
4198                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4199
4200        // reader
4201        synchronized (mPackages) {
4202            final PackageParser.Package p = mPackages.get(packageName);
4203            if (p != null && p.isMatch(flags)) {
4204                PackageSetting ps = (PackageSetting) p.mExtras;
4205                if (filterAppAccessLPr(ps, callingUid, userId)) {
4206                    return null;
4207                }
4208                // TODO: Shouldn't this be checking for package installed state for userId and
4209                // return null?
4210                return ps.getPermissionsState().computeGids(userId);
4211            }
4212            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4213                final PackageSetting ps = mSettings.mPackages.get(packageName);
4214                if (ps != null && ps.isMatch(flags)
4215                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4216                    return ps.getPermissionsState().computeGids(userId);
4217                }
4218            }
4219        }
4220
4221        return null;
4222    }
4223
4224    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4225        if (bp.perm != null) {
4226            return PackageParser.generatePermissionInfo(bp.perm, flags);
4227        }
4228        PermissionInfo pi = new PermissionInfo();
4229        pi.name = bp.name;
4230        pi.packageName = bp.sourcePackage;
4231        pi.nonLocalizedLabel = bp.name;
4232        pi.protectionLevel = bp.protectionLevel;
4233        return pi;
4234    }
4235
4236    @Override
4237    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4238        final int callingUid = Binder.getCallingUid();
4239        if (getInstantAppPackageName(callingUid) != null) {
4240            return null;
4241        }
4242        // reader
4243        synchronized (mPackages) {
4244            final BasePermission p = mSettings.mPermissions.get(name);
4245            if (p == null) {
4246                return null;
4247            }
4248            // If the caller is an app that targets pre 26 SDK drop protection flags.
4249            PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4250            if (permissionInfo != null) {
4251                final int protectionLevel = adjustPermissionProtectionFlagsLPr(
4252                        permissionInfo.protectionLevel, packageName, callingUid);
4253                if (permissionInfo.protectionLevel != protectionLevel) {
4254                    // If we return different protection level, don't use the cached info
4255                    if (p.perm != null && p.perm.info == permissionInfo) {
4256                        permissionInfo = new PermissionInfo(permissionInfo);
4257                    }
4258                    permissionInfo.protectionLevel = protectionLevel;
4259                }
4260            }
4261            return permissionInfo;
4262        }
4263    }
4264
4265    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4266            String packageName, int uid) {
4267        // Signature permission flags area always reported
4268        final int protectionLevelMasked = protectionLevel
4269                & (PermissionInfo.PROTECTION_NORMAL
4270                | PermissionInfo.PROTECTION_DANGEROUS
4271                | PermissionInfo.PROTECTION_SIGNATURE);
4272        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4273            return protectionLevel;
4274        }
4275
4276        // System sees all flags.
4277        final int appId = UserHandle.getAppId(uid);
4278        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4279                || appId == Process.SHELL_UID) {
4280            return protectionLevel;
4281        }
4282
4283        // Normalize package name to handle renamed packages and static libs
4284        packageName = resolveInternalPackageNameLPr(packageName,
4285                PackageManager.VERSION_CODE_HIGHEST);
4286
4287        // Apps that target O see flags for all protection levels.
4288        final PackageSetting ps = mSettings.mPackages.get(packageName);
4289        if (ps == null) {
4290            return protectionLevel;
4291        }
4292        if (ps.appId != appId) {
4293            return protectionLevel;
4294        }
4295
4296        final PackageParser.Package pkg = mPackages.get(packageName);
4297        if (pkg == null) {
4298            return protectionLevel;
4299        }
4300        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4301            return protectionLevelMasked;
4302        }
4303
4304        return protectionLevel;
4305    }
4306
4307    @Override
4308    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4309            int flags) {
4310        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4311            return null;
4312        }
4313        // reader
4314        synchronized (mPackages) {
4315            if (group != null && !mPermissionGroups.containsKey(group)) {
4316                // This is thrown as NameNotFoundException
4317                return null;
4318            }
4319
4320            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4321            for (BasePermission p : mSettings.mPermissions.values()) {
4322                if (group == null) {
4323                    if (p.perm == null || p.perm.info.group == null) {
4324                        out.add(generatePermissionInfo(p, flags));
4325                    }
4326                } else {
4327                    if (p.perm != null && group.equals(p.perm.info.group)) {
4328                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4329                    }
4330                }
4331            }
4332            return new ParceledListSlice<>(out);
4333        }
4334    }
4335
4336    @Override
4337    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4338        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4339            return null;
4340        }
4341        // reader
4342        synchronized (mPackages) {
4343            return PackageParser.generatePermissionGroupInfo(
4344                    mPermissionGroups.get(name), flags);
4345        }
4346    }
4347
4348    @Override
4349    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4350        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4351            return ParceledListSlice.emptyList();
4352        }
4353        // reader
4354        synchronized (mPackages) {
4355            final int N = mPermissionGroups.size();
4356            ArrayList<PermissionGroupInfo> out
4357                    = new ArrayList<PermissionGroupInfo>(N);
4358            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4359                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4360            }
4361            return new ParceledListSlice<>(out);
4362        }
4363    }
4364
4365    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4366            int filterCallingUid, int userId) {
4367        if (!sUserManager.exists(userId)) return null;
4368        PackageSetting ps = mSettings.mPackages.get(packageName);
4369        if (ps != null) {
4370            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4371                return null;
4372            }
4373            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4374                return null;
4375            }
4376            if (ps.pkg == null) {
4377                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4378                if (pInfo != null) {
4379                    return pInfo.applicationInfo;
4380                }
4381                return null;
4382            }
4383            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4384                    ps.readUserState(userId), userId);
4385            if (ai != null) {
4386                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4387            }
4388            return ai;
4389        }
4390        return null;
4391    }
4392
4393    @Override
4394    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4395        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4396    }
4397
4398    /**
4399     * Important: The provided filterCallingUid is used exclusively to filter out applications
4400     * that can be seen based on user state. It's typically the original caller uid prior
4401     * to clearing. Because it can only be provided by trusted code, it's value can be
4402     * trusted and will be used as-is; unlike userId which will be validated by this method.
4403     */
4404    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4405            int filterCallingUid, int userId) {
4406        if (!sUserManager.exists(userId)) return null;
4407        flags = updateFlagsForApplication(flags, userId, packageName);
4408        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4409                false /* requireFullPermission */, false /* checkShell */, "get application info");
4410
4411        // writer
4412        synchronized (mPackages) {
4413            // Normalize package name to handle renamed packages and static libs
4414            packageName = resolveInternalPackageNameLPr(packageName,
4415                    PackageManager.VERSION_CODE_HIGHEST);
4416
4417            PackageParser.Package p = mPackages.get(packageName);
4418            if (DEBUG_PACKAGE_INFO) Log.v(
4419                    TAG, "getApplicationInfo " + packageName
4420                    + ": " + p);
4421            if (p != null) {
4422                PackageSetting ps = mSettings.mPackages.get(packageName);
4423                if (ps == null) return null;
4424                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4425                    return null;
4426                }
4427                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4428                    return null;
4429                }
4430                // Note: isEnabledLP() does not apply here - always return info
4431                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4432                        p, flags, ps.readUserState(userId), userId);
4433                if (ai != null) {
4434                    ai.packageName = resolveExternalPackageNameLPr(p);
4435                }
4436                return ai;
4437            }
4438            if ("android".equals(packageName)||"system".equals(packageName)) {
4439                return mAndroidApplication;
4440            }
4441            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4442                // Already generates the external package name
4443                return generateApplicationInfoFromSettingsLPw(packageName,
4444                        flags, filterCallingUid, userId);
4445            }
4446        }
4447        return null;
4448    }
4449
4450    private String normalizePackageNameLPr(String packageName) {
4451        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4452        return normalizedPackageName != null ? normalizedPackageName : packageName;
4453    }
4454
4455    @Override
4456    public void deletePreloadsFileCache() {
4457        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4458            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4459        }
4460        File dir = Environment.getDataPreloadsFileCacheDirectory();
4461        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4462        FileUtils.deleteContents(dir);
4463    }
4464
4465    @Override
4466    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4467            final int storageFlags, final IPackageDataObserver observer) {
4468        mContext.enforceCallingOrSelfPermission(
4469                android.Manifest.permission.CLEAR_APP_CACHE, null);
4470        mHandler.post(() -> {
4471            boolean success = false;
4472            try {
4473                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4474                success = true;
4475            } catch (IOException e) {
4476                Slog.w(TAG, e);
4477            }
4478            if (observer != null) {
4479                try {
4480                    observer.onRemoveCompleted(null, success);
4481                } catch (RemoteException e) {
4482                    Slog.w(TAG, e);
4483                }
4484            }
4485        });
4486    }
4487
4488    @Override
4489    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4490            final int storageFlags, final IntentSender pi) {
4491        mContext.enforceCallingOrSelfPermission(
4492                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4493        mHandler.post(() -> {
4494            boolean success = false;
4495            try {
4496                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4497                success = true;
4498            } catch (IOException e) {
4499                Slog.w(TAG, e);
4500            }
4501            if (pi != null) {
4502                try {
4503                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4504                } catch (SendIntentException e) {
4505                    Slog.w(TAG, e);
4506                }
4507            }
4508        });
4509    }
4510
4511    /**
4512     * Blocking call to clear various types of cached data across the system
4513     * until the requested bytes are available.
4514     */
4515    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4516        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4517        final File file = storage.findPathForUuid(volumeUuid);
4518        if (file.getUsableSpace() >= bytes) return;
4519
4520        if (ENABLE_FREE_CACHE_V2) {
4521            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4522                    volumeUuid);
4523            final boolean aggressive = (storageFlags
4524                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4525            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4526
4527            // 1. Pre-flight to determine if we have any chance to succeed
4528            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4529            if (internalVolume && (aggressive || SystemProperties
4530                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4531                deletePreloadsFileCache();
4532                if (file.getUsableSpace() >= bytes) return;
4533            }
4534
4535            // 3. Consider parsed APK data (aggressive only)
4536            if (internalVolume && aggressive) {
4537                FileUtils.deleteContents(mCacheDir);
4538                if (file.getUsableSpace() >= bytes) return;
4539            }
4540
4541            // 4. Consider cached app data (above quotas)
4542            try {
4543                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4544                        Installer.FLAG_FREE_CACHE_V2);
4545            } catch (InstallerException ignored) {
4546            }
4547            if (file.getUsableSpace() >= bytes) return;
4548
4549            // 5. Consider shared libraries with refcount=0 and age>min cache period
4550            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4551                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4552                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4553                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4554                return;
4555            }
4556
4557            // 6. Consider dexopt output (aggressive only)
4558            // TODO: Implement
4559
4560            // 7. Consider installed instant apps unused longer than min cache period
4561            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4562                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4563                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4564                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4565                return;
4566            }
4567
4568            // 8. Consider cached app data (below quotas)
4569            try {
4570                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4571                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4572            } catch (InstallerException ignored) {
4573            }
4574            if (file.getUsableSpace() >= bytes) return;
4575
4576            // 9. Consider DropBox entries
4577            // TODO: Implement
4578
4579            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4580            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4581                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4582                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4583                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4584                return;
4585            }
4586        } else {
4587            try {
4588                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4589            } catch (InstallerException ignored) {
4590            }
4591            if (file.getUsableSpace() >= bytes) return;
4592        }
4593
4594        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4595    }
4596
4597    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4598            throws IOException {
4599        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4600        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4601
4602        List<VersionedPackage> packagesToDelete = null;
4603        final long now = System.currentTimeMillis();
4604
4605        synchronized (mPackages) {
4606            final int[] allUsers = sUserManager.getUserIds();
4607            final int libCount = mSharedLibraries.size();
4608            for (int i = 0; i < libCount; i++) {
4609                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4610                if (versionedLib == null) {
4611                    continue;
4612                }
4613                final int versionCount = versionedLib.size();
4614                for (int j = 0; j < versionCount; j++) {
4615                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4616                    // Skip packages that are not static shared libs.
4617                    if (!libInfo.isStatic()) {
4618                        break;
4619                    }
4620                    // Important: We skip static shared libs used for some user since
4621                    // in such a case we need to keep the APK on the device. The check for
4622                    // a lib being used for any user is performed by the uninstall call.
4623                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4624                    // Resolve the package name - we use synthetic package names internally
4625                    final String internalPackageName = resolveInternalPackageNameLPr(
4626                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4627                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4628                    // Skip unused static shared libs cached less than the min period
4629                    // to prevent pruning a lib needed by a subsequently installed package.
4630                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4631                        continue;
4632                    }
4633                    if (packagesToDelete == null) {
4634                        packagesToDelete = new ArrayList<>();
4635                    }
4636                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4637                            declaringPackage.getVersionCode()));
4638                }
4639            }
4640        }
4641
4642        if (packagesToDelete != null) {
4643            final int packageCount = packagesToDelete.size();
4644            for (int i = 0; i < packageCount; i++) {
4645                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4646                // Delete the package synchronously (will fail of the lib used for any user).
4647                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4648                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4649                                == PackageManager.DELETE_SUCCEEDED) {
4650                    if (volume.getUsableSpace() >= neededSpace) {
4651                        return true;
4652                    }
4653                }
4654            }
4655        }
4656
4657        return false;
4658    }
4659
4660    /**
4661     * Update given flags based on encryption status of current user.
4662     */
4663    private int updateFlags(int flags, int userId) {
4664        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4665                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4666            // Caller expressed an explicit opinion about what encryption
4667            // aware/unaware components they want to see, so fall through and
4668            // give them what they want
4669        } else {
4670            // Caller expressed no opinion, so match based on user state
4671            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4672                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4673            } else {
4674                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4675            }
4676        }
4677        return flags;
4678    }
4679
4680    private UserManagerInternal getUserManagerInternal() {
4681        if (mUserManagerInternal == null) {
4682            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4683        }
4684        return mUserManagerInternal;
4685    }
4686
4687    private DeviceIdleController.LocalService getDeviceIdleController() {
4688        if (mDeviceIdleController == null) {
4689            mDeviceIdleController =
4690                    LocalServices.getService(DeviceIdleController.LocalService.class);
4691        }
4692        return mDeviceIdleController;
4693    }
4694
4695    /**
4696     * Update given flags when being used to request {@link PackageInfo}.
4697     */
4698    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4699        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4700        boolean triaged = true;
4701        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4702                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4703            // Caller is asking for component details, so they'd better be
4704            // asking for specific encryption matching behavior, or be triaged
4705            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4706                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4707                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4708                triaged = false;
4709            }
4710        }
4711        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4712                | PackageManager.MATCH_SYSTEM_ONLY
4713                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4714            triaged = false;
4715        }
4716        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4717            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4718                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4719                    + Debug.getCallers(5));
4720        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4721                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4722            // If the caller wants all packages and has a restricted profile associated with it,
4723            // then match all users. This is to make sure that launchers that need to access work
4724            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4725            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4726            flags |= PackageManager.MATCH_ANY_USER;
4727        }
4728        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4729            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4730                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4731        }
4732        return updateFlags(flags, userId);
4733    }
4734
4735    /**
4736     * Update given flags when being used to request {@link ApplicationInfo}.
4737     */
4738    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4739        return updateFlagsForPackage(flags, userId, cookie);
4740    }
4741
4742    /**
4743     * Update given flags when being used to request {@link ComponentInfo}.
4744     */
4745    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4746        if (cookie instanceof Intent) {
4747            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4748                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4749            }
4750        }
4751
4752        boolean triaged = true;
4753        // Caller is asking for component details, so they'd better be
4754        // asking for specific encryption matching behavior, or be triaged
4755        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4756                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4757                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4758            triaged = false;
4759        }
4760        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4761            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4762                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4763        }
4764
4765        return updateFlags(flags, userId);
4766    }
4767
4768    /**
4769     * Update given intent when being used to request {@link ResolveInfo}.
4770     */
4771    private Intent updateIntentForResolve(Intent intent) {
4772        if (intent.getSelector() != null) {
4773            intent = intent.getSelector();
4774        }
4775        if (DEBUG_PREFERRED) {
4776            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4777        }
4778        return intent;
4779    }
4780
4781    /**
4782     * Update given flags when being used to request {@link ResolveInfo}.
4783     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4784     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4785     * flag set. However, this flag is only honoured in three circumstances:
4786     * <ul>
4787     * <li>when called from a system process</li>
4788     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4789     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4790     * action and a {@code android.intent.category.BROWSABLE} category</li>
4791     * </ul>
4792     */
4793    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4794        return updateFlagsForResolve(flags, userId, intent, callingUid,
4795                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4796    }
4797    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4798            boolean wantInstantApps) {
4799        return updateFlagsForResolve(flags, userId, intent, callingUid,
4800                wantInstantApps, false /*onlyExposedExplicitly*/);
4801    }
4802    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4803            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4804        // Safe mode means we shouldn't match any third-party components
4805        if (mSafeMode) {
4806            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4807        }
4808        if (getInstantAppPackageName(callingUid) != null) {
4809            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4810            if (onlyExposedExplicitly) {
4811                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4812            }
4813            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4814            flags |= PackageManager.MATCH_INSTANT;
4815        } else {
4816            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4817            final boolean allowMatchInstant =
4818                    (wantInstantApps
4819                            && Intent.ACTION_VIEW.equals(intent.getAction())
4820                            && hasWebURI(intent))
4821                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4822            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4823                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4824            if (!allowMatchInstant) {
4825                flags &= ~PackageManager.MATCH_INSTANT;
4826            }
4827        }
4828        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4829    }
4830
4831    @Override
4832    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4833        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4834    }
4835
4836    /**
4837     * Important: The provided filterCallingUid is used exclusively to filter out activities
4838     * that can be seen based on user state. It's typically the original caller uid prior
4839     * to clearing. Because it can only be provided by trusted code, it's value can be
4840     * trusted and will be used as-is; unlike userId which will be validated by this method.
4841     */
4842    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4843            int filterCallingUid, int userId) {
4844        if (!sUserManager.exists(userId)) return null;
4845        flags = updateFlagsForComponent(flags, userId, component);
4846        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4847                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4848        synchronized (mPackages) {
4849            PackageParser.Activity a = mActivities.mActivities.get(component);
4850
4851            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4852            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4853                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4854                if (ps == null) return null;
4855                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4856                    return null;
4857                }
4858                return PackageParser.generateActivityInfo(
4859                        a, flags, ps.readUserState(userId), userId);
4860            }
4861            if (mResolveComponentName.equals(component)) {
4862                return PackageParser.generateActivityInfo(
4863                        mResolveActivity, flags, new PackageUserState(), userId);
4864            }
4865        }
4866        return null;
4867    }
4868
4869    @Override
4870    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4871            String resolvedType) {
4872        synchronized (mPackages) {
4873            if (component.equals(mResolveComponentName)) {
4874                // The resolver supports EVERYTHING!
4875                return true;
4876            }
4877            final int callingUid = Binder.getCallingUid();
4878            final int callingUserId = UserHandle.getUserId(callingUid);
4879            PackageParser.Activity a = mActivities.mActivities.get(component);
4880            if (a == null) {
4881                return false;
4882            }
4883            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4884            if (ps == null) {
4885                return false;
4886            }
4887            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4888                return false;
4889            }
4890            for (int i=0; i<a.intents.size(); i++) {
4891                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4892                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4893                    return true;
4894                }
4895            }
4896            return false;
4897        }
4898    }
4899
4900    @Override
4901    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4902        if (!sUserManager.exists(userId)) return null;
4903        final int callingUid = Binder.getCallingUid();
4904        flags = updateFlagsForComponent(flags, userId, component);
4905        enforceCrossUserPermission(callingUid, userId,
4906                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4907        synchronized (mPackages) {
4908            PackageParser.Activity a = mReceivers.mActivities.get(component);
4909            if (DEBUG_PACKAGE_INFO) Log.v(
4910                TAG, "getReceiverInfo " + component + ": " + a);
4911            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4912                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4913                if (ps == null) return null;
4914                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4915                    return null;
4916                }
4917                return PackageParser.generateActivityInfo(
4918                        a, flags, ps.readUserState(userId), userId);
4919            }
4920        }
4921        return null;
4922    }
4923
4924    @Override
4925    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4926            int flags, int userId) {
4927        if (!sUserManager.exists(userId)) return null;
4928        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4929        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4930            return null;
4931        }
4932
4933        flags = updateFlagsForPackage(flags, userId, null);
4934
4935        final boolean canSeeStaticLibraries =
4936                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4937                        == PERMISSION_GRANTED
4938                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4939                        == PERMISSION_GRANTED
4940                || canRequestPackageInstallsInternal(packageName,
4941                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4942                        false  /* throwIfPermNotDeclared*/)
4943                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4944                        == PERMISSION_GRANTED;
4945
4946        synchronized (mPackages) {
4947            List<SharedLibraryInfo> result = null;
4948
4949            final int libCount = mSharedLibraries.size();
4950            for (int i = 0; i < libCount; i++) {
4951                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4952                if (versionedLib == null) {
4953                    continue;
4954                }
4955
4956                final int versionCount = versionedLib.size();
4957                for (int j = 0; j < versionCount; j++) {
4958                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4959                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4960                        break;
4961                    }
4962                    final long identity = Binder.clearCallingIdentity();
4963                    try {
4964                        PackageInfo packageInfo = getPackageInfoVersioned(
4965                                libInfo.getDeclaringPackage(), flags
4966                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4967                        if (packageInfo == null) {
4968                            continue;
4969                        }
4970                    } finally {
4971                        Binder.restoreCallingIdentity(identity);
4972                    }
4973
4974                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4975                            libInfo.getVersion(), libInfo.getType(),
4976                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4977                            flags, userId));
4978
4979                    if (result == null) {
4980                        result = new ArrayList<>();
4981                    }
4982                    result.add(resLibInfo);
4983                }
4984            }
4985
4986            return result != null ? new ParceledListSlice<>(result) : null;
4987        }
4988    }
4989
4990    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4991            SharedLibraryInfo libInfo, int flags, int userId) {
4992        List<VersionedPackage> versionedPackages = null;
4993        final int packageCount = mSettings.mPackages.size();
4994        for (int i = 0; i < packageCount; i++) {
4995            PackageSetting ps = mSettings.mPackages.valueAt(i);
4996
4997            if (ps == null) {
4998                continue;
4999            }
5000
5001            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5002                continue;
5003            }
5004
5005            final String libName = libInfo.getName();
5006            if (libInfo.isStatic()) {
5007                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5008                if (libIdx < 0) {
5009                    continue;
5010                }
5011                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5012                    continue;
5013                }
5014                if (versionedPackages == null) {
5015                    versionedPackages = new ArrayList<>();
5016                }
5017                // If the dependent is a static shared lib, use the public package name
5018                String dependentPackageName = ps.name;
5019                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5020                    dependentPackageName = ps.pkg.manifestPackageName;
5021                }
5022                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5023            } else if (ps.pkg != null) {
5024                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5025                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5026                    if (versionedPackages == null) {
5027                        versionedPackages = new ArrayList<>();
5028                    }
5029                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5030                }
5031            }
5032        }
5033
5034        return versionedPackages;
5035    }
5036
5037    @Override
5038    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5039        if (!sUserManager.exists(userId)) return null;
5040        final int callingUid = Binder.getCallingUid();
5041        flags = updateFlagsForComponent(flags, userId, component);
5042        enforceCrossUserPermission(callingUid, userId,
5043                false /* requireFullPermission */, false /* checkShell */, "get service info");
5044        synchronized (mPackages) {
5045            PackageParser.Service s = mServices.mServices.get(component);
5046            if (DEBUG_PACKAGE_INFO) Log.v(
5047                TAG, "getServiceInfo " + component + ": " + s);
5048            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5049                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5050                if (ps == null) return null;
5051                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5052                    return null;
5053                }
5054                return PackageParser.generateServiceInfo(
5055                        s, flags, ps.readUserState(userId), userId);
5056            }
5057        }
5058        return null;
5059    }
5060
5061    @Override
5062    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5063        if (!sUserManager.exists(userId)) return null;
5064        final int callingUid = Binder.getCallingUid();
5065        flags = updateFlagsForComponent(flags, userId, component);
5066        enforceCrossUserPermission(callingUid, userId,
5067                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5068        synchronized (mPackages) {
5069            PackageParser.Provider p = mProviders.mProviders.get(component);
5070            if (DEBUG_PACKAGE_INFO) Log.v(
5071                TAG, "getProviderInfo " + component + ": " + p);
5072            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5073                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5074                if (ps == null) return null;
5075                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5076                    return null;
5077                }
5078                return PackageParser.generateProviderInfo(
5079                        p, flags, ps.readUserState(userId), userId);
5080            }
5081        }
5082        return null;
5083    }
5084
5085    @Override
5086    public String[] getSystemSharedLibraryNames() {
5087        // allow instant applications
5088        synchronized (mPackages) {
5089            Set<String> libs = null;
5090            final int libCount = mSharedLibraries.size();
5091            for (int i = 0; i < libCount; i++) {
5092                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5093                if (versionedLib == null) {
5094                    continue;
5095                }
5096                final int versionCount = versionedLib.size();
5097                for (int j = 0; j < versionCount; j++) {
5098                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5099                    if (!libEntry.info.isStatic()) {
5100                        if (libs == null) {
5101                            libs = new ArraySet<>();
5102                        }
5103                        libs.add(libEntry.info.getName());
5104                        break;
5105                    }
5106                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5107                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5108                            UserHandle.getUserId(Binder.getCallingUid()),
5109                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5110                        if (libs == null) {
5111                            libs = new ArraySet<>();
5112                        }
5113                        libs.add(libEntry.info.getName());
5114                        break;
5115                    }
5116                }
5117            }
5118
5119            if (libs != null) {
5120                String[] libsArray = new String[libs.size()];
5121                libs.toArray(libsArray);
5122                return libsArray;
5123            }
5124
5125            return null;
5126        }
5127    }
5128
5129    @Override
5130    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5131        // allow instant applications
5132        synchronized (mPackages) {
5133            return mServicesSystemSharedLibraryPackageName;
5134        }
5135    }
5136
5137    @Override
5138    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5139        // allow instant applications
5140        synchronized (mPackages) {
5141            return mSharedSystemSharedLibraryPackageName;
5142        }
5143    }
5144
5145    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5146        for (int i = userList.length - 1; i >= 0; --i) {
5147            final int userId = userList[i];
5148            // don't add instant app to the list of updates
5149            if (pkgSetting.getInstantApp(userId)) {
5150                continue;
5151            }
5152            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5153            if (changedPackages == null) {
5154                changedPackages = new SparseArray<>();
5155                mChangedPackages.put(userId, changedPackages);
5156            }
5157            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5158            if (sequenceNumbers == null) {
5159                sequenceNumbers = new HashMap<>();
5160                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5161            }
5162            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5163            if (sequenceNumber != null) {
5164                changedPackages.remove(sequenceNumber);
5165            }
5166            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5167            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5168        }
5169        mChangedPackagesSequenceNumber++;
5170    }
5171
5172    @Override
5173    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5174        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5175            return null;
5176        }
5177        synchronized (mPackages) {
5178            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5179                return null;
5180            }
5181            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5182            if (changedPackages == null) {
5183                return null;
5184            }
5185            final List<String> packageNames =
5186                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5187            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5188                final String packageName = changedPackages.get(i);
5189                if (packageName != null) {
5190                    packageNames.add(packageName);
5191                }
5192            }
5193            return packageNames.isEmpty()
5194                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5195        }
5196    }
5197
5198    @Override
5199    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5200        // allow instant applications
5201        ArrayList<FeatureInfo> res;
5202        synchronized (mAvailableFeatures) {
5203            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5204            res.addAll(mAvailableFeatures.values());
5205        }
5206        final FeatureInfo fi = new FeatureInfo();
5207        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5208                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5209        res.add(fi);
5210
5211        return new ParceledListSlice<>(res);
5212    }
5213
5214    @Override
5215    public boolean hasSystemFeature(String name, int version) {
5216        // allow instant applications
5217        synchronized (mAvailableFeatures) {
5218            final FeatureInfo feat = mAvailableFeatures.get(name);
5219            if (feat == null) {
5220                return false;
5221            } else {
5222                return feat.version >= version;
5223            }
5224        }
5225    }
5226
5227    @Override
5228    public int checkPermission(String permName, String pkgName, int userId) {
5229        if (!sUserManager.exists(userId)) {
5230            return PackageManager.PERMISSION_DENIED;
5231        }
5232        final int callingUid = Binder.getCallingUid();
5233
5234        synchronized (mPackages) {
5235            final PackageParser.Package p = mPackages.get(pkgName);
5236            if (p != null && p.mExtras != null) {
5237                final PackageSetting ps = (PackageSetting) p.mExtras;
5238                if (filterAppAccessLPr(ps, callingUid, userId)) {
5239                    return PackageManager.PERMISSION_DENIED;
5240                }
5241                final boolean instantApp = ps.getInstantApp(userId);
5242                final PermissionsState permissionsState = ps.getPermissionsState();
5243                if (permissionsState.hasPermission(permName, userId)) {
5244                    if (instantApp) {
5245                        BasePermission bp = mSettings.mPermissions.get(permName);
5246                        if (bp != null && bp.isInstant()) {
5247                            return PackageManager.PERMISSION_GRANTED;
5248                        }
5249                    } else {
5250                        return PackageManager.PERMISSION_GRANTED;
5251                    }
5252                }
5253                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5254                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5255                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5256                    return PackageManager.PERMISSION_GRANTED;
5257                }
5258            }
5259        }
5260
5261        return PackageManager.PERMISSION_DENIED;
5262    }
5263
5264    @Override
5265    public int checkUidPermission(String permName, int uid) {
5266        final int callingUid = Binder.getCallingUid();
5267        final int callingUserId = UserHandle.getUserId(callingUid);
5268        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5269        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5270        final int userId = UserHandle.getUserId(uid);
5271        if (!sUserManager.exists(userId)) {
5272            return PackageManager.PERMISSION_DENIED;
5273        }
5274
5275        synchronized (mPackages) {
5276            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5277            if (obj != null) {
5278                if (obj instanceof SharedUserSetting) {
5279                    if (isCallerInstantApp) {
5280                        return PackageManager.PERMISSION_DENIED;
5281                    }
5282                } else if (obj instanceof PackageSetting) {
5283                    final PackageSetting ps = (PackageSetting) obj;
5284                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5285                        return PackageManager.PERMISSION_DENIED;
5286                    }
5287                }
5288                final SettingBase settingBase = (SettingBase) obj;
5289                final PermissionsState permissionsState = settingBase.getPermissionsState();
5290                if (permissionsState.hasPermission(permName, userId)) {
5291                    if (isUidInstantApp) {
5292                        BasePermission bp = mSettings.mPermissions.get(permName);
5293                        if (bp != null && bp.isInstant()) {
5294                            return PackageManager.PERMISSION_GRANTED;
5295                        }
5296                    } else {
5297                        return PackageManager.PERMISSION_GRANTED;
5298                    }
5299                }
5300                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5301                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5302                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5303                    return PackageManager.PERMISSION_GRANTED;
5304                }
5305            } else {
5306                ArraySet<String> perms = mSystemPermissions.get(uid);
5307                if (perms != null) {
5308                    if (perms.contains(permName)) {
5309                        return PackageManager.PERMISSION_GRANTED;
5310                    }
5311                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5312                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5313                        return PackageManager.PERMISSION_GRANTED;
5314                    }
5315                }
5316            }
5317        }
5318
5319        return PackageManager.PERMISSION_DENIED;
5320    }
5321
5322    @Override
5323    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5324        if (UserHandle.getCallingUserId() != userId) {
5325            mContext.enforceCallingPermission(
5326                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5327                    "isPermissionRevokedByPolicy for user " + userId);
5328        }
5329
5330        if (checkPermission(permission, packageName, userId)
5331                == PackageManager.PERMISSION_GRANTED) {
5332            return false;
5333        }
5334
5335        final int callingUid = Binder.getCallingUid();
5336        if (getInstantAppPackageName(callingUid) != null) {
5337            if (!isCallerSameApp(packageName, callingUid)) {
5338                return false;
5339            }
5340        } else {
5341            if (isInstantApp(packageName, userId)) {
5342                return false;
5343            }
5344        }
5345
5346        final long identity = Binder.clearCallingIdentity();
5347        try {
5348            final int flags = getPermissionFlags(permission, packageName, userId);
5349            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5350        } finally {
5351            Binder.restoreCallingIdentity(identity);
5352        }
5353    }
5354
5355    @Override
5356    public String getPermissionControllerPackageName() {
5357        synchronized (mPackages) {
5358            return mRequiredInstallerPackage;
5359        }
5360    }
5361
5362    /**
5363     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5364     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5365     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5366     * @param message the message to log on security exception
5367     */
5368    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5369            boolean checkShell, String message) {
5370        if (userId < 0) {
5371            throw new IllegalArgumentException("Invalid userId " + userId);
5372        }
5373        if (checkShell) {
5374            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5375        }
5376        if (userId == UserHandle.getUserId(callingUid)) return;
5377        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5378            if (requireFullPermission) {
5379                mContext.enforceCallingOrSelfPermission(
5380                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5381            } else {
5382                try {
5383                    mContext.enforceCallingOrSelfPermission(
5384                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5385                } catch (SecurityException se) {
5386                    mContext.enforceCallingOrSelfPermission(
5387                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5388                }
5389            }
5390        }
5391    }
5392
5393    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5394        if (callingUid == Process.SHELL_UID) {
5395            if (userHandle >= 0
5396                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5397                throw new SecurityException("Shell does not have permission to access user "
5398                        + userHandle);
5399            } else if (userHandle < 0) {
5400                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5401                        + Debug.getCallers(3));
5402            }
5403        }
5404    }
5405
5406    private BasePermission findPermissionTreeLP(String permName) {
5407        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5408            if (permName.startsWith(bp.name) &&
5409                    permName.length() > bp.name.length() &&
5410                    permName.charAt(bp.name.length()) == '.') {
5411                return bp;
5412            }
5413        }
5414        return null;
5415    }
5416
5417    private BasePermission checkPermissionTreeLP(String permName) {
5418        if (permName != null) {
5419            BasePermission bp = findPermissionTreeLP(permName);
5420            if (bp != null) {
5421                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5422                    return bp;
5423                }
5424                throw new SecurityException("Calling uid "
5425                        + Binder.getCallingUid()
5426                        + " is not allowed to add to permission tree "
5427                        + bp.name + " owned by uid " + bp.uid);
5428            }
5429        }
5430        throw new SecurityException("No permission tree found for " + permName);
5431    }
5432
5433    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5434        if (s1 == null) {
5435            return s2 == null;
5436        }
5437        if (s2 == null) {
5438            return false;
5439        }
5440        if (s1.getClass() != s2.getClass()) {
5441            return false;
5442        }
5443        return s1.equals(s2);
5444    }
5445
5446    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5447        if (pi1.icon != pi2.icon) return false;
5448        if (pi1.logo != pi2.logo) return false;
5449        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5450        if (!compareStrings(pi1.name, pi2.name)) return false;
5451        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5452        // We'll take care of setting this one.
5453        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5454        // These are not currently stored in settings.
5455        //if (!compareStrings(pi1.group, pi2.group)) return false;
5456        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5457        //if (pi1.labelRes != pi2.labelRes) return false;
5458        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5459        return true;
5460    }
5461
5462    int permissionInfoFootprint(PermissionInfo info) {
5463        int size = info.name.length();
5464        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5465        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5466        return size;
5467    }
5468
5469    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5470        int size = 0;
5471        for (BasePermission perm : mSettings.mPermissions.values()) {
5472            if (perm.uid == tree.uid) {
5473                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5474            }
5475        }
5476        return size;
5477    }
5478
5479    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5480        // We calculate the max size of permissions defined by this uid and throw
5481        // if that plus the size of 'info' would exceed our stated maximum.
5482        if (tree.uid != Process.SYSTEM_UID) {
5483            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5484            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5485                throw new SecurityException("Permission tree size cap exceeded");
5486            }
5487        }
5488    }
5489
5490    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5491        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5492            throw new SecurityException("Instant apps can't add permissions");
5493        }
5494        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5495            throw new SecurityException("Label must be specified in permission");
5496        }
5497        BasePermission tree = checkPermissionTreeLP(info.name);
5498        BasePermission bp = mSettings.mPermissions.get(info.name);
5499        boolean added = bp == null;
5500        boolean changed = true;
5501        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5502        if (added) {
5503            enforcePermissionCapLocked(info, tree);
5504            bp = new BasePermission(info.name, tree.sourcePackage,
5505                    BasePermission.TYPE_DYNAMIC);
5506        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5507            throw new SecurityException(
5508                    "Not allowed to modify non-dynamic permission "
5509                    + info.name);
5510        } else {
5511            if (bp.protectionLevel == fixedLevel
5512                    && bp.perm.owner.equals(tree.perm.owner)
5513                    && bp.uid == tree.uid
5514                    && comparePermissionInfos(bp.perm.info, info)) {
5515                changed = false;
5516            }
5517        }
5518        bp.protectionLevel = fixedLevel;
5519        info = new PermissionInfo(info);
5520        info.protectionLevel = fixedLevel;
5521        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5522        bp.perm.info.packageName = tree.perm.info.packageName;
5523        bp.uid = tree.uid;
5524        if (added) {
5525            mSettings.mPermissions.put(info.name, bp);
5526        }
5527        if (changed) {
5528            if (!async) {
5529                mSettings.writeLPr();
5530            } else {
5531                scheduleWriteSettingsLocked();
5532            }
5533        }
5534        return added;
5535    }
5536
5537    @Override
5538    public boolean addPermission(PermissionInfo info) {
5539        synchronized (mPackages) {
5540            return addPermissionLocked(info, false);
5541        }
5542    }
5543
5544    @Override
5545    public boolean addPermissionAsync(PermissionInfo info) {
5546        synchronized (mPackages) {
5547            return addPermissionLocked(info, true);
5548        }
5549    }
5550
5551    @Override
5552    public void removePermission(String name) {
5553        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5554            throw new SecurityException("Instant applications don't have access to this method");
5555        }
5556        synchronized (mPackages) {
5557            checkPermissionTreeLP(name);
5558            BasePermission bp = mSettings.mPermissions.get(name);
5559            if (bp != null) {
5560                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5561                    throw new SecurityException(
5562                            "Not allowed to modify non-dynamic permission "
5563                            + name);
5564                }
5565                mSettings.mPermissions.remove(name);
5566                mSettings.writeLPr();
5567            }
5568        }
5569    }
5570
5571    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5572            PackageParser.Package pkg, BasePermission bp) {
5573        int index = pkg.requestedPermissions.indexOf(bp.name);
5574        if (index == -1) {
5575            throw new SecurityException("Package " + pkg.packageName
5576                    + " has not requested permission " + bp.name);
5577        }
5578        if (!bp.isRuntime() && !bp.isDevelopment()) {
5579            throw new SecurityException("Permission " + bp.name
5580                    + " is not a changeable permission type");
5581        }
5582    }
5583
5584    @Override
5585    public void grantRuntimePermission(String packageName, String name, final int userId) {
5586        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5587    }
5588
5589    private void grantRuntimePermission(String packageName, String name, final int userId,
5590            boolean overridePolicy) {
5591        if (!sUserManager.exists(userId)) {
5592            Log.e(TAG, "No such user:" + userId);
5593            return;
5594        }
5595        final int callingUid = Binder.getCallingUid();
5596
5597        mContext.enforceCallingOrSelfPermission(
5598                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5599                "grantRuntimePermission");
5600
5601        enforceCrossUserPermission(callingUid, userId,
5602                true /* requireFullPermission */, true /* checkShell */,
5603                "grantRuntimePermission");
5604
5605        final int uid;
5606        final PackageSetting ps;
5607
5608        synchronized (mPackages) {
5609            final PackageParser.Package pkg = mPackages.get(packageName);
5610            if (pkg == null) {
5611                throw new IllegalArgumentException("Unknown package: " + packageName);
5612            }
5613            final BasePermission bp = mSettings.mPermissions.get(name);
5614            if (bp == null) {
5615                throw new IllegalArgumentException("Unknown permission: " + name);
5616            }
5617            ps = (PackageSetting) pkg.mExtras;
5618            if (ps == null
5619                    || filterAppAccessLPr(ps, callingUid, userId)) {
5620                throw new IllegalArgumentException("Unknown package: " + packageName);
5621            }
5622
5623            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5624
5625            // If a permission review is required for legacy apps we represent
5626            // their permissions as always granted runtime ones since we need
5627            // to keep the review required permission flag per user while an
5628            // install permission's state is shared across all users.
5629            if (mPermissionReviewRequired
5630                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5631                    && bp.isRuntime()) {
5632                return;
5633            }
5634
5635            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5636
5637            final PermissionsState permissionsState = ps.getPermissionsState();
5638
5639            final int flags = permissionsState.getPermissionFlags(name, userId);
5640            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5641                throw new SecurityException("Cannot grant system fixed permission "
5642                        + name + " for package " + packageName);
5643            }
5644            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5645                throw new SecurityException("Cannot grant policy fixed permission "
5646                        + name + " for package " + packageName);
5647            }
5648
5649            if (bp.isDevelopment()) {
5650                // Development permissions must be handled specially, since they are not
5651                // normal runtime permissions.  For now they apply to all users.
5652                if (permissionsState.grantInstallPermission(bp) !=
5653                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5654                    scheduleWriteSettingsLocked();
5655                }
5656                return;
5657            }
5658
5659            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5660                throw new SecurityException("Cannot grant non-ephemeral permission"
5661                        + name + " for package " + packageName);
5662            }
5663
5664            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5665                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5666                return;
5667            }
5668
5669            final int result = permissionsState.grantRuntimePermission(bp, userId);
5670            switch (result) {
5671                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5672                    return;
5673                }
5674
5675                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5676                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5677                    mHandler.post(new Runnable() {
5678                        @Override
5679                        public void run() {
5680                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5681                        }
5682                    });
5683                }
5684                break;
5685            }
5686
5687            if (bp.isRuntime()) {
5688                logPermissionGranted(mContext, name, packageName);
5689            }
5690
5691            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5692
5693            // Not critical if that is lost - app has to request again.
5694            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5695        }
5696
5697        // Only need to do this if user is initialized. Otherwise it's a new user
5698        // and there are no processes running as the user yet and there's no need
5699        // to make an expensive call to remount processes for the changed permissions.
5700        if (READ_EXTERNAL_STORAGE.equals(name)
5701                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5702            final long token = Binder.clearCallingIdentity();
5703            try {
5704                if (sUserManager.isInitialized(userId)) {
5705                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5706                            StorageManagerInternal.class);
5707                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5708                }
5709            } finally {
5710                Binder.restoreCallingIdentity(token);
5711            }
5712        }
5713    }
5714
5715    @Override
5716    public void revokeRuntimePermission(String packageName, String name, int userId) {
5717        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5718    }
5719
5720    private void revokeRuntimePermission(String packageName, String name, int userId,
5721            boolean overridePolicy) {
5722        if (!sUserManager.exists(userId)) {
5723            Log.e(TAG, "No such user:" + userId);
5724            return;
5725        }
5726
5727        mContext.enforceCallingOrSelfPermission(
5728                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5729                "revokeRuntimePermission");
5730
5731        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5732                true /* requireFullPermission */, true /* checkShell */,
5733                "revokeRuntimePermission");
5734
5735        final int appId;
5736
5737        synchronized (mPackages) {
5738            final PackageParser.Package pkg = mPackages.get(packageName);
5739            if (pkg == null) {
5740                throw new IllegalArgumentException("Unknown package: " + packageName);
5741            }
5742            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5743            if (ps == null
5744                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5745                throw new IllegalArgumentException("Unknown package: " + packageName);
5746            }
5747            final BasePermission bp = mSettings.mPermissions.get(name);
5748            if (bp == null) {
5749                throw new IllegalArgumentException("Unknown permission: " + name);
5750            }
5751
5752            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5753
5754            // If a permission review is required for legacy apps we represent
5755            // their permissions as always granted runtime ones since we need
5756            // to keep the review required permission flag per user while an
5757            // install permission's state is shared across all users.
5758            if (mPermissionReviewRequired
5759                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5760                    && bp.isRuntime()) {
5761                return;
5762            }
5763
5764            final PermissionsState permissionsState = ps.getPermissionsState();
5765
5766            final int flags = permissionsState.getPermissionFlags(name, userId);
5767            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5768                throw new SecurityException("Cannot revoke system fixed permission "
5769                        + name + " for package " + packageName);
5770            }
5771            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5772                throw new SecurityException("Cannot revoke policy fixed permission "
5773                        + name + " for package " + packageName);
5774            }
5775
5776            if (bp.isDevelopment()) {
5777                // Development permissions must be handled specially, since they are not
5778                // normal runtime permissions.  For now they apply to all users.
5779                if (permissionsState.revokeInstallPermission(bp) !=
5780                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5781                    scheduleWriteSettingsLocked();
5782                }
5783                return;
5784            }
5785
5786            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5787                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5788                return;
5789            }
5790
5791            if (bp.isRuntime()) {
5792                logPermissionRevoked(mContext, name, packageName);
5793            }
5794
5795            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5796
5797            // Critical, after this call app should never have the permission.
5798            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5799
5800            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5801        }
5802
5803        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5804    }
5805
5806    /**
5807     * Get the first event id for the permission.
5808     *
5809     * <p>There are four events for each permission: <ul>
5810     *     <li>Request permission: first id + 0</li>
5811     *     <li>Grant permission: first id + 1</li>
5812     *     <li>Request for permission denied: first id + 2</li>
5813     *     <li>Revoke permission: first id + 3</li>
5814     * </ul></p>
5815     *
5816     * @param name name of the permission
5817     *
5818     * @return The first event id for the permission
5819     */
5820    private static int getBaseEventId(@NonNull String name) {
5821        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5822
5823        if (eventIdIndex == -1) {
5824            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5825                    || Build.IS_USER) {
5826                Log.i(TAG, "Unknown permission " + name);
5827
5828                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5829            } else {
5830                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5831                //
5832                // Also update
5833                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5834                // - metrics_constants.proto
5835                throw new IllegalStateException("Unknown permission " + name);
5836            }
5837        }
5838
5839        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5840    }
5841
5842    /**
5843     * Log that a permission was revoked.
5844     *
5845     * @param context Context of the caller
5846     * @param name name of the permission
5847     * @param packageName package permission if for
5848     */
5849    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5850            @NonNull String packageName) {
5851        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5852    }
5853
5854    /**
5855     * Log that a permission request was granted.
5856     *
5857     * @param context Context of the caller
5858     * @param name name of the permission
5859     * @param packageName package permission if for
5860     */
5861    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5862            @NonNull String packageName) {
5863        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5864    }
5865
5866    @Override
5867    public void resetRuntimePermissions() {
5868        mContext.enforceCallingOrSelfPermission(
5869                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5870                "revokeRuntimePermission");
5871
5872        int callingUid = Binder.getCallingUid();
5873        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5874            mContext.enforceCallingOrSelfPermission(
5875                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5876                    "resetRuntimePermissions");
5877        }
5878
5879        synchronized (mPackages) {
5880            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5881            for (int userId : UserManagerService.getInstance().getUserIds()) {
5882                final int packageCount = mPackages.size();
5883                for (int i = 0; i < packageCount; i++) {
5884                    PackageParser.Package pkg = mPackages.valueAt(i);
5885                    if (!(pkg.mExtras instanceof PackageSetting)) {
5886                        continue;
5887                    }
5888                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5889                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5890                }
5891            }
5892        }
5893    }
5894
5895    @Override
5896    public int getPermissionFlags(String name, String packageName, int userId) {
5897        if (!sUserManager.exists(userId)) {
5898            return 0;
5899        }
5900
5901        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5902
5903        final int callingUid = Binder.getCallingUid();
5904        enforceCrossUserPermission(callingUid, userId,
5905                true /* requireFullPermission */, false /* checkShell */,
5906                "getPermissionFlags");
5907
5908        synchronized (mPackages) {
5909            final PackageParser.Package pkg = mPackages.get(packageName);
5910            if (pkg == null) {
5911                return 0;
5912            }
5913            final BasePermission bp = mSettings.mPermissions.get(name);
5914            if (bp == null) {
5915                return 0;
5916            }
5917            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5918            if (ps == null
5919                    || filterAppAccessLPr(ps, callingUid, userId)) {
5920                return 0;
5921            }
5922            PermissionsState permissionsState = ps.getPermissionsState();
5923            return permissionsState.getPermissionFlags(name, userId);
5924        }
5925    }
5926
5927    @Override
5928    public void updatePermissionFlags(String name, String packageName, int flagMask,
5929            int flagValues, int userId) {
5930        if (!sUserManager.exists(userId)) {
5931            return;
5932        }
5933
5934        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5935
5936        final int callingUid = Binder.getCallingUid();
5937        enforceCrossUserPermission(callingUid, userId,
5938                true /* requireFullPermission */, true /* checkShell */,
5939                "updatePermissionFlags");
5940
5941        // Only the system can change these flags and nothing else.
5942        if (getCallingUid() != Process.SYSTEM_UID) {
5943            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5944            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5945            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5946            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5947            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5948        }
5949
5950        synchronized (mPackages) {
5951            final PackageParser.Package pkg = mPackages.get(packageName);
5952            if (pkg == null) {
5953                throw new IllegalArgumentException("Unknown package: " + packageName);
5954            }
5955            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5956            if (ps == null
5957                    || filterAppAccessLPr(ps, callingUid, userId)) {
5958                throw new IllegalArgumentException("Unknown package: " + packageName);
5959            }
5960
5961            final BasePermission bp = mSettings.mPermissions.get(name);
5962            if (bp == null) {
5963                throw new IllegalArgumentException("Unknown permission: " + name);
5964            }
5965
5966            PermissionsState permissionsState = ps.getPermissionsState();
5967
5968            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5969
5970            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5971                // Install and runtime permissions are stored in different places,
5972                // so figure out what permission changed and persist the change.
5973                if (permissionsState.getInstallPermissionState(name) != null) {
5974                    scheduleWriteSettingsLocked();
5975                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5976                        || hadState) {
5977                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5978                }
5979            }
5980        }
5981    }
5982
5983    /**
5984     * Update the permission flags for all packages and runtime permissions of a user in order
5985     * to allow device or profile owner to remove POLICY_FIXED.
5986     */
5987    @Override
5988    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5989        if (!sUserManager.exists(userId)) {
5990            return;
5991        }
5992
5993        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5994
5995        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5996                true /* requireFullPermission */, true /* checkShell */,
5997                "updatePermissionFlagsForAllApps");
5998
5999        // Only the system can change system fixed flags.
6000        if (getCallingUid() != Process.SYSTEM_UID) {
6001            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6002            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6003        }
6004
6005        synchronized (mPackages) {
6006            boolean changed = false;
6007            final int packageCount = mPackages.size();
6008            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6009                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6010                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6011                if (ps == null) {
6012                    continue;
6013                }
6014                PermissionsState permissionsState = ps.getPermissionsState();
6015                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6016                        userId, flagMask, flagValues);
6017            }
6018            if (changed) {
6019                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6020            }
6021        }
6022    }
6023
6024    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6025        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6026                != PackageManager.PERMISSION_GRANTED
6027            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6028                != PackageManager.PERMISSION_GRANTED) {
6029            throw new SecurityException(message + " requires "
6030                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6031                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6032        }
6033    }
6034
6035    @Override
6036    public boolean shouldShowRequestPermissionRationale(String permissionName,
6037            String packageName, int userId) {
6038        if (UserHandle.getCallingUserId() != userId) {
6039            mContext.enforceCallingPermission(
6040                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6041                    "canShowRequestPermissionRationale for user " + userId);
6042        }
6043
6044        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6045        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6046            return false;
6047        }
6048
6049        if (checkPermission(permissionName, packageName, userId)
6050                == PackageManager.PERMISSION_GRANTED) {
6051            return false;
6052        }
6053
6054        final int flags;
6055
6056        final long identity = Binder.clearCallingIdentity();
6057        try {
6058            flags = getPermissionFlags(permissionName,
6059                    packageName, userId);
6060        } finally {
6061            Binder.restoreCallingIdentity(identity);
6062        }
6063
6064        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6065                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6066                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6067
6068        if ((flags & fixedFlags) != 0) {
6069            return false;
6070        }
6071
6072        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6073    }
6074
6075    @Override
6076    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6077        mContext.enforceCallingOrSelfPermission(
6078                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6079                "addOnPermissionsChangeListener");
6080
6081        synchronized (mPackages) {
6082            mOnPermissionChangeListeners.addListenerLocked(listener);
6083        }
6084    }
6085
6086    @Override
6087    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6088        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6089            throw new SecurityException("Instant applications don't have access to this method");
6090        }
6091        synchronized (mPackages) {
6092            mOnPermissionChangeListeners.removeListenerLocked(listener);
6093        }
6094    }
6095
6096    @Override
6097    public boolean isProtectedBroadcast(String actionName) {
6098        // allow instant applications
6099        synchronized (mProtectedBroadcasts) {
6100            if (mProtectedBroadcasts.contains(actionName)) {
6101                return true;
6102            } else if (actionName != null) {
6103                // TODO: remove these terrible hacks
6104                if (actionName.startsWith("android.net.netmon.lingerExpired")
6105                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6106                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6107                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6108                    return true;
6109                }
6110            }
6111        }
6112        return false;
6113    }
6114
6115    @Override
6116    public int checkSignatures(String pkg1, String pkg2) {
6117        synchronized (mPackages) {
6118            final PackageParser.Package p1 = mPackages.get(pkg1);
6119            final PackageParser.Package p2 = mPackages.get(pkg2);
6120            if (p1 == null || p1.mExtras == null
6121                    || p2 == null || p2.mExtras == null) {
6122                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6123            }
6124            final int callingUid = Binder.getCallingUid();
6125            final int callingUserId = UserHandle.getUserId(callingUid);
6126            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6127            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6128            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6129                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6130                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6131            }
6132            return compareSignatures(p1.mSignatures, p2.mSignatures);
6133        }
6134    }
6135
6136    @Override
6137    public int checkUidSignatures(int uid1, int uid2) {
6138        final int callingUid = Binder.getCallingUid();
6139        final int callingUserId = UserHandle.getUserId(callingUid);
6140        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6141        // Map to base uids.
6142        uid1 = UserHandle.getAppId(uid1);
6143        uid2 = UserHandle.getAppId(uid2);
6144        // reader
6145        synchronized (mPackages) {
6146            Signature[] s1;
6147            Signature[] s2;
6148            Object obj = mSettings.getUserIdLPr(uid1);
6149            if (obj != null) {
6150                if (obj instanceof SharedUserSetting) {
6151                    if (isCallerInstantApp) {
6152                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6153                    }
6154                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6155                } else if (obj instanceof PackageSetting) {
6156                    final PackageSetting ps = (PackageSetting) obj;
6157                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6158                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6159                    }
6160                    s1 = ps.signatures.mSignatures;
6161                } else {
6162                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6163                }
6164            } else {
6165                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6166            }
6167            obj = mSettings.getUserIdLPr(uid2);
6168            if (obj != null) {
6169                if (obj instanceof SharedUserSetting) {
6170                    if (isCallerInstantApp) {
6171                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6172                    }
6173                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6174                } else if (obj instanceof PackageSetting) {
6175                    final PackageSetting ps = (PackageSetting) obj;
6176                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6177                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6178                    }
6179                    s2 = ps.signatures.mSignatures;
6180                } else {
6181                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6182                }
6183            } else {
6184                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6185            }
6186            return compareSignatures(s1, s2);
6187        }
6188    }
6189
6190    /**
6191     * This method should typically only be used when granting or revoking
6192     * permissions, since the app may immediately restart after this call.
6193     * <p>
6194     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6195     * guard your work against the app being relaunched.
6196     */
6197    private void killUid(int appId, int userId, String reason) {
6198        final long identity = Binder.clearCallingIdentity();
6199        try {
6200            IActivityManager am = ActivityManager.getService();
6201            if (am != null) {
6202                try {
6203                    am.killUid(appId, userId, reason);
6204                } catch (RemoteException e) {
6205                    /* ignore - same process */
6206                }
6207            }
6208        } finally {
6209            Binder.restoreCallingIdentity(identity);
6210        }
6211    }
6212
6213    /**
6214     * Compares two sets of signatures. Returns:
6215     * <br />
6216     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6217     * <br />
6218     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6219     * <br />
6220     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6221     * <br />
6222     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6223     * <br />
6224     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6225     */
6226    static int compareSignatures(Signature[] s1, Signature[] s2) {
6227        if (s1 == null) {
6228            return s2 == null
6229                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6230                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6231        }
6232
6233        if (s2 == null) {
6234            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6235        }
6236
6237        if (s1.length != s2.length) {
6238            return PackageManager.SIGNATURE_NO_MATCH;
6239        }
6240
6241        // Since both signature sets are of size 1, we can compare without HashSets.
6242        if (s1.length == 1) {
6243            return s1[0].equals(s2[0]) ?
6244                    PackageManager.SIGNATURE_MATCH :
6245                    PackageManager.SIGNATURE_NO_MATCH;
6246        }
6247
6248        ArraySet<Signature> set1 = new ArraySet<Signature>();
6249        for (Signature sig : s1) {
6250            set1.add(sig);
6251        }
6252        ArraySet<Signature> set2 = new ArraySet<Signature>();
6253        for (Signature sig : s2) {
6254            set2.add(sig);
6255        }
6256        // Make sure s2 contains all signatures in s1.
6257        if (set1.equals(set2)) {
6258            return PackageManager.SIGNATURE_MATCH;
6259        }
6260        return PackageManager.SIGNATURE_NO_MATCH;
6261    }
6262
6263    /**
6264     * If the database version for this type of package (internal storage or
6265     * external storage) is less than the version where package signatures
6266     * were updated, return true.
6267     */
6268    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6269        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6270        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6271    }
6272
6273    /**
6274     * Used for backward compatibility to make sure any packages with
6275     * certificate chains get upgraded to the new style. {@code existingSigs}
6276     * will be in the old format (since they were stored on disk from before the
6277     * system upgrade) and {@code scannedSigs} will be in the newer format.
6278     */
6279    private int compareSignaturesCompat(PackageSignatures existingSigs,
6280            PackageParser.Package scannedPkg) {
6281        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6282            return PackageManager.SIGNATURE_NO_MATCH;
6283        }
6284
6285        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6286        for (Signature sig : existingSigs.mSignatures) {
6287            existingSet.add(sig);
6288        }
6289        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6290        for (Signature sig : scannedPkg.mSignatures) {
6291            try {
6292                Signature[] chainSignatures = sig.getChainSignatures();
6293                for (Signature chainSig : chainSignatures) {
6294                    scannedCompatSet.add(chainSig);
6295                }
6296            } catch (CertificateEncodingException e) {
6297                scannedCompatSet.add(sig);
6298            }
6299        }
6300        /*
6301         * Make sure the expanded scanned set contains all signatures in the
6302         * existing one.
6303         */
6304        if (scannedCompatSet.equals(existingSet)) {
6305            // Migrate the old signatures to the new scheme.
6306            existingSigs.assignSignatures(scannedPkg.mSignatures);
6307            // The new KeySets will be re-added later in the scanning process.
6308            synchronized (mPackages) {
6309                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6310            }
6311            return PackageManager.SIGNATURE_MATCH;
6312        }
6313        return PackageManager.SIGNATURE_NO_MATCH;
6314    }
6315
6316    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6317        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6318        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6319    }
6320
6321    private int compareSignaturesRecover(PackageSignatures existingSigs,
6322            PackageParser.Package scannedPkg) {
6323        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6324            return PackageManager.SIGNATURE_NO_MATCH;
6325        }
6326
6327        String msg = null;
6328        try {
6329            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6330                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6331                        + scannedPkg.packageName);
6332                return PackageManager.SIGNATURE_MATCH;
6333            }
6334        } catch (CertificateException e) {
6335            msg = e.getMessage();
6336        }
6337
6338        logCriticalInfo(Log.INFO,
6339                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6340        return PackageManager.SIGNATURE_NO_MATCH;
6341    }
6342
6343    @Override
6344    public List<String> getAllPackages() {
6345        final int callingUid = Binder.getCallingUid();
6346        final int callingUserId = UserHandle.getUserId(callingUid);
6347        synchronized (mPackages) {
6348            if (canViewInstantApps(callingUid, callingUserId)) {
6349                return new ArrayList<String>(mPackages.keySet());
6350            }
6351            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6352            final List<String> result = new ArrayList<>();
6353            if (instantAppPkgName != null) {
6354                // caller is an instant application; filter unexposed applications
6355                for (PackageParser.Package pkg : mPackages.values()) {
6356                    if (!pkg.visibleToInstantApps) {
6357                        continue;
6358                    }
6359                    result.add(pkg.packageName);
6360                }
6361            } else {
6362                // caller is a normal application; filter instant applications
6363                for (PackageParser.Package pkg : mPackages.values()) {
6364                    final PackageSetting ps =
6365                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6366                    if (ps != null
6367                            && ps.getInstantApp(callingUserId)
6368                            && !mInstantAppRegistry.isInstantAccessGranted(
6369                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6370                        continue;
6371                    }
6372                    result.add(pkg.packageName);
6373                }
6374            }
6375            return result;
6376        }
6377    }
6378
6379    @Override
6380    public String[] getPackagesForUid(int uid) {
6381        final int callingUid = Binder.getCallingUid();
6382        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6383        final int userId = UserHandle.getUserId(uid);
6384        uid = UserHandle.getAppId(uid);
6385        // reader
6386        synchronized (mPackages) {
6387            Object obj = mSettings.getUserIdLPr(uid);
6388            if (obj instanceof SharedUserSetting) {
6389                if (isCallerInstantApp) {
6390                    return null;
6391                }
6392                final SharedUserSetting sus = (SharedUserSetting) obj;
6393                final int N = sus.packages.size();
6394                String[] res = new String[N];
6395                final Iterator<PackageSetting> it = sus.packages.iterator();
6396                int i = 0;
6397                while (it.hasNext()) {
6398                    PackageSetting ps = it.next();
6399                    if (ps.getInstalled(userId)) {
6400                        res[i++] = ps.name;
6401                    } else {
6402                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6403                    }
6404                }
6405                return res;
6406            } else if (obj instanceof PackageSetting) {
6407                final PackageSetting ps = (PackageSetting) obj;
6408                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6409                    return new String[]{ps.name};
6410                }
6411            }
6412        }
6413        return null;
6414    }
6415
6416    @Override
6417    public String getNameForUid(int uid) {
6418        final int callingUid = Binder.getCallingUid();
6419        if (getInstantAppPackageName(callingUid) != null) {
6420            return null;
6421        }
6422        synchronized (mPackages) {
6423            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6424            if (obj instanceof SharedUserSetting) {
6425                final SharedUserSetting sus = (SharedUserSetting) obj;
6426                return sus.name + ":" + sus.userId;
6427            } else if (obj instanceof PackageSetting) {
6428                final PackageSetting ps = (PackageSetting) obj;
6429                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6430                    return null;
6431                }
6432                return ps.name;
6433            }
6434            return null;
6435        }
6436    }
6437
6438    @Override
6439    public String[] getNamesForUids(int[] uids) {
6440        if (uids == null || uids.length == 0) {
6441            return null;
6442        }
6443        final int callingUid = Binder.getCallingUid();
6444        if (getInstantAppPackageName(callingUid) != null) {
6445            return null;
6446        }
6447        final String[] names = new String[uids.length];
6448        synchronized (mPackages) {
6449            for (int i = uids.length - 1; i >= 0; i--) {
6450                final int uid = uids[i];
6451                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6452                if (obj instanceof SharedUserSetting) {
6453                    final SharedUserSetting sus = (SharedUserSetting) obj;
6454                    names[i] = "shared:" + sus.name;
6455                } else if (obj instanceof PackageSetting) {
6456                    final PackageSetting ps = (PackageSetting) obj;
6457                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6458                        names[i] = null;
6459                    } else {
6460                        names[i] = ps.name;
6461                    }
6462                } else {
6463                    names[i] = null;
6464                }
6465            }
6466        }
6467        return names;
6468    }
6469
6470    @Override
6471    public int getUidForSharedUser(String sharedUserName) {
6472        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6473            return -1;
6474        }
6475        if (sharedUserName == null) {
6476            return -1;
6477        }
6478        // reader
6479        synchronized (mPackages) {
6480            SharedUserSetting suid;
6481            try {
6482                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6483                if (suid != null) {
6484                    return suid.userId;
6485                }
6486            } catch (PackageManagerException ignore) {
6487                // can't happen, but, still need to catch it
6488            }
6489            return -1;
6490        }
6491    }
6492
6493    @Override
6494    public int getFlagsForUid(int uid) {
6495        final int callingUid = Binder.getCallingUid();
6496        if (getInstantAppPackageName(callingUid) != null) {
6497            return 0;
6498        }
6499        synchronized (mPackages) {
6500            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6501            if (obj instanceof SharedUserSetting) {
6502                final SharedUserSetting sus = (SharedUserSetting) obj;
6503                return sus.pkgFlags;
6504            } else if (obj instanceof PackageSetting) {
6505                final PackageSetting ps = (PackageSetting) obj;
6506                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6507                    return 0;
6508                }
6509                return ps.pkgFlags;
6510            }
6511        }
6512        return 0;
6513    }
6514
6515    @Override
6516    public int getPrivateFlagsForUid(int uid) {
6517        final int callingUid = Binder.getCallingUid();
6518        if (getInstantAppPackageName(callingUid) != null) {
6519            return 0;
6520        }
6521        synchronized (mPackages) {
6522            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6523            if (obj instanceof SharedUserSetting) {
6524                final SharedUserSetting sus = (SharedUserSetting) obj;
6525                return sus.pkgPrivateFlags;
6526            } else if (obj instanceof PackageSetting) {
6527                final PackageSetting ps = (PackageSetting) obj;
6528                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6529                    return 0;
6530                }
6531                return ps.pkgPrivateFlags;
6532            }
6533        }
6534        return 0;
6535    }
6536
6537    @Override
6538    public boolean isUidPrivileged(int uid) {
6539        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6540            return false;
6541        }
6542        uid = UserHandle.getAppId(uid);
6543        // reader
6544        synchronized (mPackages) {
6545            Object obj = mSettings.getUserIdLPr(uid);
6546            if (obj instanceof SharedUserSetting) {
6547                final SharedUserSetting sus = (SharedUserSetting) obj;
6548                final Iterator<PackageSetting> it = sus.packages.iterator();
6549                while (it.hasNext()) {
6550                    if (it.next().isPrivileged()) {
6551                        return true;
6552                    }
6553                }
6554            } else if (obj instanceof PackageSetting) {
6555                final PackageSetting ps = (PackageSetting) obj;
6556                return ps.isPrivileged();
6557            }
6558        }
6559        return false;
6560    }
6561
6562    @Override
6563    public String[] getAppOpPermissionPackages(String permissionName) {
6564        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6565            return null;
6566        }
6567        synchronized (mPackages) {
6568            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6569            if (pkgs == null) {
6570                return null;
6571            }
6572            return pkgs.toArray(new String[pkgs.size()]);
6573        }
6574    }
6575
6576    @Override
6577    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6578            int flags, int userId) {
6579        return resolveIntentInternal(
6580                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6581    }
6582
6583    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6584            int flags, int userId, boolean resolveForStart) {
6585        try {
6586            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6587
6588            if (!sUserManager.exists(userId)) return null;
6589            final int callingUid = Binder.getCallingUid();
6590            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6591            enforceCrossUserPermission(callingUid, userId,
6592                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6593
6594            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6595            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6596                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6597            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6598
6599            final ResolveInfo bestChoice =
6600                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6601            return bestChoice;
6602        } finally {
6603            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6604        }
6605    }
6606
6607    @Override
6608    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6609        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6610            throw new SecurityException(
6611                    "findPersistentPreferredActivity can only be run by the system");
6612        }
6613        if (!sUserManager.exists(userId)) {
6614            return null;
6615        }
6616        final int callingUid = Binder.getCallingUid();
6617        intent = updateIntentForResolve(intent);
6618        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6619        final int flags = updateFlagsForResolve(
6620                0, userId, intent, callingUid, false /*includeInstantApps*/);
6621        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6622                userId);
6623        synchronized (mPackages) {
6624            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6625                    userId);
6626        }
6627    }
6628
6629    @Override
6630    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6631            IntentFilter filter, int match, ComponentName activity) {
6632        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6633            return;
6634        }
6635        final int userId = UserHandle.getCallingUserId();
6636        if (DEBUG_PREFERRED) {
6637            Log.v(TAG, "setLastChosenActivity intent=" + intent
6638                + " resolvedType=" + resolvedType
6639                + " flags=" + flags
6640                + " filter=" + filter
6641                + " match=" + match
6642                + " activity=" + activity);
6643            filter.dump(new PrintStreamPrinter(System.out), "    ");
6644        }
6645        intent.setComponent(null);
6646        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6647                userId);
6648        // Find any earlier preferred or last chosen entries and nuke them
6649        findPreferredActivity(intent, resolvedType,
6650                flags, query, 0, false, true, false, userId);
6651        // Add the new activity as the last chosen for this filter
6652        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6653                "Setting last chosen");
6654    }
6655
6656    @Override
6657    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6658        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6659            return null;
6660        }
6661        final int userId = UserHandle.getCallingUserId();
6662        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6663        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6664                userId);
6665        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6666                false, false, false, userId);
6667    }
6668
6669    /**
6670     * Returns whether or not instant apps have been disabled remotely.
6671     */
6672    private boolean isEphemeralDisabled() {
6673        return mEphemeralAppsDisabled;
6674    }
6675
6676    private boolean isInstantAppAllowed(
6677            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6678            boolean skipPackageCheck) {
6679        if (mInstantAppResolverConnection == null) {
6680            return false;
6681        }
6682        if (mInstantAppInstallerActivity == null) {
6683            return false;
6684        }
6685        if (intent.getComponent() != null) {
6686            return false;
6687        }
6688        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6689            return false;
6690        }
6691        if (!skipPackageCheck && intent.getPackage() != null) {
6692            return false;
6693        }
6694        final boolean isWebUri = hasWebURI(intent);
6695        if (!isWebUri || intent.getData().getHost() == null) {
6696            return false;
6697        }
6698        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6699        // Or if there's already an ephemeral app installed that handles the action
6700        synchronized (mPackages) {
6701            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6702            for (int n = 0; n < count; n++) {
6703                final ResolveInfo info = resolvedActivities.get(n);
6704                final String packageName = info.activityInfo.packageName;
6705                final PackageSetting ps = mSettings.mPackages.get(packageName);
6706                if (ps != null) {
6707                    // only check domain verification status if the app is not a browser
6708                    if (!info.handleAllWebDataURI) {
6709                        // Try to get the status from User settings first
6710                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6711                        final int status = (int) (packedStatus >> 32);
6712                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6713                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6714                            if (DEBUG_EPHEMERAL) {
6715                                Slog.v(TAG, "DENY instant app;"
6716                                    + " pkg: " + packageName + ", status: " + status);
6717                            }
6718                            return false;
6719                        }
6720                    }
6721                    if (ps.getInstantApp(userId)) {
6722                        if (DEBUG_EPHEMERAL) {
6723                            Slog.v(TAG, "DENY instant app installed;"
6724                                    + " pkg: " + packageName);
6725                        }
6726                        return false;
6727                    }
6728                }
6729            }
6730        }
6731        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6732        return true;
6733    }
6734
6735    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6736            Intent origIntent, String resolvedType, String callingPackage,
6737            Bundle verificationBundle, int userId) {
6738        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6739                new InstantAppRequest(responseObj, origIntent, resolvedType,
6740                        callingPackage, userId, verificationBundle));
6741        mHandler.sendMessage(msg);
6742    }
6743
6744    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6745            int flags, List<ResolveInfo> query, int userId) {
6746        if (query != null) {
6747            final int N = query.size();
6748            if (N == 1) {
6749                return query.get(0);
6750            } else if (N > 1) {
6751                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6752                // If there is more than one activity with the same priority,
6753                // then let the user decide between them.
6754                ResolveInfo r0 = query.get(0);
6755                ResolveInfo r1 = query.get(1);
6756                if (DEBUG_INTENT_MATCHING || debug) {
6757                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6758                            + r1.activityInfo.name + "=" + r1.priority);
6759                }
6760                // If the first activity has a higher priority, or a different
6761                // default, then it is always desirable to pick it.
6762                if (r0.priority != r1.priority
6763                        || r0.preferredOrder != r1.preferredOrder
6764                        || r0.isDefault != r1.isDefault) {
6765                    return query.get(0);
6766                }
6767                // If we have saved a preference for a preferred activity for
6768                // this Intent, use that.
6769                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6770                        flags, query, r0.priority, true, false, debug, userId);
6771                if (ri != null) {
6772                    return ri;
6773                }
6774                // If we have an ephemeral app, use it
6775                for (int i = 0; i < N; i++) {
6776                    ri = query.get(i);
6777                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6778                        final String packageName = ri.activityInfo.packageName;
6779                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6780                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6781                        final int status = (int)(packedStatus >> 32);
6782                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6783                            return ri;
6784                        }
6785                    }
6786                }
6787                ri = new ResolveInfo(mResolveInfo);
6788                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6789                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6790                // If all of the options come from the same package, show the application's
6791                // label and icon instead of the generic resolver's.
6792                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6793                // and then throw away the ResolveInfo itself, meaning that the caller loses
6794                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6795                // a fallback for this case; we only set the target package's resources on
6796                // the ResolveInfo, not the ActivityInfo.
6797                final String intentPackage = intent.getPackage();
6798                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6799                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6800                    ri.resolvePackageName = intentPackage;
6801                    if (userNeedsBadging(userId)) {
6802                        ri.noResourceId = true;
6803                    } else {
6804                        ri.icon = appi.icon;
6805                    }
6806                    ri.iconResourceId = appi.icon;
6807                    ri.labelRes = appi.labelRes;
6808                }
6809                ri.activityInfo.applicationInfo = new ApplicationInfo(
6810                        ri.activityInfo.applicationInfo);
6811                if (userId != 0) {
6812                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6813                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6814                }
6815                // Make sure that the resolver is displayable in car mode
6816                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6817                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6818                return ri;
6819            }
6820        }
6821        return null;
6822    }
6823
6824    /**
6825     * Return true if the given list is not empty and all of its contents have
6826     * an activityInfo with the given package name.
6827     */
6828    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6829        if (ArrayUtils.isEmpty(list)) {
6830            return false;
6831        }
6832        for (int i = 0, N = list.size(); i < N; i++) {
6833            final ResolveInfo ri = list.get(i);
6834            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6835            if (ai == null || !packageName.equals(ai.packageName)) {
6836                return false;
6837            }
6838        }
6839        return true;
6840    }
6841
6842    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6843            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6844        final int N = query.size();
6845        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6846                .get(userId);
6847        // Get the list of persistent preferred activities that handle the intent
6848        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6849        List<PersistentPreferredActivity> pprefs = ppir != null
6850                ? ppir.queryIntent(intent, resolvedType,
6851                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6852                        userId)
6853                : null;
6854        if (pprefs != null && pprefs.size() > 0) {
6855            final int M = pprefs.size();
6856            for (int i=0; i<M; i++) {
6857                final PersistentPreferredActivity ppa = pprefs.get(i);
6858                if (DEBUG_PREFERRED || debug) {
6859                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6860                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6861                            + "\n  component=" + ppa.mComponent);
6862                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6863                }
6864                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6865                        flags | MATCH_DISABLED_COMPONENTS, userId);
6866                if (DEBUG_PREFERRED || debug) {
6867                    Slog.v(TAG, "Found persistent preferred activity:");
6868                    if (ai != null) {
6869                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6870                    } else {
6871                        Slog.v(TAG, "  null");
6872                    }
6873                }
6874                if (ai == null) {
6875                    // This previously registered persistent preferred activity
6876                    // component is no longer known. Ignore it and do NOT remove it.
6877                    continue;
6878                }
6879                for (int j=0; j<N; j++) {
6880                    final ResolveInfo ri = query.get(j);
6881                    if (!ri.activityInfo.applicationInfo.packageName
6882                            .equals(ai.applicationInfo.packageName)) {
6883                        continue;
6884                    }
6885                    if (!ri.activityInfo.name.equals(ai.name)) {
6886                        continue;
6887                    }
6888                    //  Found a persistent preference that can handle the intent.
6889                    if (DEBUG_PREFERRED || debug) {
6890                        Slog.v(TAG, "Returning persistent preferred activity: " +
6891                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6892                    }
6893                    return ri;
6894                }
6895            }
6896        }
6897        return null;
6898    }
6899
6900    // TODO: handle preferred activities missing while user has amnesia
6901    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6902            List<ResolveInfo> query, int priority, boolean always,
6903            boolean removeMatches, boolean debug, int userId) {
6904        if (!sUserManager.exists(userId)) return null;
6905        final int callingUid = Binder.getCallingUid();
6906        flags = updateFlagsForResolve(
6907                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6908        intent = updateIntentForResolve(intent);
6909        // writer
6910        synchronized (mPackages) {
6911            // Try to find a matching persistent preferred activity.
6912            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6913                    debug, userId);
6914
6915            // If a persistent preferred activity matched, use it.
6916            if (pri != null) {
6917                return pri;
6918            }
6919
6920            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6921            // Get the list of preferred activities that handle the intent
6922            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6923            List<PreferredActivity> prefs = pir != null
6924                    ? pir.queryIntent(intent, resolvedType,
6925                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6926                            userId)
6927                    : null;
6928            if (prefs != null && prefs.size() > 0) {
6929                boolean changed = false;
6930                try {
6931                    // First figure out how good the original match set is.
6932                    // We will only allow preferred activities that came
6933                    // from the same match quality.
6934                    int match = 0;
6935
6936                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6937
6938                    final int N = query.size();
6939                    for (int j=0; j<N; j++) {
6940                        final ResolveInfo ri = query.get(j);
6941                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6942                                + ": 0x" + Integer.toHexString(match));
6943                        if (ri.match > match) {
6944                            match = ri.match;
6945                        }
6946                    }
6947
6948                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6949                            + Integer.toHexString(match));
6950
6951                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6952                    final int M = prefs.size();
6953                    for (int i=0; i<M; i++) {
6954                        final PreferredActivity pa = prefs.get(i);
6955                        if (DEBUG_PREFERRED || debug) {
6956                            Slog.v(TAG, "Checking PreferredActivity ds="
6957                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6958                                    + "\n  component=" + pa.mPref.mComponent);
6959                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6960                        }
6961                        if (pa.mPref.mMatch != match) {
6962                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6963                                    + Integer.toHexString(pa.mPref.mMatch));
6964                            continue;
6965                        }
6966                        // If it's not an "always" type preferred activity and that's what we're
6967                        // looking for, skip it.
6968                        if (always && !pa.mPref.mAlways) {
6969                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6970                            continue;
6971                        }
6972                        final ActivityInfo ai = getActivityInfo(
6973                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6974                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6975                                userId);
6976                        if (DEBUG_PREFERRED || debug) {
6977                            Slog.v(TAG, "Found preferred activity:");
6978                            if (ai != null) {
6979                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6980                            } else {
6981                                Slog.v(TAG, "  null");
6982                            }
6983                        }
6984                        if (ai == null) {
6985                            // This previously registered preferred activity
6986                            // component is no longer known.  Most likely an update
6987                            // to the app was installed and in the new version this
6988                            // component no longer exists.  Clean it up by removing
6989                            // it from the preferred activities list, and skip it.
6990                            Slog.w(TAG, "Removing dangling preferred activity: "
6991                                    + pa.mPref.mComponent);
6992                            pir.removeFilter(pa);
6993                            changed = true;
6994                            continue;
6995                        }
6996                        for (int j=0; j<N; j++) {
6997                            final ResolveInfo ri = query.get(j);
6998                            if (!ri.activityInfo.applicationInfo.packageName
6999                                    .equals(ai.applicationInfo.packageName)) {
7000                                continue;
7001                            }
7002                            if (!ri.activityInfo.name.equals(ai.name)) {
7003                                continue;
7004                            }
7005
7006                            if (removeMatches) {
7007                                pir.removeFilter(pa);
7008                                changed = true;
7009                                if (DEBUG_PREFERRED) {
7010                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7011                                }
7012                                break;
7013                            }
7014
7015                            // Okay we found a previously set preferred or last chosen app.
7016                            // If the result set is different from when this
7017                            // was created, and is not a subset of the preferred set, we need to
7018                            // clear it and re-ask the user their preference, if we're looking for
7019                            // an "always" type entry.
7020                            if (always && !pa.mPref.sameSet(query)) {
7021                                if (pa.mPref.isSuperset(query)) {
7022                                    // some components of the set are no longer present in
7023                                    // the query, but the preferred activity can still be reused
7024                                    if (DEBUG_PREFERRED) {
7025                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
7026                                                + " still valid as only non-preferred components"
7027                                                + " were removed for " + intent + " type "
7028                                                + resolvedType);
7029                                    }
7030                                    // remove obsolete components and re-add the up-to-date filter
7031                                    PreferredActivity freshPa = new PreferredActivity(pa,
7032                                            pa.mPref.mMatch,
7033                                            pa.mPref.discardObsoleteComponents(query),
7034                                            pa.mPref.mComponent,
7035                                            pa.mPref.mAlways);
7036                                    pir.removeFilter(pa);
7037                                    pir.addFilter(freshPa);
7038                                    changed = true;
7039                                } else {
7040                                    Slog.i(TAG,
7041                                            "Result set changed, dropping preferred activity for "
7042                                                    + intent + " type " + resolvedType);
7043                                    if (DEBUG_PREFERRED) {
7044                                        Slog.v(TAG, "Removing preferred activity since set changed "
7045                                                + pa.mPref.mComponent);
7046                                    }
7047                                    pir.removeFilter(pa);
7048                                    // Re-add the filter as a "last chosen" entry (!always)
7049                                    PreferredActivity lastChosen = new PreferredActivity(
7050                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7051                                    pir.addFilter(lastChosen);
7052                                    changed = true;
7053                                    return null;
7054                                }
7055                            }
7056
7057                            // Yay! Either the set matched or we're looking for the last chosen
7058                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7059                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7060                            return ri;
7061                        }
7062                    }
7063                } finally {
7064                    if (changed) {
7065                        if (DEBUG_PREFERRED) {
7066                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7067                        }
7068                        scheduleWritePackageRestrictionsLocked(userId);
7069                    }
7070                }
7071            }
7072        }
7073        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7074        return null;
7075    }
7076
7077    /*
7078     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7079     */
7080    @Override
7081    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7082            int targetUserId) {
7083        mContext.enforceCallingOrSelfPermission(
7084                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7085        List<CrossProfileIntentFilter> matches =
7086                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7087        if (matches != null) {
7088            int size = matches.size();
7089            for (int i = 0; i < size; i++) {
7090                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7091            }
7092        }
7093        if (hasWebURI(intent)) {
7094            // cross-profile app linking works only towards the parent.
7095            final int callingUid = Binder.getCallingUid();
7096            final UserInfo parent = getProfileParent(sourceUserId);
7097            synchronized(mPackages) {
7098                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7099                        false /*includeInstantApps*/);
7100                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7101                        intent, resolvedType, flags, sourceUserId, parent.id);
7102                return xpDomainInfo != null;
7103            }
7104        }
7105        return false;
7106    }
7107
7108    private UserInfo getProfileParent(int userId) {
7109        final long identity = Binder.clearCallingIdentity();
7110        try {
7111            return sUserManager.getProfileParent(userId);
7112        } finally {
7113            Binder.restoreCallingIdentity(identity);
7114        }
7115    }
7116
7117    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7118            String resolvedType, int userId) {
7119        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7120        if (resolver != null) {
7121            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7122        }
7123        return null;
7124    }
7125
7126    @Override
7127    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7128            String resolvedType, int flags, int userId) {
7129        try {
7130            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7131
7132            return new ParceledListSlice<>(
7133                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7134        } finally {
7135            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7136        }
7137    }
7138
7139    /**
7140     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7141     * instant, returns {@code null}.
7142     */
7143    private String getInstantAppPackageName(int callingUid) {
7144        synchronized (mPackages) {
7145            // If the caller is an isolated app use the owner's uid for the lookup.
7146            if (Process.isIsolated(callingUid)) {
7147                callingUid = mIsolatedOwners.get(callingUid);
7148            }
7149            final int appId = UserHandle.getAppId(callingUid);
7150            final Object obj = mSettings.getUserIdLPr(appId);
7151            if (obj instanceof PackageSetting) {
7152                final PackageSetting ps = (PackageSetting) obj;
7153                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7154                return isInstantApp ? ps.pkg.packageName : null;
7155            }
7156        }
7157        return null;
7158    }
7159
7160    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7161            String resolvedType, int flags, int userId) {
7162        return queryIntentActivitiesInternal(
7163                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7164                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7165    }
7166
7167    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7168            String resolvedType, int flags, int filterCallingUid, int userId,
7169            boolean resolveForStart, boolean allowDynamicSplits) {
7170        if (!sUserManager.exists(userId)) return Collections.emptyList();
7171        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7172        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7173                false /* requireFullPermission */, false /* checkShell */,
7174                "query intent activities");
7175        final String pkgName = intent.getPackage();
7176        ComponentName comp = intent.getComponent();
7177        if (comp == null) {
7178            if (intent.getSelector() != null) {
7179                intent = intent.getSelector();
7180                comp = intent.getComponent();
7181            }
7182        }
7183
7184        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7185                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7186        if (comp != null) {
7187            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7188            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7189            if (ai != null) {
7190                // When specifying an explicit component, we prevent the activity from being
7191                // used when either 1) the calling package is normal and the activity is within
7192                // an ephemeral application or 2) the calling package is ephemeral and the
7193                // activity is not visible to ephemeral applications.
7194                final boolean matchInstantApp =
7195                        (flags & PackageManager.MATCH_INSTANT) != 0;
7196                final boolean matchVisibleToInstantAppOnly =
7197                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7198                final boolean matchExplicitlyVisibleOnly =
7199                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7200                final boolean isCallerInstantApp =
7201                        instantAppPkgName != null;
7202                final boolean isTargetSameInstantApp =
7203                        comp.getPackageName().equals(instantAppPkgName);
7204                final boolean isTargetInstantApp =
7205                        (ai.applicationInfo.privateFlags
7206                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7207                final boolean isTargetVisibleToInstantApp =
7208                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7209                final boolean isTargetExplicitlyVisibleToInstantApp =
7210                        isTargetVisibleToInstantApp
7211                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7212                final boolean isTargetHiddenFromInstantApp =
7213                        !isTargetVisibleToInstantApp
7214                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7215                final boolean blockResolution =
7216                        !isTargetSameInstantApp
7217                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7218                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7219                                        && isTargetHiddenFromInstantApp));
7220                if (!blockResolution) {
7221                    final ResolveInfo ri = new ResolveInfo();
7222                    ri.activityInfo = ai;
7223                    list.add(ri);
7224                }
7225            }
7226            return applyPostResolutionFilter(
7227                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7228        }
7229
7230        // reader
7231        boolean sortResult = false;
7232        boolean addEphemeral = false;
7233        List<ResolveInfo> result;
7234        final boolean ephemeralDisabled = isEphemeralDisabled();
7235        synchronized (mPackages) {
7236            if (pkgName == null) {
7237                List<CrossProfileIntentFilter> matchingFilters =
7238                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7239                // Check for results that need to skip the current profile.
7240                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7241                        resolvedType, flags, userId);
7242                if (xpResolveInfo != null) {
7243                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7244                    xpResult.add(xpResolveInfo);
7245                    return applyPostResolutionFilter(
7246                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7247                            allowDynamicSplits, filterCallingUid, userId);
7248                }
7249
7250                // Check for results in the current profile.
7251                result = filterIfNotSystemUser(mActivities.queryIntent(
7252                        intent, resolvedType, flags, userId), userId);
7253                addEphemeral = !ephemeralDisabled
7254                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7255                // Check for cross profile results.
7256                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7257                xpResolveInfo = queryCrossProfileIntents(
7258                        matchingFilters, intent, resolvedType, flags, userId,
7259                        hasNonNegativePriorityResult);
7260                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7261                    boolean isVisibleToUser = filterIfNotSystemUser(
7262                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7263                    if (isVisibleToUser) {
7264                        result.add(xpResolveInfo);
7265                        sortResult = true;
7266                    }
7267                }
7268                if (hasWebURI(intent)) {
7269                    CrossProfileDomainInfo xpDomainInfo = null;
7270                    final UserInfo parent = getProfileParent(userId);
7271                    if (parent != null) {
7272                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7273                                flags, userId, parent.id);
7274                    }
7275                    if (xpDomainInfo != null) {
7276                        if (xpResolveInfo != null) {
7277                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7278                            // in the result.
7279                            result.remove(xpResolveInfo);
7280                        }
7281                        if (result.size() == 0 && !addEphemeral) {
7282                            // No result in current profile, but found candidate in parent user.
7283                            // And we are not going to add emphemeral app, so we can return the
7284                            // result straight away.
7285                            result.add(xpDomainInfo.resolveInfo);
7286                            return applyPostResolutionFilter(result, instantAppPkgName,
7287                                    allowDynamicSplits, filterCallingUid, userId);
7288                        }
7289                    } else if (result.size() <= 1 && !addEphemeral) {
7290                        // No result in parent user and <= 1 result in current profile, and we
7291                        // are not going to add emphemeral app, so we can return the result without
7292                        // further processing.
7293                        return applyPostResolutionFilter(result, instantAppPkgName,
7294                                allowDynamicSplits, filterCallingUid, userId);
7295                    }
7296                    // We have more than one candidate (combining results from current and parent
7297                    // profile), so we need filtering and sorting.
7298                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7299                            intent, flags, result, xpDomainInfo, userId);
7300                    sortResult = true;
7301                }
7302            } else {
7303                final PackageParser.Package pkg = mPackages.get(pkgName);
7304                result = null;
7305                if (pkg != null) {
7306                    result = filterIfNotSystemUser(
7307                            mActivities.queryIntentForPackage(
7308                                    intent, resolvedType, flags, pkg.activities, userId),
7309                            userId);
7310                }
7311                if (result == null || result.size() == 0) {
7312                    // the caller wants to resolve for a particular package; however, there
7313                    // were no installed results, so, try to find an ephemeral result
7314                    addEphemeral = !ephemeralDisabled
7315                            && isInstantAppAllowed(
7316                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7317                    if (result == null) {
7318                        result = new ArrayList<>();
7319                    }
7320                }
7321            }
7322        }
7323        if (addEphemeral) {
7324            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7325        }
7326        if (sortResult) {
7327            Collections.sort(result, mResolvePrioritySorter);
7328        }
7329        return applyPostResolutionFilter(
7330                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7331    }
7332
7333    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7334            String resolvedType, int flags, int userId) {
7335        // first, check to see if we've got an instant app already installed
7336        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7337        ResolveInfo localInstantApp = null;
7338        boolean blockResolution = false;
7339        if (!alreadyResolvedLocally) {
7340            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7341                    flags
7342                        | PackageManager.GET_RESOLVED_FILTER
7343                        | PackageManager.MATCH_INSTANT
7344                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7345                    userId);
7346            for (int i = instantApps.size() - 1; i >= 0; --i) {
7347                final ResolveInfo info = instantApps.get(i);
7348                final String packageName = info.activityInfo.packageName;
7349                final PackageSetting ps = mSettings.mPackages.get(packageName);
7350                if (ps.getInstantApp(userId)) {
7351                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7352                    final int status = (int)(packedStatus >> 32);
7353                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7354                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7355                        // there's a local instant application installed, but, the user has
7356                        // chosen to never use it; skip resolution and don't acknowledge
7357                        // an instant application is even available
7358                        if (DEBUG_EPHEMERAL) {
7359                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7360                        }
7361                        blockResolution = true;
7362                        break;
7363                    } else {
7364                        // we have a locally installed instant application; skip resolution
7365                        // but acknowledge there's an instant application available
7366                        if (DEBUG_EPHEMERAL) {
7367                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7368                        }
7369                        localInstantApp = info;
7370                        break;
7371                    }
7372                }
7373            }
7374        }
7375        // no app installed, let's see if one's available
7376        AuxiliaryResolveInfo auxiliaryResponse = null;
7377        if (!blockResolution) {
7378            if (localInstantApp == null) {
7379                // we don't have an instant app locally, resolve externally
7380                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7381                final InstantAppRequest requestObject = new InstantAppRequest(
7382                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7383                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7384                auxiliaryResponse =
7385                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7386                                mContext, mInstantAppResolverConnection, requestObject);
7387                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7388            } else {
7389                // we have an instant application locally, but, we can't admit that since
7390                // callers shouldn't be able to determine prior browsing. create a dummy
7391                // auxiliary response so the downstream code behaves as if there's an
7392                // instant application available externally. when it comes time to start
7393                // the instant application, we'll do the right thing.
7394                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7395                auxiliaryResponse = new AuxiliaryResolveInfo(
7396                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7397                        ai.versionCode, null /*failureIntent*/);
7398            }
7399        }
7400        if (auxiliaryResponse != null) {
7401            if (DEBUG_EPHEMERAL) {
7402                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7403            }
7404            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7405            final PackageSetting ps =
7406                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7407            if (ps != null) {
7408                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7409                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7410                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7411                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7412                // make sure this resolver is the default
7413                ephemeralInstaller.isDefault = true;
7414                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7415                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7416                // add a non-generic filter
7417                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7418                ephemeralInstaller.filter.addDataPath(
7419                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7420                ephemeralInstaller.isInstantAppAvailable = true;
7421                result.add(ephemeralInstaller);
7422            }
7423        }
7424        return result;
7425    }
7426
7427    private static class CrossProfileDomainInfo {
7428        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7429        ResolveInfo resolveInfo;
7430        /* Best domain verification status of the activities found in the other profile */
7431        int bestDomainVerificationStatus;
7432    }
7433
7434    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7435            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7436        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7437                sourceUserId)) {
7438            return null;
7439        }
7440        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7441                resolvedType, flags, parentUserId);
7442
7443        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7444            return null;
7445        }
7446        CrossProfileDomainInfo result = null;
7447        int size = resultTargetUser.size();
7448        for (int i = 0; i < size; i++) {
7449            ResolveInfo riTargetUser = resultTargetUser.get(i);
7450            // Intent filter verification is only for filters that specify a host. So don't return
7451            // those that handle all web uris.
7452            if (riTargetUser.handleAllWebDataURI) {
7453                continue;
7454            }
7455            String packageName = riTargetUser.activityInfo.packageName;
7456            PackageSetting ps = mSettings.mPackages.get(packageName);
7457            if (ps == null) {
7458                continue;
7459            }
7460            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7461            int status = (int)(verificationState >> 32);
7462            if (result == null) {
7463                result = new CrossProfileDomainInfo();
7464                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7465                        sourceUserId, parentUserId);
7466                result.bestDomainVerificationStatus = status;
7467            } else {
7468                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7469                        result.bestDomainVerificationStatus);
7470            }
7471        }
7472        // Don't consider matches with status NEVER across profiles.
7473        if (result != null && result.bestDomainVerificationStatus
7474                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7475            return null;
7476        }
7477        return result;
7478    }
7479
7480    /**
7481     * Verification statuses are ordered from the worse to the best, except for
7482     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7483     */
7484    private int bestDomainVerificationStatus(int status1, int status2) {
7485        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7486            return status2;
7487        }
7488        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7489            return status1;
7490        }
7491        return (int) MathUtils.max(status1, status2);
7492    }
7493
7494    private boolean isUserEnabled(int userId) {
7495        long callingId = Binder.clearCallingIdentity();
7496        try {
7497            UserInfo userInfo = sUserManager.getUserInfo(userId);
7498            return userInfo != null && userInfo.isEnabled();
7499        } finally {
7500            Binder.restoreCallingIdentity(callingId);
7501        }
7502    }
7503
7504    /**
7505     * Filter out activities with systemUserOnly flag set, when current user is not System.
7506     *
7507     * @return filtered list
7508     */
7509    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7510        if (userId == UserHandle.USER_SYSTEM) {
7511            return resolveInfos;
7512        }
7513        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7514            ResolveInfo info = resolveInfos.get(i);
7515            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7516                resolveInfos.remove(i);
7517            }
7518        }
7519        return resolveInfos;
7520    }
7521
7522    /**
7523     * Filters out ephemeral activities.
7524     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7525     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7526     *
7527     * @param resolveInfos The pre-filtered list of resolved activities
7528     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7529     *          is performed.
7530     * @return A filtered list of resolved activities.
7531     */
7532    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7533            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7534        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7535            final ResolveInfo info = resolveInfos.get(i);
7536            // allow activities that are defined in the provided package
7537            if (allowDynamicSplits
7538                    && info.activityInfo.splitName != null
7539                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7540                            info.activityInfo.splitName)) {
7541                // requested activity is defined in a split that hasn't been installed yet.
7542                // add the installer to the resolve list
7543                if (DEBUG_INSTALL) {
7544                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7545                }
7546                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7547                final ComponentName installFailureActivity = findInstallFailureActivity(
7548                        info.activityInfo.packageName,  filterCallingUid, userId);
7549                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7550                        info.activityInfo.packageName, info.activityInfo.splitName,
7551                        installFailureActivity,
7552                        info.activityInfo.applicationInfo.versionCode,
7553                        null /*failureIntent*/);
7554                // make sure this resolver is the default
7555                installerInfo.isDefault = true;
7556                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7557                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7558                // add a non-generic filter
7559                installerInfo.filter = new IntentFilter();
7560                // load resources from the correct package
7561                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7562                resolveInfos.set(i, installerInfo);
7563                continue;
7564            }
7565            // caller is a full app, don't need to apply any other filtering
7566            if (ephemeralPkgName == null) {
7567                continue;
7568            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7569                // caller is same app; don't need to apply any other filtering
7570                continue;
7571            }
7572            // allow activities that have been explicitly exposed to ephemeral apps
7573            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7574            if (!isEphemeralApp
7575                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7576                continue;
7577            }
7578            resolveInfos.remove(i);
7579        }
7580        return resolveInfos;
7581    }
7582
7583    /**
7584     * Returns the activity component that can handle install failures.
7585     * <p>By default, the instant application installer handles failures. However, an
7586     * application may want to handle failures on its own. Applications do this by
7587     * creating an activity with an intent filter that handles the action
7588     * {@link Intent#ACTION_INSTALL_FAILURE}.
7589     */
7590    private @Nullable ComponentName findInstallFailureActivity(
7591            String packageName, int filterCallingUid, int userId) {
7592        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7593        failureActivityIntent.setPackage(packageName);
7594        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7595        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7596                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7597                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7598        final int NR = result.size();
7599        if (NR > 0) {
7600            for (int i = 0; i < NR; i++) {
7601                final ResolveInfo info = result.get(i);
7602                if (info.activityInfo.splitName != null) {
7603                    continue;
7604                }
7605                return new ComponentName(packageName, info.activityInfo.name);
7606            }
7607        }
7608        return null;
7609    }
7610
7611    /**
7612     * @param resolveInfos list of resolve infos in descending priority order
7613     * @return if the list contains a resolve info with non-negative priority
7614     */
7615    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7616        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7617    }
7618
7619    private static boolean hasWebURI(Intent intent) {
7620        if (intent.getData() == null) {
7621            return false;
7622        }
7623        final String scheme = intent.getScheme();
7624        if (TextUtils.isEmpty(scheme)) {
7625            return false;
7626        }
7627        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7628    }
7629
7630    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7631            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7632            int userId) {
7633        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7634
7635        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7636            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7637                    candidates.size());
7638        }
7639
7640        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7641        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7642        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7643        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7644        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7645        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7646
7647        synchronized (mPackages) {
7648            final int count = candidates.size();
7649            // First, try to use linked apps. Partition the candidates into four lists:
7650            // one for the final results, one for the "do not use ever", one for "undefined status"
7651            // and finally one for "browser app type".
7652            for (int n=0; n<count; n++) {
7653                ResolveInfo info = candidates.get(n);
7654                String packageName = info.activityInfo.packageName;
7655                PackageSetting ps = mSettings.mPackages.get(packageName);
7656                if (ps != null) {
7657                    // Add to the special match all list (Browser use case)
7658                    if (info.handleAllWebDataURI) {
7659                        matchAllList.add(info);
7660                        continue;
7661                    }
7662                    // Try to get the status from User settings first
7663                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7664                    int status = (int)(packedStatus >> 32);
7665                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7666                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7667                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7668                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7669                                    + " : linkgen=" + linkGeneration);
7670                        }
7671                        // Use link-enabled generation as preferredOrder, i.e.
7672                        // prefer newly-enabled over earlier-enabled.
7673                        info.preferredOrder = linkGeneration;
7674                        alwaysList.add(info);
7675                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7676                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7677                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7678                        }
7679                        neverList.add(info);
7680                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7681                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7682                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7683                        }
7684                        alwaysAskList.add(info);
7685                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7686                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7687                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7688                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7689                        }
7690                        undefinedList.add(info);
7691                    }
7692                }
7693            }
7694
7695            // We'll want to include browser possibilities in a few cases
7696            boolean includeBrowser = false;
7697
7698            // First try to add the "always" resolution(s) for the current user, if any
7699            if (alwaysList.size() > 0) {
7700                result.addAll(alwaysList);
7701            } else {
7702                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7703                result.addAll(undefinedList);
7704                // Maybe add one for the other profile.
7705                if (xpDomainInfo != null && (
7706                        xpDomainInfo.bestDomainVerificationStatus
7707                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7708                    result.add(xpDomainInfo.resolveInfo);
7709                }
7710                includeBrowser = true;
7711            }
7712
7713            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7714            // If there were 'always' entries their preferred order has been set, so we also
7715            // back that off to make the alternatives equivalent
7716            if (alwaysAskList.size() > 0) {
7717                for (ResolveInfo i : result) {
7718                    i.preferredOrder = 0;
7719                }
7720                result.addAll(alwaysAskList);
7721                includeBrowser = true;
7722            }
7723
7724            if (includeBrowser) {
7725                // Also add browsers (all of them or only the default one)
7726                if (DEBUG_DOMAIN_VERIFICATION) {
7727                    Slog.v(TAG, "   ...including browsers in candidate set");
7728                }
7729                if ((matchFlags & MATCH_ALL) != 0) {
7730                    result.addAll(matchAllList);
7731                } else {
7732                    // Browser/generic handling case.  If there's a default browser, go straight
7733                    // to that (but only if there is no other higher-priority match).
7734                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7735                    int maxMatchPrio = 0;
7736                    ResolveInfo defaultBrowserMatch = null;
7737                    final int numCandidates = matchAllList.size();
7738                    for (int n = 0; n < numCandidates; n++) {
7739                        ResolveInfo info = matchAllList.get(n);
7740                        // track the highest overall match priority...
7741                        if (info.priority > maxMatchPrio) {
7742                            maxMatchPrio = info.priority;
7743                        }
7744                        // ...and the highest-priority default browser match
7745                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7746                            if (defaultBrowserMatch == null
7747                                    || (defaultBrowserMatch.priority < info.priority)) {
7748                                if (debug) {
7749                                    Slog.v(TAG, "Considering default browser match " + info);
7750                                }
7751                                defaultBrowserMatch = info;
7752                            }
7753                        }
7754                    }
7755                    if (defaultBrowserMatch != null
7756                            && defaultBrowserMatch.priority >= maxMatchPrio
7757                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7758                    {
7759                        if (debug) {
7760                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7761                        }
7762                        result.add(defaultBrowserMatch);
7763                    } else {
7764                        result.addAll(matchAllList);
7765                    }
7766                }
7767
7768                // If there is nothing selected, add all candidates and remove the ones that the user
7769                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7770                if (result.size() == 0) {
7771                    result.addAll(candidates);
7772                    result.removeAll(neverList);
7773                }
7774            }
7775        }
7776        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7777            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7778                    result.size());
7779            for (ResolveInfo info : result) {
7780                Slog.v(TAG, "  + " + info.activityInfo);
7781            }
7782        }
7783        return result;
7784    }
7785
7786    // Returns a packed value as a long:
7787    //
7788    // high 'int'-sized word: link status: undefined/ask/never/always.
7789    // low 'int'-sized word: relative priority among 'always' results.
7790    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7791        long result = ps.getDomainVerificationStatusForUser(userId);
7792        // if none available, get the master status
7793        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7794            if (ps.getIntentFilterVerificationInfo() != null) {
7795                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7796            }
7797        }
7798        return result;
7799    }
7800
7801    private ResolveInfo querySkipCurrentProfileIntents(
7802            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7803            int flags, int sourceUserId) {
7804        if (matchingFilters != null) {
7805            int size = matchingFilters.size();
7806            for (int i = 0; i < size; i ++) {
7807                CrossProfileIntentFilter filter = matchingFilters.get(i);
7808                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7809                    // Checking if there are activities in the target user that can handle the
7810                    // intent.
7811                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7812                            resolvedType, flags, sourceUserId);
7813                    if (resolveInfo != null) {
7814                        return resolveInfo;
7815                    }
7816                }
7817            }
7818        }
7819        return null;
7820    }
7821
7822    // Return matching ResolveInfo in target user if any.
7823    private ResolveInfo queryCrossProfileIntents(
7824            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7825            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7826        if (matchingFilters != null) {
7827            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7828            // match the same intent. For performance reasons, it is better not to
7829            // run queryIntent twice for the same userId
7830            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7831            int size = matchingFilters.size();
7832            for (int i = 0; i < size; i++) {
7833                CrossProfileIntentFilter filter = matchingFilters.get(i);
7834                int targetUserId = filter.getTargetUserId();
7835                boolean skipCurrentProfile =
7836                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7837                boolean skipCurrentProfileIfNoMatchFound =
7838                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7839                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7840                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7841                    // Checking if there are activities in the target user that can handle the
7842                    // intent.
7843                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7844                            resolvedType, flags, sourceUserId);
7845                    if (resolveInfo != null) return resolveInfo;
7846                    alreadyTriedUserIds.put(targetUserId, true);
7847                }
7848            }
7849        }
7850        return null;
7851    }
7852
7853    /**
7854     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7855     * will forward the intent to the filter's target user.
7856     * Otherwise, returns null.
7857     */
7858    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7859            String resolvedType, int flags, int sourceUserId) {
7860        int targetUserId = filter.getTargetUserId();
7861        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7862                resolvedType, flags, targetUserId);
7863        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7864            // If all the matches in the target profile are suspended, return null.
7865            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7866                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7867                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7868                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7869                            targetUserId);
7870                }
7871            }
7872        }
7873        return null;
7874    }
7875
7876    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7877            int sourceUserId, int targetUserId) {
7878        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7879        long ident = Binder.clearCallingIdentity();
7880        boolean targetIsProfile;
7881        try {
7882            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7883        } finally {
7884            Binder.restoreCallingIdentity(ident);
7885        }
7886        String className;
7887        if (targetIsProfile) {
7888            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7889        } else {
7890            className = FORWARD_INTENT_TO_PARENT;
7891        }
7892        ComponentName forwardingActivityComponentName = new ComponentName(
7893                mAndroidApplication.packageName, className);
7894        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7895                sourceUserId);
7896        if (!targetIsProfile) {
7897            forwardingActivityInfo.showUserIcon = targetUserId;
7898            forwardingResolveInfo.noResourceId = true;
7899        }
7900        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7901        forwardingResolveInfo.priority = 0;
7902        forwardingResolveInfo.preferredOrder = 0;
7903        forwardingResolveInfo.match = 0;
7904        forwardingResolveInfo.isDefault = true;
7905        forwardingResolveInfo.filter = filter;
7906        forwardingResolveInfo.targetUserId = targetUserId;
7907        return forwardingResolveInfo;
7908    }
7909
7910    @Override
7911    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7912            Intent[] specifics, String[] specificTypes, Intent intent,
7913            String resolvedType, int flags, int userId) {
7914        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7915                specificTypes, intent, resolvedType, flags, userId));
7916    }
7917
7918    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7919            Intent[] specifics, String[] specificTypes, Intent intent,
7920            String resolvedType, int flags, int userId) {
7921        if (!sUserManager.exists(userId)) return Collections.emptyList();
7922        final int callingUid = Binder.getCallingUid();
7923        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7924                false /*includeInstantApps*/);
7925        enforceCrossUserPermission(callingUid, userId,
7926                false /*requireFullPermission*/, false /*checkShell*/,
7927                "query intent activity options");
7928        final String resultsAction = intent.getAction();
7929
7930        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7931                | PackageManager.GET_RESOLVED_FILTER, userId);
7932
7933        if (DEBUG_INTENT_MATCHING) {
7934            Log.v(TAG, "Query " + intent + ": " + results);
7935        }
7936
7937        int specificsPos = 0;
7938        int N;
7939
7940        // todo: note that the algorithm used here is O(N^2).  This
7941        // isn't a problem in our current environment, but if we start running
7942        // into situations where we have more than 5 or 10 matches then this
7943        // should probably be changed to something smarter...
7944
7945        // First we go through and resolve each of the specific items
7946        // that were supplied, taking care of removing any corresponding
7947        // duplicate items in the generic resolve list.
7948        if (specifics != null) {
7949            for (int i=0; i<specifics.length; i++) {
7950                final Intent sintent = specifics[i];
7951                if (sintent == null) {
7952                    continue;
7953                }
7954
7955                if (DEBUG_INTENT_MATCHING) {
7956                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7957                }
7958
7959                String action = sintent.getAction();
7960                if (resultsAction != null && resultsAction.equals(action)) {
7961                    // If this action was explicitly requested, then don't
7962                    // remove things that have it.
7963                    action = null;
7964                }
7965
7966                ResolveInfo ri = null;
7967                ActivityInfo ai = null;
7968
7969                ComponentName comp = sintent.getComponent();
7970                if (comp == null) {
7971                    ri = resolveIntent(
7972                        sintent,
7973                        specificTypes != null ? specificTypes[i] : null,
7974                            flags, userId);
7975                    if (ri == null) {
7976                        continue;
7977                    }
7978                    if (ri == mResolveInfo) {
7979                        // ACK!  Must do something better with this.
7980                    }
7981                    ai = ri.activityInfo;
7982                    comp = new ComponentName(ai.applicationInfo.packageName,
7983                            ai.name);
7984                } else {
7985                    ai = getActivityInfo(comp, flags, userId);
7986                    if (ai == null) {
7987                        continue;
7988                    }
7989                }
7990
7991                // Look for any generic query activities that are duplicates
7992                // of this specific one, and remove them from the results.
7993                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7994                N = results.size();
7995                int j;
7996                for (j=specificsPos; j<N; j++) {
7997                    ResolveInfo sri = results.get(j);
7998                    if ((sri.activityInfo.name.equals(comp.getClassName())
7999                            && sri.activityInfo.applicationInfo.packageName.equals(
8000                                    comp.getPackageName()))
8001                        || (action != null && sri.filter.matchAction(action))) {
8002                        results.remove(j);
8003                        if (DEBUG_INTENT_MATCHING) Log.v(
8004                            TAG, "Removing duplicate item from " + j
8005                            + " due to specific " + specificsPos);
8006                        if (ri == null) {
8007                            ri = sri;
8008                        }
8009                        j--;
8010                        N--;
8011                    }
8012                }
8013
8014                // Add this specific item to its proper place.
8015                if (ri == null) {
8016                    ri = new ResolveInfo();
8017                    ri.activityInfo = ai;
8018                }
8019                results.add(specificsPos, ri);
8020                ri.specificIndex = i;
8021                specificsPos++;
8022            }
8023        }
8024
8025        // Now we go through the remaining generic results and remove any
8026        // duplicate actions that are found here.
8027        N = results.size();
8028        for (int i=specificsPos; i<N-1; i++) {
8029            final ResolveInfo rii = results.get(i);
8030            if (rii.filter == null) {
8031                continue;
8032            }
8033
8034            // Iterate over all of the actions of this result's intent
8035            // filter...  typically this should be just one.
8036            final Iterator<String> it = rii.filter.actionsIterator();
8037            if (it == null) {
8038                continue;
8039            }
8040            while (it.hasNext()) {
8041                final String action = it.next();
8042                if (resultsAction != null && resultsAction.equals(action)) {
8043                    // If this action was explicitly requested, then don't
8044                    // remove things that have it.
8045                    continue;
8046                }
8047                for (int j=i+1; j<N; j++) {
8048                    final ResolveInfo rij = results.get(j);
8049                    if (rij.filter != null && rij.filter.hasAction(action)) {
8050                        results.remove(j);
8051                        if (DEBUG_INTENT_MATCHING) Log.v(
8052                            TAG, "Removing duplicate item from " + j
8053                            + " due to action " + action + " at " + i);
8054                        j--;
8055                        N--;
8056                    }
8057                }
8058            }
8059
8060            // If the caller didn't request filter information, drop it now
8061            // so we don't have to marshall/unmarshall it.
8062            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8063                rii.filter = null;
8064            }
8065        }
8066
8067        // Filter out the caller activity if so requested.
8068        if (caller != null) {
8069            N = results.size();
8070            for (int i=0; i<N; i++) {
8071                ActivityInfo ainfo = results.get(i).activityInfo;
8072                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8073                        && caller.getClassName().equals(ainfo.name)) {
8074                    results.remove(i);
8075                    break;
8076                }
8077            }
8078        }
8079
8080        // If the caller didn't request filter information,
8081        // drop them now so we don't have to
8082        // marshall/unmarshall it.
8083        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8084            N = results.size();
8085            for (int i=0; i<N; i++) {
8086                results.get(i).filter = null;
8087            }
8088        }
8089
8090        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8091        return results;
8092    }
8093
8094    @Override
8095    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8096            String resolvedType, int flags, int userId) {
8097        return new ParceledListSlice<>(
8098                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8099                        false /*allowDynamicSplits*/));
8100    }
8101
8102    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8103            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8104        if (!sUserManager.exists(userId)) return Collections.emptyList();
8105        final int callingUid = Binder.getCallingUid();
8106        enforceCrossUserPermission(callingUid, userId,
8107                false /*requireFullPermission*/, false /*checkShell*/,
8108                "query intent receivers");
8109        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8110        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8111                false /*includeInstantApps*/);
8112        ComponentName comp = intent.getComponent();
8113        if (comp == null) {
8114            if (intent.getSelector() != null) {
8115                intent = intent.getSelector();
8116                comp = intent.getComponent();
8117            }
8118        }
8119        if (comp != null) {
8120            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8121            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8122            if (ai != null) {
8123                // When specifying an explicit component, we prevent the activity from being
8124                // used when either 1) the calling package is normal and the activity is within
8125                // an instant application or 2) the calling package is ephemeral and the
8126                // activity is not visible to instant applications.
8127                final boolean matchInstantApp =
8128                        (flags & PackageManager.MATCH_INSTANT) != 0;
8129                final boolean matchVisibleToInstantAppOnly =
8130                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8131                final boolean matchExplicitlyVisibleOnly =
8132                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8133                final boolean isCallerInstantApp =
8134                        instantAppPkgName != null;
8135                final boolean isTargetSameInstantApp =
8136                        comp.getPackageName().equals(instantAppPkgName);
8137                final boolean isTargetInstantApp =
8138                        (ai.applicationInfo.privateFlags
8139                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8140                final boolean isTargetVisibleToInstantApp =
8141                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8142                final boolean isTargetExplicitlyVisibleToInstantApp =
8143                        isTargetVisibleToInstantApp
8144                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8145                final boolean isTargetHiddenFromInstantApp =
8146                        !isTargetVisibleToInstantApp
8147                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8148                final boolean blockResolution =
8149                        !isTargetSameInstantApp
8150                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8151                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8152                                        && isTargetHiddenFromInstantApp));
8153                if (!blockResolution) {
8154                    ResolveInfo ri = new ResolveInfo();
8155                    ri.activityInfo = ai;
8156                    list.add(ri);
8157                }
8158            }
8159            return applyPostResolutionFilter(
8160                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8161        }
8162
8163        // reader
8164        synchronized (mPackages) {
8165            String pkgName = intent.getPackage();
8166            if (pkgName == null) {
8167                final List<ResolveInfo> result =
8168                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8169                return applyPostResolutionFilter(
8170                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8171            }
8172            final PackageParser.Package pkg = mPackages.get(pkgName);
8173            if (pkg != null) {
8174                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8175                        intent, resolvedType, flags, pkg.receivers, userId);
8176                return applyPostResolutionFilter(
8177                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8178            }
8179            return Collections.emptyList();
8180        }
8181    }
8182
8183    @Override
8184    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8185        final int callingUid = Binder.getCallingUid();
8186        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8187    }
8188
8189    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8190            int userId, int callingUid) {
8191        if (!sUserManager.exists(userId)) return null;
8192        flags = updateFlagsForResolve(
8193                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8194        List<ResolveInfo> query = queryIntentServicesInternal(
8195                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8196        if (query != null) {
8197            if (query.size() >= 1) {
8198                // If there is more than one service with the same priority,
8199                // just arbitrarily pick the first one.
8200                return query.get(0);
8201            }
8202        }
8203        return null;
8204    }
8205
8206    @Override
8207    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8208            String resolvedType, int flags, int userId) {
8209        final int callingUid = Binder.getCallingUid();
8210        return new ParceledListSlice<>(queryIntentServicesInternal(
8211                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8212    }
8213
8214    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8215            String resolvedType, int flags, int userId, int callingUid,
8216            boolean includeInstantApps) {
8217        if (!sUserManager.exists(userId)) return Collections.emptyList();
8218        enforceCrossUserPermission(callingUid, userId,
8219                false /*requireFullPermission*/, false /*checkShell*/,
8220                "query intent receivers");
8221        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8222        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8223        ComponentName comp = intent.getComponent();
8224        if (comp == null) {
8225            if (intent.getSelector() != null) {
8226                intent = intent.getSelector();
8227                comp = intent.getComponent();
8228            }
8229        }
8230        if (comp != null) {
8231            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8232            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8233            if (si != null) {
8234                // When specifying an explicit component, we prevent the service from being
8235                // used when either 1) the service is in an instant application and the
8236                // caller is not the same instant application or 2) the calling package is
8237                // ephemeral and the activity is not visible to ephemeral applications.
8238                final boolean matchInstantApp =
8239                        (flags & PackageManager.MATCH_INSTANT) != 0;
8240                final boolean matchVisibleToInstantAppOnly =
8241                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8242                final boolean isCallerInstantApp =
8243                        instantAppPkgName != null;
8244                final boolean isTargetSameInstantApp =
8245                        comp.getPackageName().equals(instantAppPkgName);
8246                final boolean isTargetInstantApp =
8247                        (si.applicationInfo.privateFlags
8248                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8249                final boolean isTargetHiddenFromInstantApp =
8250                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8251                final boolean blockResolution =
8252                        !isTargetSameInstantApp
8253                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8254                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8255                                        && isTargetHiddenFromInstantApp));
8256                if (!blockResolution) {
8257                    final ResolveInfo ri = new ResolveInfo();
8258                    ri.serviceInfo = si;
8259                    list.add(ri);
8260                }
8261            }
8262            return list;
8263        }
8264
8265        // reader
8266        synchronized (mPackages) {
8267            String pkgName = intent.getPackage();
8268            if (pkgName == null) {
8269                return applyPostServiceResolutionFilter(
8270                        mServices.queryIntent(intent, resolvedType, flags, userId),
8271                        instantAppPkgName);
8272            }
8273            final PackageParser.Package pkg = mPackages.get(pkgName);
8274            if (pkg != null) {
8275                return applyPostServiceResolutionFilter(
8276                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8277                                userId),
8278                        instantAppPkgName);
8279            }
8280            return Collections.emptyList();
8281        }
8282    }
8283
8284    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8285            String instantAppPkgName) {
8286        if (instantAppPkgName == null) {
8287            return resolveInfos;
8288        }
8289        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8290            final ResolveInfo info = resolveInfos.get(i);
8291            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8292            // allow services that are defined in the provided package
8293            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8294                if (info.serviceInfo.splitName != null
8295                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8296                                info.serviceInfo.splitName)) {
8297                    // requested service is defined in a split that hasn't been installed yet.
8298                    // add the installer to the resolve list
8299                    if (DEBUG_EPHEMERAL) {
8300                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8301                    }
8302                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8303                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8304                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8305                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8306                            null /*failureIntent*/);
8307                    // make sure this resolver is the default
8308                    installerInfo.isDefault = true;
8309                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8310                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8311                    // add a non-generic filter
8312                    installerInfo.filter = new IntentFilter();
8313                    // load resources from the correct package
8314                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8315                    resolveInfos.set(i, installerInfo);
8316                }
8317                continue;
8318            }
8319            // allow services that have been explicitly exposed to ephemeral apps
8320            if (!isEphemeralApp
8321                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8322                continue;
8323            }
8324            resolveInfos.remove(i);
8325        }
8326        return resolveInfos;
8327    }
8328
8329    @Override
8330    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8331            String resolvedType, int flags, int userId) {
8332        return new ParceledListSlice<>(
8333                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8334    }
8335
8336    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8337            Intent intent, String resolvedType, int flags, int userId) {
8338        if (!sUserManager.exists(userId)) return Collections.emptyList();
8339        final int callingUid = Binder.getCallingUid();
8340        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8341        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8342                false /*includeInstantApps*/);
8343        ComponentName comp = intent.getComponent();
8344        if (comp == null) {
8345            if (intent.getSelector() != null) {
8346                intent = intent.getSelector();
8347                comp = intent.getComponent();
8348            }
8349        }
8350        if (comp != null) {
8351            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8352            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8353            if (pi != null) {
8354                // When specifying an explicit component, we prevent the provider from being
8355                // used when either 1) the provider is in an instant application and the
8356                // caller is not the same instant application or 2) the calling package is an
8357                // instant application and the provider is not visible to instant applications.
8358                final boolean matchInstantApp =
8359                        (flags & PackageManager.MATCH_INSTANT) != 0;
8360                final boolean matchVisibleToInstantAppOnly =
8361                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8362                final boolean isCallerInstantApp =
8363                        instantAppPkgName != null;
8364                final boolean isTargetSameInstantApp =
8365                        comp.getPackageName().equals(instantAppPkgName);
8366                final boolean isTargetInstantApp =
8367                        (pi.applicationInfo.privateFlags
8368                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8369                final boolean isTargetHiddenFromInstantApp =
8370                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8371                final boolean blockResolution =
8372                        !isTargetSameInstantApp
8373                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8374                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8375                                        && isTargetHiddenFromInstantApp));
8376                if (!blockResolution) {
8377                    final ResolveInfo ri = new ResolveInfo();
8378                    ri.providerInfo = pi;
8379                    list.add(ri);
8380                }
8381            }
8382            return list;
8383        }
8384
8385        // reader
8386        synchronized (mPackages) {
8387            String pkgName = intent.getPackage();
8388            if (pkgName == null) {
8389                return applyPostContentProviderResolutionFilter(
8390                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8391                        instantAppPkgName);
8392            }
8393            final PackageParser.Package pkg = mPackages.get(pkgName);
8394            if (pkg != null) {
8395                return applyPostContentProviderResolutionFilter(
8396                        mProviders.queryIntentForPackage(
8397                        intent, resolvedType, flags, pkg.providers, userId),
8398                        instantAppPkgName);
8399            }
8400            return Collections.emptyList();
8401        }
8402    }
8403
8404    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8405            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8406        if (instantAppPkgName == null) {
8407            return resolveInfos;
8408        }
8409        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8410            final ResolveInfo info = resolveInfos.get(i);
8411            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8412            // allow providers that are defined in the provided package
8413            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8414                if (info.providerInfo.splitName != null
8415                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8416                                info.providerInfo.splitName)) {
8417                    // requested provider is defined in a split that hasn't been installed yet.
8418                    // add the installer to the resolve list
8419                    if (DEBUG_EPHEMERAL) {
8420                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8421                    }
8422                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8423                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8424                            info.providerInfo.packageName, info.providerInfo.splitName,
8425                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8426                            null /*failureIntent*/);
8427                    // make sure this resolver is the default
8428                    installerInfo.isDefault = true;
8429                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8430                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8431                    // add a non-generic filter
8432                    installerInfo.filter = new IntentFilter();
8433                    // load resources from the correct package
8434                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8435                    resolveInfos.set(i, installerInfo);
8436                }
8437                continue;
8438            }
8439            // allow providers that have been explicitly exposed to instant applications
8440            if (!isEphemeralApp
8441                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8442                continue;
8443            }
8444            resolveInfos.remove(i);
8445        }
8446        return resolveInfos;
8447    }
8448
8449    @Override
8450    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8451        final int callingUid = Binder.getCallingUid();
8452        if (getInstantAppPackageName(callingUid) != null) {
8453            return ParceledListSlice.emptyList();
8454        }
8455        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8456        flags = updateFlagsForPackage(flags, userId, null);
8457        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8458        enforceCrossUserPermission(callingUid, userId,
8459                true /* requireFullPermission */, false /* checkShell */,
8460                "get installed packages");
8461
8462        // writer
8463        synchronized (mPackages) {
8464            ArrayList<PackageInfo> list;
8465            if (listUninstalled) {
8466                list = new ArrayList<>(mSettings.mPackages.size());
8467                for (PackageSetting ps : mSettings.mPackages.values()) {
8468                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8469                        continue;
8470                    }
8471                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8472                        return null;
8473                    }
8474                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8475                    if (pi != null) {
8476                        list.add(pi);
8477                    }
8478                }
8479            } else {
8480                list = new ArrayList<>(mPackages.size());
8481                for (PackageParser.Package p : mPackages.values()) {
8482                    final PackageSetting ps = (PackageSetting) p.mExtras;
8483                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8484                        continue;
8485                    }
8486                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8487                        return null;
8488                    }
8489                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8490                            p.mExtras, flags, userId);
8491                    if (pi != null) {
8492                        list.add(pi);
8493                    }
8494                }
8495            }
8496
8497            return new ParceledListSlice<>(list);
8498        }
8499    }
8500
8501    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8502            String[] permissions, boolean[] tmp, int flags, int userId) {
8503        int numMatch = 0;
8504        final PermissionsState permissionsState = ps.getPermissionsState();
8505        for (int i=0; i<permissions.length; i++) {
8506            final String permission = permissions[i];
8507            if (permissionsState.hasPermission(permission, userId)) {
8508                tmp[i] = true;
8509                numMatch++;
8510            } else {
8511                tmp[i] = false;
8512            }
8513        }
8514        if (numMatch == 0) {
8515            return;
8516        }
8517        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8518
8519        // The above might return null in cases of uninstalled apps or install-state
8520        // skew across users/profiles.
8521        if (pi != null) {
8522            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8523                if (numMatch == permissions.length) {
8524                    pi.requestedPermissions = permissions;
8525                } else {
8526                    pi.requestedPermissions = new String[numMatch];
8527                    numMatch = 0;
8528                    for (int i=0; i<permissions.length; i++) {
8529                        if (tmp[i]) {
8530                            pi.requestedPermissions[numMatch] = permissions[i];
8531                            numMatch++;
8532                        }
8533                    }
8534                }
8535            }
8536            list.add(pi);
8537        }
8538    }
8539
8540    @Override
8541    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8542            String[] permissions, int flags, int userId) {
8543        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8544        flags = updateFlagsForPackage(flags, userId, permissions);
8545        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8546                true /* requireFullPermission */, false /* checkShell */,
8547                "get packages holding permissions");
8548        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8549
8550        // writer
8551        synchronized (mPackages) {
8552            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8553            boolean[] tmpBools = new boolean[permissions.length];
8554            if (listUninstalled) {
8555                for (PackageSetting ps : mSettings.mPackages.values()) {
8556                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8557                            userId);
8558                }
8559            } else {
8560                for (PackageParser.Package pkg : mPackages.values()) {
8561                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8562                    if (ps != null) {
8563                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8564                                userId);
8565                    }
8566                }
8567            }
8568
8569            return new ParceledListSlice<PackageInfo>(list);
8570        }
8571    }
8572
8573    @Override
8574    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8575        final int callingUid = Binder.getCallingUid();
8576        if (getInstantAppPackageName(callingUid) != null) {
8577            return ParceledListSlice.emptyList();
8578        }
8579        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8580        flags = updateFlagsForApplication(flags, userId, null);
8581        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8582
8583        // writer
8584        synchronized (mPackages) {
8585            ArrayList<ApplicationInfo> list;
8586            if (listUninstalled) {
8587                list = new ArrayList<>(mSettings.mPackages.size());
8588                for (PackageSetting ps : mSettings.mPackages.values()) {
8589                    ApplicationInfo ai;
8590                    int effectiveFlags = flags;
8591                    if (ps.isSystem()) {
8592                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8593                    }
8594                    if (ps.pkg != null) {
8595                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8596                            continue;
8597                        }
8598                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8599                            return null;
8600                        }
8601                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8602                                ps.readUserState(userId), userId);
8603                        if (ai != null) {
8604                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8605                        }
8606                    } else {
8607                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8608                        // and already converts to externally visible package name
8609                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8610                                callingUid, effectiveFlags, userId);
8611                    }
8612                    if (ai != null) {
8613                        list.add(ai);
8614                    }
8615                }
8616            } else {
8617                list = new ArrayList<>(mPackages.size());
8618                for (PackageParser.Package p : mPackages.values()) {
8619                    if (p.mExtras != null) {
8620                        PackageSetting ps = (PackageSetting) p.mExtras;
8621                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8622                            continue;
8623                        }
8624                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8625                            return null;
8626                        }
8627                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8628                                ps.readUserState(userId), userId);
8629                        if (ai != null) {
8630                            ai.packageName = resolveExternalPackageNameLPr(p);
8631                            list.add(ai);
8632                        }
8633                    }
8634                }
8635            }
8636
8637            return new ParceledListSlice<>(list);
8638        }
8639    }
8640
8641    @Override
8642    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8643        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8644            return null;
8645        }
8646        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8647            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8648                    "getEphemeralApplications");
8649        }
8650        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8651                true /* requireFullPermission */, false /* checkShell */,
8652                "getEphemeralApplications");
8653        synchronized (mPackages) {
8654            List<InstantAppInfo> instantApps = mInstantAppRegistry
8655                    .getInstantAppsLPr(userId);
8656            if (instantApps != null) {
8657                return new ParceledListSlice<>(instantApps);
8658            }
8659        }
8660        return null;
8661    }
8662
8663    @Override
8664    public boolean isInstantApp(String packageName, int userId) {
8665        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8666                true /* requireFullPermission */, false /* checkShell */,
8667                "isInstantApp");
8668        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8669            return false;
8670        }
8671
8672        synchronized (mPackages) {
8673            int callingUid = Binder.getCallingUid();
8674            if (Process.isIsolated(callingUid)) {
8675                callingUid = mIsolatedOwners.get(callingUid);
8676            }
8677            final PackageSetting ps = mSettings.mPackages.get(packageName);
8678            PackageParser.Package pkg = mPackages.get(packageName);
8679            final boolean returnAllowed =
8680                    ps != null
8681                    && (isCallerSameApp(packageName, callingUid)
8682                            || canViewInstantApps(callingUid, userId)
8683                            || mInstantAppRegistry.isInstantAccessGranted(
8684                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8685            if (returnAllowed) {
8686                return ps.getInstantApp(userId);
8687            }
8688        }
8689        return false;
8690    }
8691
8692    @Override
8693    public byte[] getInstantAppCookie(String packageName, int userId) {
8694        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8695            return null;
8696        }
8697
8698        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8699                true /* requireFullPermission */, false /* checkShell */,
8700                "getInstantAppCookie");
8701        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8702            return null;
8703        }
8704        synchronized (mPackages) {
8705            return mInstantAppRegistry.getInstantAppCookieLPw(
8706                    packageName, userId);
8707        }
8708    }
8709
8710    @Override
8711    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8712        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8713            return true;
8714        }
8715
8716        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8717                true /* requireFullPermission */, true /* checkShell */,
8718                "setInstantAppCookie");
8719        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8720            return false;
8721        }
8722        synchronized (mPackages) {
8723            return mInstantAppRegistry.setInstantAppCookieLPw(
8724                    packageName, cookie, userId);
8725        }
8726    }
8727
8728    @Override
8729    public Bitmap getInstantAppIcon(String packageName, int userId) {
8730        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8731            return null;
8732        }
8733
8734        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8735            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8736                    "getInstantAppIcon");
8737        }
8738        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8739                true /* requireFullPermission */, false /* checkShell */,
8740                "getInstantAppIcon");
8741
8742        synchronized (mPackages) {
8743            return mInstantAppRegistry.getInstantAppIconLPw(
8744                    packageName, userId);
8745        }
8746    }
8747
8748    private boolean isCallerSameApp(String packageName, int uid) {
8749        PackageParser.Package pkg = mPackages.get(packageName);
8750        return pkg != null
8751                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8752    }
8753
8754    @Override
8755    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8756        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8757            return ParceledListSlice.emptyList();
8758        }
8759        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8760    }
8761
8762    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8763        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8764
8765        // reader
8766        synchronized (mPackages) {
8767            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8768            final int userId = UserHandle.getCallingUserId();
8769            while (i.hasNext()) {
8770                final PackageParser.Package p = i.next();
8771                if (p.applicationInfo == null) continue;
8772
8773                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8774                        && !p.applicationInfo.isDirectBootAware();
8775                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8776                        && p.applicationInfo.isDirectBootAware();
8777
8778                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8779                        && (!mSafeMode || isSystemApp(p))
8780                        && (matchesUnaware || matchesAware)) {
8781                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8782                    if (ps != null) {
8783                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8784                                ps.readUserState(userId), userId);
8785                        if (ai != null) {
8786                            finalList.add(ai);
8787                        }
8788                    }
8789                }
8790            }
8791        }
8792
8793        return finalList;
8794    }
8795
8796    @Override
8797    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8798        if (!sUserManager.exists(userId)) return null;
8799        flags = updateFlagsForComponent(flags, userId, name);
8800        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8801        // reader
8802        synchronized (mPackages) {
8803            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8804            PackageSetting ps = provider != null
8805                    ? mSettings.mPackages.get(provider.owner.packageName)
8806                    : null;
8807            if (ps != null) {
8808                final boolean isInstantApp = ps.getInstantApp(userId);
8809                // normal application; filter out instant application provider
8810                if (instantAppPkgName == null && isInstantApp) {
8811                    return null;
8812                }
8813                // instant application; filter out other instant applications
8814                if (instantAppPkgName != null
8815                        && isInstantApp
8816                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8817                    return null;
8818                }
8819                // instant application; filter out non-exposed provider
8820                if (instantAppPkgName != null
8821                        && !isInstantApp
8822                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8823                    return null;
8824                }
8825                // provider not enabled
8826                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8827                    return null;
8828                }
8829                return PackageParser.generateProviderInfo(
8830                        provider, flags, ps.readUserState(userId), userId);
8831            }
8832            return null;
8833        }
8834    }
8835
8836    /**
8837     * @deprecated
8838     */
8839    @Deprecated
8840    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8841        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8842            return;
8843        }
8844        // reader
8845        synchronized (mPackages) {
8846            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8847                    .entrySet().iterator();
8848            final int userId = UserHandle.getCallingUserId();
8849            while (i.hasNext()) {
8850                Map.Entry<String, PackageParser.Provider> entry = i.next();
8851                PackageParser.Provider p = entry.getValue();
8852                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8853
8854                if (ps != null && p.syncable
8855                        && (!mSafeMode || (p.info.applicationInfo.flags
8856                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8857                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8858                            ps.readUserState(userId), userId);
8859                    if (info != null) {
8860                        outNames.add(entry.getKey());
8861                        outInfo.add(info);
8862                    }
8863                }
8864            }
8865        }
8866    }
8867
8868    @Override
8869    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8870            int uid, int flags, String metaDataKey) {
8871        final int callingUid = Binder.getCallingUid();
8872        final int userId = processName != null ? UserHandle.getUserId(uid)
8873                : UserHandle.getCallingUserId();
8874        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8875        flags = updateFlagsForComponent(flags, userId, processName);
8876        ArrayList<ProviderInfo> finalList = null;
8877        // reader
8878        synchronized (mPackages) {
8879            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8880            while (i.hasNext()) {
8881                final PackageParser.Provider p = i.next();
8882                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8883                if (ps != null && p.info.authority != null
8884                        && (processName == null
8885                                || (p.info.processName.equals(processName)
8886                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8887                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8888
8889                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8890                    // parameter.
8891                    if (metaDataKey != null
8892                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8893                        continue;
8894                    }
8895                    final ComponentName component =
8896                            new ComponentName(p.info.packageName, p.info.name);
8897                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8898                        continue;
8899                    }
8900                    if (finalList == null) {
8901                        finalList = new ArrayList<ProviderInfo>(3);
8902                    }
8903                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8904                            ps.readUserState(userId), userId);
8905                    if (info != null) {
8906                        finalList.add(info);
8907                    }
8908                }
8909            }
8910        }
8911
8912        if (finalList != null) {
8913            Collections.sort(finalList, mProviderInitOrderSorter);
8914            return new ParceledListSlice<ProviderInfo>(finalList);
8915        }
8916
8917        return ParceledListSlice.emptyList();
8918    }
8919
8920    @Override
8921    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8922        // reader
8923        synchronized (mPackages) {
8924            final int callingUid = Binder.getCallingUid();
8925            final int callingUserId = UserHandle.getUserId(callingUid);
8926            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8927            if (ps == null) return null;
8928            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8929                return null;
8930            }
8931            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8932            return PackageParser.generateInstrumentationInfo(i, flags);
8933        }
8934    }
8935
8936    @Override
8937    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8938            String targetPackage, int flags) {
8939        final int callingUid = Binder.getCallingUid();
8940        final int callingUserId = UserHandle.getUserId(callingUid);
8941        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8942        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8943            return ParceledListSlice.emptyList();
8944        }
8945        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8946    }
8947
8948    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8949            int flags) {
8950        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8951
8952        // reader
8953        synchronized (mPackages) {
8954            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8955            while (i.hasNext()) {
8956                final PackageParser.Instrumentation p = i.next();
8957                if (targetPackage == null
8958                        || targetPackage.equals(p.info.targetPackage)) {
8959                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8960                            flags);
8961                    if (ii != null) {
8962                        finalList.add(ii);
8963                    }
8964                }
8965            }
8966        }
8967
8968        return finalList;
8969    }
8970
8971    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8972        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8973        try {
8974            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8975        } finally {
8976            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8977        }
8978    }
8979
8980    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8981        final File[] files = dir.listFiles();
8982        if (ArrayUtils.isEmpty(files)) {
8983            Log.d(TAG, "No files in app dir " + dir);
8984            return;
8985        }
8986
8987        if (DEBUG_PACKAGE_SCANNING) {
8988            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8989                    + " flags=0x" + Integer.toHexString(parseFlags));
8990        }
8991        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8992                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8993                mParallelPackageParserCallback);
8994
8995        // Submit files for parsing in parallel
8996        int fileCount = 0;
8997        for (File file : files) {
8998            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8999                    && !PackageInstallerService.isStageName(file.getName());
9000            if (!isPackage) {
9001                // Ignore entries which are not packages
9002                continue;
9003            }
9004            parallelPackageParser.submit(file, parseFlags);
9005            fileCount++;
9006        }
9007
9008        // Process results one by one
9009        for (; fileCount > 0; fileCount--) {
9010            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
9011            Throwable throwable = parseResult.throwable;
9012            int errorCode = PackageManager.INSTALL_SUCCEEDED;
9013
9014            if (throwable == null) {
9015                // Static shared libraries have synthetic package names
9016                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
9017                    renameStaticSharedLibraryPackage(parseResult.pkg);
9018                }
9019                try {
9020                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
9021                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
9022                                currentTime, null);
9023                    }
9024                } catch (PackageManagerException e) {
9025                    errorCode = e.error;
9026                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9027                }
9028            } else if (throwable instanceof PackageParser.PackageParserException) {
9029                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9030                        throwable;
9031                errorCode = e.error;
9032                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9033            } else {
9034                throw new IllegalStateException("Unexpected exception occurred while parsing "
9035                        + parseResult.scanFile, throwable);
9036            }
9037
9038            // Delete invalid userdata apps
9039            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9040                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9041                logCriticalInfo(Log.WARN,
9042                        "Deleting invalid package at " + parseResult.scanFile);
9043                removeCodePathLI(parseResult.scanFile);
9044            }
9045        }
9046        parallelPackageParser.close();
9047    }
9048
9049    private static File getSettingsProblemFile() {
9050        File dataDir = Environment.getDataDirectory();
9051        File systemDir = new File(dataDir, "system");
9052        File fname = new File(systemDir, "uiderrors.txt");
9053        return fname;
9054    }
9055
9056    static void reportSettingsProblem(int priority, String msg) {
9057        logCriticalInfo(priority, msg);
9058    }
9059
9060    public static void logCriticalInfo(int priority, String msg) {
9061        Slog.println(priority, TAG, msg);
9062        EventLogTags.writePmCriticalInfo(msg);
9063        try {
9064            File fname = getSettingsProblemFile();
9065            FileOutputStream out = new FileOutputStream(fname, true);
9066            PrintWriter pw = new FastPrintWriter(out);
9067            SimpleDateFormat formatter = new SimpleDateFormat();
9068            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9069            pw.println(dateString + ": " + msg);
9070            pw.close();
9071            FileUtils.setPermissions(
9072                    fname.toString(),
9073                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9074                    -1, -1);
9075        } catch (java.io.IOException e) {
9076        }
9077    }
9078
9079    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9080        if (srcFile.isDirectory()) {
9081            final File baseFile = new File(pkg.baseCodePath);
9082            long maxModifiedTime = baseFile.lastModified();
9083            if (pkg.splitCodePaths != null) {
9084                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9085                    final File splitFile = new File(pkg.splitCodePaths[i]);
9086                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9087                }
9088            }
9089            return maxModifiedTime;
9090        }
9091        return srcFile.lastModified();
9092    }
9093
9094    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9095            final int policyFlags) throws PackageManagerException {
9096        // When upgrading from pre-N MR1, verify the package time stamp using the package
9097        // directory and not the APK file.
9098        final long lastModifiedTime = mIsPreNMR1Upgrade
9099                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9100        if (ps != null
9101                && ps.codePath.equals(srcFile)
9102                && ps.timeStamp == lastModifiedTime
9103                && !isCompatSignatureUpdateNeeded(pkg)
9104                && !isRecoverSignatureUpdateNeeded(pkg)) {
9105            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9106            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9107            ArraySet<PublicKey> signingKs;
9108            synchronized (mPackages) {
9109                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9110            }
9111            if (ps.signatures.mSignatures != null
9112                    && ps.signatures.mSignatures.length != 0
9113                    && signingKs != null) {
9114                // Optimization: reuse the existing cached certificates
9115                // if the package appears to be unchanged.
9116                pkg.mSignatures = ps.signatures.mSignatures;
9117                pkg.mSigningKeys = signingKs;
9118                return;
9119            }
9120
9121            Slog.w(TAG, "PackageSetting for " + ps.name
9122                    + " is missing signatures.  Collecting certs again to recover them.");
9123        } else {
9124            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9125        }
9126
9127        try {
9128            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9129            PackageParser.collectCertificates(pkg, policyFlags);
9130        } catch (PackageParserException e) {
9131            throw PackageManagerException.from(e);
9132        } finally {
9133            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9134        }
9135    }
9136
9137    /**
9138     *  Traces a package scan.
9139     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9140     */
9141    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9142            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9143        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9144        try {
9145            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9146        } finally {
9147            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9148        }
9149    }
9150
9151    /**
9152     *  Scans a package and returns the newly parsed package.
9153     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9154     */
9155    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9156            long currentTime, UserHandle user) throws PackageManagerException {
9157        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9158        PackageParser pp = new PackageParser();
9159        pp.setSeparateProcesses(mSeparateProcesses);
9160        pp.setOnlyCoreApps(mOnlyCore);
9161        pp.setDisplayMetrics(mMetrics);
9162        pp.setCallback(mPackageParserCallback);
9163
9164        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9165            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9166        }
9167
9168        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9169        final PackageParser.Package pkg;
9170        try {
9171            pkg = pp.parsePackage(scanFile, parseFlags);
9172        } catch (PackageParserException e) {
9173            throw PackageManagerException.from(e);
9174        } finally {
9175            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9176        }
9177
9178        // Static shared libraries have synthetic package names
9179        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9180            renameStaticSharedLibraryPackage(pkg);
9181        }
9182
9183        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9184    }
9185
9186    /**
9187     *  Scans a package and returns the newly parsed package.
9188     *  @throws PackageManagerException on a parse error.
9189     */
9190    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9191            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9192            throws PackageManagerException {
9193        // If the package has children and this is the first dive in the function
9194        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9195        // packages (parent and children) would be successfully scanned before the
9196        // actual scan since scanning mutates internal state and we want to atomically
9197        // install the package and its children.
9198        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9199            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9200                scanFlags |= SCAN_CHECK_ONLY;
9201            }
9202        } else {
9203            scanFlags &= ~SCAN_CHECK_ONLY;
9204        }
9205
9206        // Scan the parent
9207        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9208                scanFlags, currentTime, user);
9209
9210        // Scan the children
9211        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9212        for (int i = 0; i < childCount; i++) {
9213            PackageParser.Package childPackage = pkg.childPackages.get(i);
9214            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9215                    currentTime, user);
9216        }
9217
9218
9219        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9220            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9221        }
9222
9223        return scannedPkg;
9224    }
9225
9226    /**
9227     *  Scans a package and returns the newly parsed package.
9228     *  @throws PackageManagerException on a parse error.
9229     */
9230    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9231            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9232            throws PackageManagerException {
9233        PackageSetting ps = null;
9234        PackageSetting updatedPkg;
9235        // reader
9236        synchronized (mPackages) {
9237            // Look to see if we already know about this package.
9238            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9239            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9240                // This package has been renamed to its original name.  Let's
9241                // use that.
9242                ps = mSettings.getPackageLPr(oldName);
9243            }
9244            // If there was no original package, see one for the real package name.
9245            if (ps == null) {
9246                ps = mSettings.getPackageLPr(pkg.packageName);
9247            }
9248            // Check to see if this package could be hiding/updating a system
9249            // package.  Must look for it either under the original or real
9250            // package name depending on our state.
9251            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9252            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9253
9254            // If this is a package we don't know about on the system partition, we
9255            // may need to remove disabled child packages on the system partition
9256            // or may need to not add child packages if the parent apk is updated
9257            // on the data partition and no longer defines this child package.
9258            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9259                // If this is a parent package for an updated system app and this system
9260                // app got an OTA update which no longer defines some of the child packages
9261                // we have to prune them from the disabled system packages.
9262                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9263                if (disabledPs != null) {
9264                    final int scannedChildCount = (pkg.childPackages != null)
9265                            ? pkg.childPackages.size() : 0;
9266                    final int disabledChildCount = disabledPs.childPackageNames != null
9267                            ? disabledPs.childPackageNames.size() : 0;
9268                    for (int i = 0; i < disabledChildCount; i++) {
9269                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9270                        boolean disabledPackageAvailable = false;
9271                        for (int j = 0; j < scannedChildCount; j++) {
9272                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9273                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9274                                disabledPackageAvailable = true;
9275                                break;
9276                            }
9277                         }
9278                         if (!disabledPackageAvailable) {
9279                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9280                         }
9281                    }
9282                }
9283            }
9284        }
9285
9286        final boolean isUpdatedPkg = updatedPkg != null;
9287        final boolean isUpdatedSystemPkg = isUpdatedPkg
9288                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9289        boolean isUpdatedPkgBetter = false;
9290        // First check if this is a system package that may involve an update
9291        if (isUpdatedSystemPkg) {
9292            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9293            // it needs to drop FLAG_PRIVILEGED.
9294            if (locationIsPrivileged(scanFile)) {
9295                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9296            } else {
9297                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9298            }
9299
9300            if (ps != null && !ps.codePath.equals(scanFile)) {
9301                // The path has changed from what was last scanned...  check the
9302                // version of the new path against what we have stored to determine
9303                // what to do.
9304                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9305                if (pkg.mVersionCode <= ps.versionCode) {
9306                    // The system package has been updated and the code path does not match
9307                    // Ignore entry. Skip it.
9308                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9309                            + " ignored: updated version " + ps.versionCode
9310                            + " better than this " + pkg.mVersionCode);
9311                    if (!updatedPkg.codePath.equals(scanFile)) {
9312                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9313                                + ps.name + " changing from " + updatedPkg.codePathString
9314                                + " to " + scanFile);
9315                        updatedPkg.codePath = scanFile;
9316                        updatedPkg.codePathString = scanFile.toString();
9317                        updatedPkg.resourcePath = scanFile;
9318                        updatedPkg.resourcePathString = scanFile.toString();
9319                    }
9320                    updatedPkg.pkg = pkg;
9321                    updatedPkg.versionCode = pkg.mVersionCode;
9322
9323                    // Update the disabled system child packages to point to the package too.
9324                    final int childCount = updatedPkg.childPackageNames != null
9325                            ? updatedPkg.childPackageNames.size() : 0;
9326                    for (int i = 0; i < childCount; i++) {
9327                        String childPackageName = updatedPkg.childPackageNames.get(i);
9328                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9329                                childPackageName);
9330                        if (updatedChildPkg != null) {
9331                            updatedChildPkg.pkg = pkg;
9332                            updatedChildPkg.versionCode = pkg.mVersionCode;
9333                        }
9334                    }
9335                } else {
9336                    // The current app on the system partition is better than
9337                    // what we have updated to on the data partition; switch
9338                    // back to the system partition version.
9339                    // At this point, its safely assumed that package installation for
9340                    // apps in system partition will go through. If not there won't be a working
9341                    // version of the app
9342                    // writer
9343                    synchronized (mPackages) {
9344                        // Just remove the loaded entries from package lists.
9345                        mPackages.remove(ps.name);
9346                    }
9347
9348                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9349                            + " reverting from " + ps.codePathString
9350                            + ": new version " + pkg.mVersionCode
9351                            + " better than installed " + ps.versionCode);
9352
9353                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9354                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9355                    synchronized (mInstallLock) {
9356                        args.cleanUpResourcesLI();
9357                    }
9358                    synchronized (mPackages) {
9359                        mSettings.enableSystemPackageLPw(ps.name);
9360                    }
9361                    isUpdatedPkgBetter = true;
9362                }
9363            }
9364        }
9365
9366        String resourcePath = null;
9367        String baseResourcePath = null;
9368        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9369            if (ps != null && ps.resourcePathString != null) {
9370                resourcePath = ps.resourcePathString;
9371                baseResourcePath = ps.resourcePathString;
9372            } else {
9373                // Should not happen at all. Just log an error.
9374                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9375            }
9376        } else {
9377            resourcePath = pkg.codePath;
9378            baseResourcePath = pkg.baseCodePath;
9379        }
9380
9381        // Set application objects path explicitly.
9382        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9383        pkg.setApplicationInfoCodePath(pkg.codePath);
9384        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9385        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9386        pkg.setApplicationInfoResourcePath(resourcePath);
9387        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9388        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9389
9390        // throw an exception if we have an update to a system application, but, it's not more
9391        // recent than the package we've already scanned
9392        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9393            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9394                    + scanFile + " ignored: updated version " + ps.versionCode
9395                    + " better than this " + pkg.mVersionCode);
9396        }
9397
9398        if (isUpdatedPkg) {
9399            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9400            // initially
9401            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9402
9403            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9404            // flag set initially
9405            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9406                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9407            }
9408        }
9409
9410        // Verify certificates against what was last scanned
9411        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9412
9413        /*
9414         * A new system app appeared, but we already had a non-system one of the
9415         * same name installed earlier.
9416         */
9417        boolean shouldHideSystemApp = false;
9418        if (!isUpdatedPkg && ps != null
9419                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9420            /*
9421             * Check to make sure the signatures match first. If they don't,
9422             * wipe the installed application and its data.
9423             */
9424            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9425                    != PackageManager.SIGNATURE_MATCH) {
9426                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9427                        + " signatures don't match existing userdata copy; removing");
9428                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9429                        "scanPackageInternalLI")) {
9430                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9431                }
9432                ps = null;
9433            } else {
9434                /*
9435                 * If the newly-added system app is an older version than the
9436                 * already installed version, hide it. It will be scanned later
9437                 * and re-added like an update.
9438                 */
9439                if (pkg.mVersionCode <= ps.versionCode) {
9440                    shouldHideSystemApp = true;
9441                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9442                            + " but new version " + pkg.mVersionCode + " better than installed "
9443                            + ps.versionCode + "; hiding system");
9444                } else {
9445                    /*
9446                     * The newly found system app is a newer version that the
9447                     * one previously installed. Simply remove the
9448                     * already-installed application and replace it with our own
9449                     * while keeping the application data.
9450                     */
9451                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9452                            + " reverting from " + ps.codePathString + ": new version "
9453                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9454                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9455                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9456                    synchronized (mInstallLock) {
9457                        args.cleanUpResourcesLI();
9458                    }
9459                }
9460            }
9461        }
9462
9463        // The apk is forward locked (not public) if its code and resources
9464        // are kept in different files. (except for app in either system or
9465        // vendor path).
9466        // TODO grab this value from PackageSettings
9467        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9468            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9469                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9470            }
9471        }
9472
9473        final int userId = ((user == null) ? 0 : user.getIdentifier());
9474        if (ps != null && ps.getInstantApp(userId)) {
9475            scanFlags |= SCAN_AS_INSTANT_APP;
9476        }
9477        if (ps != null && ps.getVirtulalPreload(userId)) {
9478            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9479        }
9480
9481        // Note that we invoke the following method only if we are about to unpack an application
9482        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9483                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9484
9485        /*
9486         * If the system app should be overridden by a previously installed
9487         * data, hide the system app now and let the /data/app scan pick it up
9488         * again.
9489         */
9490        if (shouldHideSystemApp) {
9491            synchronized (mPackages) {
9492                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9493            }
9494        }
9495
9496        return scannedPkg;
9497    }
9498
9499    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9500        // Derive the new package synthetic package name
9501        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9502                + pkg.staticSharedLibVersion);
9503    }
9504
9505    private static String fixProcessName(String defProcessName,
9506            String processName) {
9507        if (processName == null) {
9508            return defProcessName;
9509        }
9510        return processName;
9511    }
9512
9513    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9514            throws PackageManagerException {
9515        if (pkgSetting.signatures.mSignatures != null) {
9516            // Already existing package. Make sure signatures match
9517            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9518                    == PackageManager.SIGNATURE_MATCH;
9519            if (!match) {
9520                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9521                        == PackageManager.SIGNATURE_MATCH;
9522            }
9523            if (!match) {
9524                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9525                        == PackageManager.SIGNATURE_MATCH;
9526            }
9527            if (!match) {
9528                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9529                        + pkg.packageName + " signatures do not match the "
9530                        + "previously installed version; ignoring!");
9531            }
9532        }
9533
9534        // Check for shared user signatures
9535        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9536            // Already existing package. Make sure signatures match
9537            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9538                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9539            if (!match) {
9540                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9541                        == PackageManager.SIGNATURE_MATCH;
9542            }
9543            if (!match) {
9544                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9545                        == PackageManager.SIGNATURE_MATCH;
9546            }
9547            if (!match) {
9548                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9549                        "Package " + pkg.packageName
9550                        + " has no signatures that match those in shared user "
9551                        + pkgSetting.sharedUser.name + "; ignoring!");
9552            }
9553        }
9554    }
9555
9556    /**
9557     * Enforces that only the system UID or root's UID can call a method exposed
9558     * via Binder.
9559     *
9560     * @param message used as message if SecurityException is thrown
9561     * @throws SecurityException if the caller is not system or root
9562     */
9563    private static final void enforceSystemOrRoot(String message) {
9564        final int uid = Binder.getCallingUid();
9565        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9566            throw new SecurityException(message);
9567        }
9568    }
9569
9570    @Override
9571    public void performFstrimIfNeeded() {
9572        enforceSystemOrRoot("Only the system can request fstrim");
9573
9574        // Before everything else, see whether we need to fstrim.
9575        try {
9576            IStorageManager sm = PackageHelper.getStorageManager();
9577            if (sm != null) {
9578                boolean doTrim = false;
9579                final long interval = android.provider.Settings.Global.getLong(
9580                        mContext.getContentResolver(),
9581                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9582                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9583                if (interval > 0) {
9584                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9585                    if (timeSinceLast > interval) {
9586                        doTrim = true;
9587                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9588                                + "; running immediately");
9589                    }
9590                }
9591                if (doTrim) {
9592                    final boolean dexOptDialogShown;
9593                    synchronized (mPackages) {
9594                        dexOptDialogShown = mDexOptDialogShown;
9595                    }
9596                    if (!isFirstBoot() && dexOptDialogShown) {
9597                        try {
9598                            ActivityManager.getService().showBootMessage(
9599                                    mContext.getResources().getString(
9600                                            R.string.android_upgrading_fstrim), true);
9601                        } catch (RemoteException e) {
9602                        }
9603                    }
9604                    sm.runMaintenance();
9605                }
9606            } else {
9607                Slog.e(TAG, "storageManager service unavailable!");
9608            }
9609        } catch (RemoteException e) {
9610            // Can't happen; StorageManagerService is local
9611        }
9612    }
9613
9614    @Override
9615    public void updatePackagesIfNeeded() {
9616        enforceSystemOrRoot("Only the system can request package update");
9617
9618        // We need to re-extract after an OTA.
9619        boolean causeUpgrade = isUpgrade();
9620
9621        // First boot or factory reset.
9622        // Note: we also handle devices that are upgrading to N right now as if it is their
9623        //       first boot, as they do not have profile data.
9624        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9625
9626        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9627        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9628
9629        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9630            return;
9631        }
9632
9633        List<PackageParser.Package> pkgs;
9634        synchronized (mPackages) {
9635            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9636        }
9637
9638        final long startTime = System.nanoTime();
9639        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9640                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9641                    false /* bootComplete */);
9642
9643        final int elapsedTimeSeconds =
9644                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9645
9646        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9647        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9648        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9649        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9650        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9651    }
9652
9653    /*
9654     * Return the prebuilt profile path given a package base code path.
9655     */
9656    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9657        return pkg.baseCodePath + ".prof";
9658    }
9659
9660    /**
9661     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9662     * containing statistics about the invocation. The array consists of three elements,
9663     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9664     * and {@code numberOfPackagesFailed}.
9665     */
9666    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9667            String compilerFilter, boolean bootComplete) {
9668
9669        int numberOfPackagesVisited = 0;
9670        int numberOfPackagesOptimized = 0;
9671        int numberOfPackagesSkipped = 0;
9672        int numberOfPackagesFailed = 0;
9673        final int numberOfPackagesToDexopt = pkgs.size();
9674
9675        for (PackageParser.Package pkg : pkgs) {
9676            numberOfPackagesVisited++;
9677
9678            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9679                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9680                // that are already compiled.
9681                File profileFile = new File(getPrebuildProfilePath(pkg));
9682                // Copy profile if it exists.
9683                if (profileFile.exists()) {
9684                    try {
9685                        // We could also do this lazily before calling dexopt in
9686                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9687                        // is that we don't have a good way to say "do this only once".
9688                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9689                                pkg.applicationInfo.uid, pkg.packageName)) {
9690                            Log.e(TAG, "Installer failed to copy system profile!");
9691                        }
9692                    } catch (Exception e) {
9693                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9694                                e);
9695                    }
9696                }
9697            }
9698
9699            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9700                if (DEBUG_DEXOPT) {
9701                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9702                }
9703                numberOfPackagesSkipped++;
9704                continue;
9705            }
9706
9707            if (DEBUG_DEXOPT) {
9708                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9709                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9710            }
9711
9712            if (showDialog) {
9713                try {
9714                    ActivityManager.getService().showBootMessage(
9715                            mContext.getResources().getString(R.string.android_upgrading_apk,
9716                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9717                } catch (RemoteException e) {
9718                }
9719                synchronized (mPackages) {
9720                    mDexOptDialogShown = true;
9721                }
9722            }
9723
9724            // If the OTA updates a system app which was previously preopted to a non-preopted state
9725            // the app might end up being verified at runtime. That's because by default the apps
9726            // are verify-profile but for preopted apps there's no profile.
9727            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9728            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9729            // filter (by default 'quicken').
9730            // Note that at this stage unused apps are already filtered.
9731            if (isSystemApp(pkg) &&
9732                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9733                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9734                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9735            }
9736
9737            // checkProfiles is false to avoid merging profiles during boot which
9738            // might interfere with background compilation (b/28612421).
9739            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9740            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9741            // trade-off worth doing to save boot time work.
9742            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9743            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9744                    pkg.packageName,
9745                    compilerFilter,
9746                    dexoptFlags));
9747
9748            if (pkg.isSystemApp()) {
9749                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9750                // too much boot after an OTA.
9751                int secondaryDexoptFlags = dexoptFlags |
9752                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9753                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9754                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9755                        pkg.packageName,
9756                        compilerFilter,
9757                        secondaryDexoptFlags));
9758            }
9759
9760            // TODO(shubhamajmera): Record secondary dexopt stats.
9761            switch (primaryDexOptStaus) {
9762                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9763                    numberOfPackagesOptimized++;
9764                    break;
9765                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9766                    numberOfPackagesSkipped++;
9767                    break;
9768                case PackageDexOptimizer.DEX_OPT_FAILED:
9769                    numberOfPackagesFailed++;
9770                    break;
9771                default:
9772                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9773                    break;
9774            }
9775        }
9776
9777        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9778                numberOfPackagesFailed };
9779    }
9780
9781    @Override
9782    public void notifyPackageUse(String packageName, int reason) {
9783        synchronized (mPackages) {
9784            final int callingUid = Binder.getCallingUid();
9785            final int callingUserId = UserHandle.getUserId(callingUid);
9786            if (getInstantAppPackageName(callingUid) != null) {
9787                if (!isCallerSameApp(packageName, callingUid)) {
9788                    return;
9789                }
9790            } else {
9791                if (isInstantApp(packageName, callingUserId)) {
9792                    return;
9793                }
9794            }
9795            final PackageParser.Package p = mPackages.get(packageName);
9796            if (p == null) {
9797                return;
9798            }
9799            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9800        }
9801    }
9802
9803    @Override
9804    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9805            List<String> classPaths, String loaderIsa) {
9806        int userId = UserHandle.getCallingUserId();
9807        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9808        if (ai == null) {
9809            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9810                + loadingPackageName + ", user=" + userId);
9811            return;
9812        }
9813        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9814    }
9815
9816    @Override
9817    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9818            IDexModuleRegisterCallback callback) {
9819        int userId = UserHandle.getCallingUserId();
9820        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9821        DexManager.RegisterDexModuleResult result;
9822        if (ai == null) {
9823            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9824                     " calling user. package=" + packageName + ", user=" + userId);
9825            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9826        } else {
9827            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9828        }
9829
9830        if (callback != null) {
9831            mHandler.post(() -> {
9832                try {
9833                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9834                } catch (RemoteException e) {
9835                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9836                }
9837            });
9838        }
9839    }
9840
9841    /**
9842     * Ask the package manager to perform a dex-opt with the given compiler filter.
9843     *
9844     * Note: exposed only for the shell command to allow moving packages explicitly to a
9845     *       definite state.
9846     */
9847    @Override
9848    public boolean performDexOptMode(String packageName,
9849            boolean checkProfiles, String targetCompilerFilter, boolean force,
9850            boolean bootComplete, String splitName) {
9851        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9852                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9853                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9854        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9855                splitName, flags));
9856    }
9857
9858    /**
9859     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9860     * secondary dex files belonging to the given package.
9861     *
9862     * Note: exposed only for the shell command to allow moving packages explicitly to a
9863     *       definite state.
9864     */
9865    @Override
9866    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9867            boolean force) {
9868        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9869                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9870                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9871                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9872        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9873    }
9874
9875    /*package*/ boolean performDexOpt(DexoptOptions options) {
9876        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9877            return false;
9878        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9879            return false;
9880        }
9881
9882        if (options.isDexoptOnlySecondaryDex()) {
9883            return mDexManager.dexoptSecondaryDex(options);
9884        } else {
9885            int dexoptStatus = performDexOptWithStatus(options);
9886            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9887        }
9888    }
9889
9890    /**
9891     * Perform dexopt on the given package and return one of following result:
9892     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9893     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9894     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9895     */
9896    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9897        return performDexOptTraced(options);
9898    }
9899
9900    private int performDexOptTraced(DexoptOptions options) {
9901        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9902        try {
9903            return performDexOptInternal(options);
9904        } finally {
9905            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9906        }
9907    }
9908
9909    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9910    // if the package can now be considered up to date for the given filter.
9911    private int performDexOptInternal(DexoptOptions options) {
9912        PackageParser.Package p;
9913        synchronized (mPackages) {
9914            p = mPackages.get(options.getPackageName());
9915            if (p == null) {
9916                // Package could not be found. Report failure.
9917                return PackageDexOptimizer.DEX_OPT_FAILED;
9918            }
9919            mPackageUsage.maybeWriteAsync(mPackages);
9920            mCompilerStats.maybeWriteAsync();
9921        }
9922        long callingId = Binder.clearCallingIdentity();
9923        try {
9924            synchronized (mInstallLock) {
9925                return performDexOptInternalWithDependenciesLI(p, options);
9926            }
9927        } finally {
9928            Binder.restoreCallingIdentity(callingId);
9929        }
9930    }
9931
9932    public ArraySet<String> getOptimizablePackages() {
9933        ArraySet<String> pkgs = new ArraySet<String>();
9934        synchronized (mPackages) {
9935            for (PackageParser.Package p : mPackages.values()) {
9936                if (PackageDexOptimizer.canOptimizePackage(p)) {
9937                    pkgs.add(p.packageName);
9938                }
9939            }
9940        }
9941        return pkgs;
9942    }
9943
9944    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9945            DexoptOptions options) {
9946        // Select the dex optimizer based on the force parameter.
9947        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9948        //       allocate an object here.
9949        PackageDexOptimizer pdo = options.isForce()
9950                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9951                : mPackageDexOptimizer;
9952
9953        // Dexopt all dependencies first. Note: we ignore the return value and march on
9954        // on errors.
9955        // Note that we are going to call performDexOpt on those libraries as many times as
9956        // they are referenced in packages. When we do a batch of performDexOpt (for example
9957        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9958        // and the first package that uses the library will dexopt it. The
9959        // others will see that the compiled code for the library is up to date.
9960        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9961        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9962        if (!deps.isEmpty()) {
9963            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9964                    options.getCompilerFilter(), options.getSplitName(),
9965                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9966            for (PackageParser.Package depPackage : deps) {
9967                // TODO: Analyze and investigate if we (should) profile libraries.
9968                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9969                        getOrCreateCompilerPackageStats(depPackage),
9970                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9971            }
9972        }
9973        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9974                getOrCreateCompilerPackageStats(p),
9975                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9976    }
9977
9978    /**
9979     * Reconcile the information we have about the secondary dex files belonging to
9980     * {@code packagName} and the actual dex files. For all dex files that were
9981     * deleted, update the internal records and delete the generated oat files.
9982     */
9983    @Override
9984    public void reconcileSecondaryDexFiles(String packageName) {
9985        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9986            return;
9987        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9988            return;
9989        }
9990        mDexManager.reconcileSecondaryDexFiles(packageName);
9991    }
9992
9993    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9994    // a reference there.
9995    /*package*/ DexManager getDexManager() {
9996        return mDexManager;
9997    }
9998
9999    /**
10000     * Execute the background dexopt job immediately.
10001     */
10002    @Override
10003    public boolean runBackgroundDexoptJob() {
10004        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10005            return false;
10006        }
10007        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
10008    }
10009
10010    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
10011        if (p.usesLibraries != null || p.usesOptionalLibraries != null
10012                || p.usesStaticLibraries != null) {
10013            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
10014            Set<String> collectedNames = new HashSet<>();
10015            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
10016
10017            retValue.remove(p);
10018
10019            return retValue;
10020        } else {
10021            return Collections.emptyList();
10022        }
10023    }
10024
10025    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
10026            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10027        if (!collectedNames.contains(p.packageName)) {
10028            collectedNames.add(p.packageName);
10029            collected.add(p);
10030
10031            if (p.usesLibraries != null) {
10032                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10033                        null, collected, collectedNames);
10034            }
10035            if (p.usesOptionalLibraries != null) {
10036                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10037                        null, collected, collectedNames);
10038            }
10039            if (p.usesStaticLibraries != null) {
10040                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10041                        p.usesStaticLibrariesVersions, collected, collectedNames);
10042            }
10043        }
10044    }
10045
10046    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10047            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10048        final int libNameCount = libs.size();
10049        for (int i = 0; i < libNameCount; i++) {
10050            String libName = libs.get(i);
10051            int version = (versions != null && versions.length == libNameCount)
10052                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10053            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10054            if (libPkg != null) {
10055                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10056            }
10057        }
10058    }
10059
10060    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10061        synchronized (mPackages) {
10062            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10063            if (libEntry != null) {
10064                return mPackages.get(libEntry.apk);
10065            }
10066            return null;
10067        }
10068    }
10069
10070    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10071        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10072        if (versionedLib == null) {
10073            return null;
10074        }
10075        return versionedLib.get(version);
10076    }
10077
10078    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10079        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10080                pkg.staticSharedLibName);
10081        if (versionedLib == null) {
10082            return null;
10083        }
10084        int previousLibVersion = -1;
10085        final int versionCount = versionedLib.size();
10086        for (int i = 0; i < versionCount; i++) {
10087            final int libVersion = versionedLib.keyAt(i);
10088            if (libVersion < pkg.staticSharedLibVersion) {
10089                previousLibVersion = Math.max(previousLibVersion, libVersion);
10090            }
10091        }
10092        if (previousLibVersion >= 0) {
10093            return versionedLib.get(previousLibVersion);
10094        }
10095        return null;
10096    }
10097
10098    public void shutdown() {
10099        mPackageUsage.writeNow(mPackages);
10100        mCompilerStats.writeNow();
10101        mDexManager.writePackageDexUsageNow();
10102    }
10103
10104    @Override
10105    public void dumpProfiles(String packageName) {
10106        PackageParser.Package pkg;
10107        synchronized (mPackages) {
10108            pkg = mPackages.get(packageName);
10109            if (pkg == null) {
10110                throw new IllegalArgumentException("Unknown package: " + packageName);
10111            }
10112        }
10113        /* Only the shell, root, or the app user should be able to dump profiles. */
10114        int callingUid = Binder.getCallingUid();
10115        if (callingUid != Process.SHELL_UID &&
10116            callingUid != Process.ROOT_UID &&
10117            callingUid != pkg.applicationInfo.uid) {
10118            throw new SecurityException("dumpProfiles");
10119        }
10120
10121        synchronized (mInstallLock) {
10122            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10123            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10124            try {
10125                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10126                String codePaths = TextUtils.join(";", allCodePaths);
10127                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10128            } catch (InstallerException e) {
10129                Slog.w(TAG, "Failed to dump profiles", e);
10130            }
10131            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10132        }
10133    }
10134
10135    @Override
10136    public void forceDexOpt(String packageName) {
10137        enforceSystemOrRoot("forceDexOpt");
10138
10139        PackageParser.Package pkg;
10140        synchronized (mPackages) {
10141            pkg = mPackages.get(packageName);
10142            if (pkg == null) {
10143                throw new IllegalArgumentException("Unknown package: " + packageName);
10144            }
10145        }
10146
10147        synchronized (mInstallLock) {
10148            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10149
10150            // Whoever is calling forceDexOpt wants a compiled package.
10151            // Don't use profiles since that may cause compilation to be skipped.
10152            final int res = performDexOptInternalWithDependenciesLI(
10153                    pkg,
10154                    new DexoptOptions(packageName,
10155                            getDefaultCompilerFilter(),
10156                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10157
10158            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10159            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10160                throw new IllegalStateException("Failed to dexopt: " + res);
10161            }
10162        }
10163    }
10164
10165    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10166        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10167            Slog.w(TAG, "Unable to update from " + oldPkg.name
10168                    + " to " + newPkg.packageName
10169                    + ": old package not in system partition");
10170            return false;
10171        } else if (mPackages.get(oldPkg.name) != null) {
10172            Slog.w(TAG, "Unable to update from " + oldPkg.name
10173                    + " to " + newPkg.packageName
10174                    + ": old package still exists");
10175            return false;
10176        }
10177        return true;
10178    }
10179
10180    void removeCodePathLI(File codePath) {
10181        if (codePath.isDirectory()) {
10182            try {
10183                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10184            } catch (InstallerException e) {
10185                Slog.w(TAG, "Failed to remove code path", e);
10186            }
10187        } else {
10188            codePath.delete();
10189        }
10190    }
10191
10192    private int[] resolveUserIds(int userId) {
10193        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10194    }
10195
10196    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10197        if (pkg == null) {
10198            Slog.wtf(TAG, "Package was null!", new Throwable());
10199            return;
10200        }
10201        clearAppDataLeafLIF(pkg, userId, flags);
10202        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10203        for (int i = 0; i < childCount; i++) {
10204            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10205        }
10206    }
10207
10208    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10209        final PackageSetting ps;
10210        synchronized (mPackages) {
10211            ps = mSettings.mPackages.get(pkg.packageName);
10212        }
10213        for (int realUserId : resolveUserIds(userId)) {
10214            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10215            try {
10216                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10217                        ceDataInode);
10218            } catch (InstallerException e) {
10219                Slog.w(TAG, String.valueOf(e));
10220            }
10221        }
10222    }
10223
10224    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10225        if (pkg == null) {
10226            Slog.wtf(TAG, "Package was null!", new Throwable());
10227            return;
10228        }
10229        destroyAppDataLeafLIF(pkg, userId, flags);
10230        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10231        for (int i = 0; i < childCount; i++) {
10232            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10233        }
10234    }
10235
10236    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10237        final PackageSetting ps;
10238        synchronized (mPackages) {
10239            ps = mSettings.mPackages.get(pkg.packageName);
10240        }
10241        for (int realUserId : resolveUserIds(userId)) {
10242            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10243            try {
10244                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10245                        ceDataInode);
10246            } catch (InstallerException e) {
10247                Slog.w(TAG, String.valueOf(e));
10248            }
10249            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10250        }
10251    }
10252
10253    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10254        if (pkg == null) {
10255            Slog.wtf(TAG, "Package was null!", new Throwable());
10256            return;
10257        }
10258        destroyAppProfilesLeafLIF(pkg);
10259        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10260        for (int i = 0; i < childCount; i++) {
10261            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10262        }
10263    }
10264
10265    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10266        try {
10267            mInstaller.destroyAppProfiles(pkg.packageName);
10268        } catch (InstallerException e) {
10269            Slog.w(TAG, String.valueOf(e));
10270        }
10271    }
10272
10273    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10274        if (pkg == null) {
10275            Slog.wtf(TAG, "Package was null!", new Throwable());
10276            return;
10277        }
10278        clearAppProfilesLeafLIF(pkg);
10279        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10280        for (int i = 0; i < childCount; i++) {
10281            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10282        }
10283    }
10284
10285    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10286        try {
10287            mInstaller.clearAppProfiles(pkg.packageName);
10288        } catch (InstallerException e) {
10289            Slog.w(TAG, String.valueOf(e));
10290        }
10291    }
10292
10293    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10294            long lastUpdateTime) {
10295        // Set parent install/update time
10296        PackageSetting ps = (PackageSetting) pkg.mExtras;
10297        if (ps != null) {
10298            ps.firstInstallTime = firstInstallTime;
10299            ps.lastUpdateTime = lastUpdateTime;
10300        }
10301        // Set children install/update time
10302        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10303        for (int i = 0; i < childCount; i++) {
10304            PackageParser.Package childPkg = pkg.childPackages.get(i);
10305            ps = (PackageSetting) childPkg.mExtras;
10306            if (ps != null) {
10307                ps.firstInstallTime = firstInstallTime;
10308                ps.lastUpdateTime = lastUpdateTime;
10309            }
10310        }
10311    }
10312
10313    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10314            PackageParser.Package changingLib) {
10315        if (file.path != null) {
10316            usesLibraryFiles.add(file.path);
10317            return;
10318        }
10319        PackageParser.Package p = mPackages.get(file.apk);
10320        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10321            // If we are doing this while in the middle of updating a library apk,
10322            // then we need to make sure to use that new apk for determining the
10323            // dependencies here.  (We haven't yet finished committing the new apk
10324            // to the package manager state.)
10325            if (p == null || p.packageName.equals(changingLib.packageName)) {
10326                p = changingLib;
10327            }
10328        }
10329        if (p != null) {
10330            usesLibraryFiles.addAll(p.getAllCodePaths());
10331            if (p.usesLibraryFiles != null) {
10332                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10333            }
10334        }
10335    }
10336
10337    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10338            PackageParser.Package changingLib) throws PackageManagerException {
10339        if (pkg == null) {
10340            return;
10341        }
10342        ArraySet<String> usesLibraryFiles = null;
10343        if (pkg.usesLibraries != null) {
10344            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10345                    null, null, pkg.packageName, changingLib, true, null);
10346        }
10347        if (pkg.usesStaticLibraries != null) {
10348            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10349                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10350                    pkg.packageName, changingLib, true, usesLibraryFiles);
10351        }
10352        if (pkg.usesOptionalLibraries != null) {
10353            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10354                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10355        }
10356        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10357            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10358        } else {
10359            pkg.usesLibraryFiles = null;
10360        }
10361    }
10362
10363    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10364            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10365            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10366            boolean required, @Nullable ArraySet<String> outUsedLibraries)
10367            throws PackageManagerException {
10368        final int libCount = requestedLibraries.size();
10369        for (int i = 0; i < libCount; i++) {
10370            final String libName = requestedLibraries.get(i);
10371            final int libVersion = requiredVersions != null ? requiredVersions[i]
10372                    : SharedLibraryInfo.VERSION_UNDEFINED;
10373            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10374            if (libEntry == null) {
10375                if (required) {
10376                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10377                            "Package " + packageName + " requires unavailable shared library "
10378                                    + libName + "; failing!");
10379                } else if (DEBUG_SHARED_LIBRARIES) {
10380                    Slog.i(TAG, "Package " + packageName
10381                            + " desires unavailable shared library "
10382                            + libName + "; ignoring!");
10383                }
10384            } else {
10385                if (requiredVersions != null && requiredCertDigests != null) {
10386                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10387                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10388                            "Package " + packageName + " requires unavailable static shared"
10389                                    + " library " + libName + " version "
10390                                    + libEntry.info.getVersion() + "; failing!");
10391                    }
10392
10393                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10394                    if (libPkg == null) {
10395                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10396                                "Package " + packageName + " requires unavailable static shared"
10397                                        + " library; failing!");
10398                    }
10399
10400                    String expectedCertDigest = requiredCertDigests[i];
10401                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10402                                libPkg.mSignatures[0]);
10403                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10404                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10405                                "Package " + packageName + " requires differently signed" +
10406                                        " static shared library; failing!");
10407                    }
10408                }
10409
10410                if (outUsedLibraries == null) {
10411                    outUsedLibraries = new ArraySet<>();
10412                }
10413                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10414            }
10415        }
10416        return outUsedLibraries;
10417    }
10418
10419    private static boolean hasString(List<String> list, List<String> which) {
10420        if (list == null) {
10421            return false;
10422        }
10423        for (int i=list.size()-1; i>=0; i--) {
10424            for (int j=which.size()-1; j>=0; j--) {
10425                if (which.get(j).equals(list.get(i))) {
10426                    return true;
10427                }
10428            }
10429        }
10430        return false;
10431    }
10432
10433    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10434            PackageParser.Package changingPkg) {
10435        ArrayList<PackageParser.Package> res = null;
10436        for (PackageParser.Package pkg : mPackages.values()) {
10437            if (changingPkg != null
10438                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10439                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10440                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10441                            changingPkg.staticSharedLibName)) {
10442                return null;
10443            }
10444            if (res == null) {
10445                res = new ArrayList<>();
10446            }
10447            res.add(pkg);
10448            try {
10449                updateSharedLibrariesLPr(pkg, changingPkg);
10450            } catch (PackageManagerException e) {
10451                // If a system app update or an app and a required lib missing we
10452                // delete the package and for updated system apps keep the data as
10453                // it is better for the user to reinstall than to be in an limbo
10454                // state. Also libs disappearing under an app should never happen
10455                // - just in case.
10456                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10457                    final int flags = pkg.isUpdatedSystemApp()
10458                            ? PackageManager.DELETE_KEEP_DATA : 0;
10459                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10460                            flags , null, true, null);
10461                }
10462                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10463            }
10464        }
10465        return res;
10466    }
10467
10468    /**
10469     * Derive the value of the {@code cpuAbiOverride} based on the provided
10470     * value and an optional stored value from the package settings.
10471     */
10472    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10473        String cpuAbiOverride = null;
10474
10475        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10476            cpuAbiOverride = null;
10477        } else if (abiOverride != null) {
10478            cpuAbiOverride = abiOverride;
10479        } else if (settings != null) {
10480            cpuAbiOverride = settings.cpuAbiOverrideString;
10481        }
10482
10483        return cpuAbiOverride;
10484    }
10485
10486    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10487            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10488                    throws PackageManagerException {
10489        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10490        // If the package has children and this is the first dive in the function
10491        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10492        // whether all packages (parent and children) would be successfully scanned
10493        // before the actual scan since scanning mutates internal state and we want
10494        // to atomically install the package and its children.
10495        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10496            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10497                scanFlags |= SCAN_CHECK_ONLY;
10498            }
10499        } else {
10500            scanFlags &= ~SCAN_CHECK_ONLY;
10501        }
10502
10503        final PackageParser.Package scannedPkg;
10504        try {
10505            // Scan the parent
10506            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10507            // Scan the children
10508            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10509            for (int i = 0; i < childCount; i++) {
10510                PackageParser.Package childPkg = pkg.childPackages.get(i);
10511                scanPackageLI(childPkg, policyFlags,
10512                        scanFlags, currentTime, user);
10513            }
10514        } finally {
10515            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10516        }
10517
10518        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10519            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10520        }
10521
10522        return scannedPkg;
10523    }
10524
10525    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10526            int scanFlags, long currentTime, @Nullable UserHandle user)
10527                    throws PackageManagerException {
10528        boolean success = false;
10529        try {
10530            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10531                    currentTime, user);
10532            success = true;
10533            return res;
10534        } finally {
10535            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10536                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10537                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10538                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10539                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10540            }
10541        }
10542    }
10543
10544    /**
10545     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10546     */
10547    private static boolean apkHasCode(String fileName) {
10548        StrictJarFile jarFile = null;
10549        try {
10550            jarFile = new StrictJarFile(fileName,
10551                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10552            return jarFile.findEntry("classes.dex") != null;
10553        } catch (IOException ignore) {
10554        } finally {
10555            try {
10556                if (jarFile != null) {
10557                    jarFile.close();
10558                }
10559            } catch (IOException ignore) {}
10560        }
10561        return false;
10562    }
10563
10564    /**
10565     * Enforces code policy for the package. This ensures that if an APK has
10566     * declared hasCode="true" in its manifest that the APK actually contains
10567     * code.
10568     *
10569     * @throws PackageManagerException If bytecode could not be found when it should exist
10570     */
10571    private static void assertCodePolicy(PackageParser.Package pkg)
10572            throws PackageManagerException {
10573        final boolean shouldHaveCode =
10574                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10575        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10576            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10577                    "Package " + pkg.baseCodePath + " code is missing");
10578        }
10579
10580        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10581            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10582                final boolean splitShouldHaveCode =
10583                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10584                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10585                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10586                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10587                }
10588            }
10589        }
10590    }
10591
10592    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10593            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10594                    throws PackageManagerException {
10595        if (DEBUG_PACKAGE_SCANNING) {
10596            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10597                Log.d(TAG, "Scanning package " + pkg.packageName);
10598        }
10599
10600        applyPolicy(pkg, policyFlags);
10601
10602        assertPackageIsValid(pkg, policyFlags, scanFlags);
10603
10604        // Initialize package source and resource directories
10605        final File scanFile = new File(pkg.codePath);
10606        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10607        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10608
10609        SharedUserSetting suid = null;
10610        PackageSetting pkgSetting = null;
10611
10612        // Getting the package setting may have a side-effect, so if we
10613        // are only checking if scan would succeed, stash a copy of the
10614        // old setting to restore at the end.
10615        PackageSetting nonMutatedPs = null;
10616
10617        // We keep references to the derived CPU Abis from settings in oder to reuse
10618        // them in the case where we're not upgrading or booting for the first time.
10619        String primaryCpuAbiFromSettings = null;
10620        String secondaryCpuAbiFromSettings = null;
10621
10622        // writer
10623        synchronized (mPackages) {
10624            if (pkg.mSharedUserId != null) {
10625                // SIDE EFFECTS; may potentially allocate a new shared user
10626                suid = mSettings.getSharedUserLPw(
10627                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10628                if (DEBUG_PACKAGE_SCANNING) {
10629                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10630                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10631                                + "): packages=" + suid.packages);
10632                }
10633            }
10634
10635            // Check if we are renaming from an original package name.
10636            PackageSetting origPackage = null;
10637            String realName = null;
10638            if (pkg.mOriginalPackages != null) {
10639                // This package may need to be renamed to a previously
10640                // installed name.  Let's check on that...
10641                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10642                if (pkg.mOriginalPackages.contains(renamed)) {
10643                    // This package had originally been installed as the
10644                    // original name, and we have already taken care of
10645                    // transitioning to the new one.  Just update the new
10646                    // one to continue using the old name.
10647                    realName = pkg.mRealPackage;
10648                    if (!pkg.packageName.equals(renamed)) {
10649                        // Callers into this function may have already taken
10650                        // care of renaming the package; only do it here if
10651                        // it is not already done.
10652                        pkg.setPackageName(renamed);
10653                    }
10654                } else {
10655                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10656                        if ((origPackage = mSettings.getPackageLPr(
10657                                pkg.mOriginalPackages.get(i))) != null) {
10658                            // We do have the package already installed under its
10659                            // original name...  should we use it?
10660                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10661                                // New package is not compatible with original.
10662                                origPackage = null;
10663                                continue;
10664                            } else if (origPackage.sharedUser != null) {
10665                                // Make sure uid is compatible between packages.
10666                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10667                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10668                                            + " to " + pkg.packageName + ": old uid "
10669                                            + origPackage.sharedUser.name
10670                                            + " differs from " + pkg.mSharedUserId);
10671                                    origPackage = null;
10672                                    continue;
10673                                }
10674                                // TODO: Add case when shared user id is added [b/28144775]
10675                            } else {
10676                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10677                                        + pkg.packageName + " to old name " + origPackage.name);
10678                            }
10679                            break;
10680                        }
10681                    }
10682                }
10683            }
10684
10685            if (mTransferedPackages.contains(pkg.packageName)) {
10686                Slog.w(TAG, "Package " + pkg.packageName
10687                        + " was transferred to another, but its .apk remains");
10688            }
10689
10690            // See comments in nonMutatedPs declaration
10691            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10692                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10693                if (foundPs != null) {
10694                    nonMutatedPs = new PackageSetting(foundPs);
10695                }
10696            }
10697
10698            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10699                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10700                if (foundPs != null) {
10701                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10702                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10703                }
10704            }
10705
10706            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10707            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10708                PackageManagerService.reportSettingsProblem(Log.WARN,
10709                        "Package " + pkg.packageName + " shared user changed from "
10710                                + (pkgSetting.sharedUser != null
10711                                        ? pkgSetting.sharedUser.name : "<nothing>")
10712                                + " to "
10713                                + (suid != null ? suid.name : "<nothing>")
10714                                + "; replacing with new");
10715                pkgSetting = null;
10716            }
10717            final PackageSetting oldPkgSetting =
10718                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10719            final PackageSetting disabledPkgSetting =
10720                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10721
10722            String[] usesStaticLibraries = null;
10723            if (pkg.usesStaticLibraries != null) {
10724                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10725                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10726            }
10727
10728            if (pkgSetting == null) {
10729                final String parentPackageName = (pkg.parentPackage != null)
10730                        ? pkg.parentPackage.packageName : null;
10731                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10732                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10733                // REMOVE SharedUserSetting from method; update in a separate call
10734                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10735                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10736                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10737                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10738                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10739                        true /*allowInstall*/, instantApp, virtualPreload,
10740                        parentPackageName, pkg.getChildPackageNames(),
10741                        UserManagerService.getInstance(), usesStaticLibraries,
10742                        pkg.usesStaticLibrariesVersions);
10743                // SIDE EFFECTS; updates system state; move elsewhere
10744                if (origPackage != null) {
10745                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10746                }
10747                mSettings.addUserToSettingLPw(pkgSetting);
10748            } else {
10749                // REMOVE SharedUserSetting from method; update in a separate call.
10750                //
10751                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10752                // secondaryCpuAbi are not known at this point so we always update them
10753                // to null here, only to reset them at a later point.
10754                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10755                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10756                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10757                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10758                        UserManagerService.getInstance(), usesStaticLibraries,
10759                        pkg.usesStaticLibrariesVersions);
10760            }
10761            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10762            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10763
10764            // SIDE EFFECTS; modifies system state; move elsewhere
10765            if (pkgSetting.origPackage != null) {
10766                // If we are first transitioning from an original package,
10767                // fix up the new package's name now.  We need to do this after
10768                // looking up the package under its new name, so getPackageLP
10769                // can take care of fiddling things correctly.
10770                pkg.setPackageName(origPackage.name);
10771
10772                // File a report about this.
10773                String msg = "New package " + pkgSetting.realName
10774                        + " renamed to replace old package " + pkgSetting.name;
10775                reportSettingsProblem(Log.WARN, msg);
10776
10777                // Make a note of it.
10778                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10779                    mTransferedPackages.add(origPackage.name);
10780                }
10781
10782                // No longer need to retain this.
10783                pkgSetting.origPackage = null;
10784            }
10785
10786            // SIDE EFFECTS; modifies system state; move elsewhere
10787            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10788                // Make a note of it.
10789                mTransferedPackages.add(pkg.packageName);
10790            }
10791
10792            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10793                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10794            }
10795
10796            if ((scanFlags & SCAN_BOOTING) == 0
10797                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10798                // Check all shared libraries and map to their actual file path.
10799                // We only do this here for apps not on a system dir, because those
10800                // are the only ones that can fail an install due to this.  We
10801                // will take care of the system apps by updating all of their
10802                // library paths after the scan is done. Also during the initial
10803                // scan don't update any libs as we do this wholesale after all
10804                // apps are scanned to avoid dependency based scanning.
10805                updateSharedLibrariesLPr(pkg, null);
10806            }
10807
10808            if (mFoundPolicyFile) {
10809                SELinuxMMAC.assignSeInfoValue(pkg);
10810            }
10811            pkg.applicationInfo.uid = pkgSetting.appId;
10812            pkg.mExtras = pkgSetting;
10813
10814
10815            // Static shared libs have same package with different versions where
10816            // we internally use a synthetic package name to allow multiple versions
10817            // of the same package, therefore we need to compare signatures against
10818            // the package setting for the latest library version.
10819            PackageSetting signatureCheckPs = pkgSetting;
10820            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10821                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10822                if (libraryEntry != null) {
10823                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10824                }
10825            }
10826
10827            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10828                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10829                    // We just determined the app is signed correctly, so bring
10830                    // over the latest parsed certs.
10831                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10832                } else {
10833                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10834                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10835                                "Package " + pkg.packageName + " upgrade keys do not match the "
10836                                + "previously installed version");
10837                    } else {
10838                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10839                        String msg = "System package " + pkg.packageName
10840                                + " signature changed; retaining data.";
10841                        reportSettingsProblem(Log.WARN, msg);
10842                    }
10843                }
10844            } else {
10845                try {
10846                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10847                    verifySignaturesLP(signatureCheckPs, pkg);
10848                    // We just determined the app is signed correctly, so bring
10849                    // over the latest parsed certs.
10850                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10851                } catch (PackageManagerException e) {
10852                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10853                        throw e;
10854                    }
10855                    // The signature has changed, but this package is in the system
10856                    // image...  let's recover!
10857                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10858                    // However...  if this package is part of a shared user, but it
10859                    // doesn't match the signature of the shared user, let's fail.
10860                    // What this means is that you can't change the signatures
10861                    // associated with an overall shared user, which doesn't seem all
10862                    // that unreasonable.
10863                    if (signatureCheckPs.sharedUser != null) {
10864                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10865                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10866                            throw new PackageManagerException(
10867                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10868                                    "Signature mismatch for shared user: "
10869                                            + pkgSetting.sharedUser);
10870                        }
10871                    }
10872                    // File a report about this.
10873                    String msg = "System package " + pkg.packageName
10874                            + " signature changed; retaining data.";
10875                    reportSettingsProblem(Log.WARN, msg);
10876                }
10877            }
10878
10879            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10880                // This package wants to adopt ownership of permissions from
10881                // another package.
10882                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10883                    final String origName = pkg.mAdoptPermissions.get(i);
10884                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10885                    if (orig != null) {
10886                        if (verifyPackageUpdateLPr(orig, pkg)) {
10887                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10888                                    + pkg.packageName);
10889                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10890                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10891                        }
10892                    }
10893                }
10894            }
10895        }
10896
10897        pkg.applicationInfo.processName = fixProcessName(
10898                pkg.applicationInfo.packageName,
10899                pkg.applicationInfo.processName);
10900
10901        if (pkg != mPlatformPackage) {
10902            // Get all of our default paths setup
10903            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10904        }
10905
10906        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10907
10908        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10909            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10910                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10911                final boolean extractNativeLibs = !pkg.isLibrary();
10912                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10913                        mAppLib32InstallDir);
10914                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10915
10916                // Some system apps still use directory structure for native libraries
10917                // in which case we might end up not detecting abi solely based on apk
10918                // structure. Try to detect abi based on directory structure.
10919                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10920                        pkg.applicationInfo.primaryCpuAbi == null) {
10921                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10922                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10923                }
10924            } else {
10925                // This is not a first boot or an upgrade, don't bother deriving the
10926                // ABI during the scan. Instead, trust the value that was stored in the
10927                // package setting.
10928                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10929                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10930
10931                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10932
10933                if (DEBUG_ABI_SELECTION) {
10934                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10935                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10936                        pkg.applicationInfo.secondaryCpuAbi);
10937                }
10938            }
10939        } else {
10940            if ((scanFlags & SCAN_MOVE) != 0) {
10941                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10942                // but we already have this packages package info in the PackageSetting. We just
10943                // use that and derive the native library path based on the new codepath.
10944                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10945                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10946            }
10947
10948            // Set native library paths again. For moves, the path will be updated based on the
10949            // ABIs we've determined above. For non-moves, the path will be updated based on the
10950            // ABIs we determined during compilation, but the path will depend on the final
10951            // package path (after the rename away from the stage path).
10952            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10953        }
10954
10955        // This is a special case for the "system" package, where the ABI is
10956        // dictated by the zygote configuration (and init.rc). We should keep track
10957        // of this ABI so that we can deal with "normal" applications that run under
10958        // the same UID correctly.
10959        if (mPlatformPackage == pkg) {
10960            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10961                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10962        }
10963
10964        // If there's a mismatch between the abi-override in the package setting
10965        // and the abiOverride specified for the install. Warn about this because we
10966        // would've already compiled the app without taking the package setting into
10967        // account.
10968        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10969            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10970                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10971                        " for package " + pkg.packageName);
10972            }
10973        }
10974
10975        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10976        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10977        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10978
10979        // Copy the derived override back to the parsed package, so that we can
10980        // update the package settings accordingly.
10981        pkg.cpuAbiOverride = cpuAbiOverride;
10982
10983        if (DEBUG_ABI_SELECTION) {
10984            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10985                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10986                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10987        }
10988
10989        // Push the derived path down into PackageSettings so we know what to
10990        // clean up at uninstall time.
10991        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10992
10993        if (DEBUG_ABI_SELECTION) {
10994            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10995                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10996                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10997        }
10998
10999        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
11000        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
11001            // We don't do this here during boot because we can do it all
11002            // at once after scanning all existing packages.
11003            //
11004            // We also do this *before* we perform dexopt on this package, so that
11005            // we can avoid redundant dexopts, and also to make sure we've got the
11006            // code and package path correct.
11007            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
11008        }
11009
11010        if (mFactoryTest && pkg.requestedPermissions.contains(
11011                android.Manifest.permission.FACTORY_TEST)) {
11012            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
11013        }
11014
11015        if (isSystemApp(pkg)) {
11016            pkgSetting.isOrphaned = true;
11017        }
11018
11019        // Take care of first install / last update times.
11020        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
11021        if (currentTime != 0) {
11022            if (pkgSetting.firstInstallTime == 0) {
11023                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11024            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11025                pkgSetting.lastUpdateTime = currentTime;
11026            }
11027        } else if (pkgSetting.firstInstallTime == 0) {
11028            // We need *something*.  Take time time stamp of the file.
11029            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11030        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11031            if (scanFileTime != pkgSetting.timeStamp) {
11032                // A package on the system image has changed; consider this
11033                // to be an update.
11034                pkgSetting.lastUpdateTime = scanFileTime;
11035            }
11036        }
11037        pkgSetting.setTimeStamp(scanFileTime);
11038
11039        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11040            if (nonMutatedPs != null) {
11041                synchronized (mPackages) {
11042                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11043                }
11044            }
11045        } else {
11046            final int userId = user == null ? 0 : user.getIdentifier();
11047            // Modify state for the given package setting
11048            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11049                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11050            if (pkgSetting.getInstantApp(userId)) {
11051                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11052            }
11053        }
11054        return pkg;
11055    }
11056
11057    /**
11058     * Applies policy to the parsed package based upon the given policy flags.
11059     * Ensures the package is in a good state.
11060     * <p>
11061     * Implementation detail: This method must NOT have any side effect. It would
11062     * ideally be static, but, it requires locks to read system state.
11063     */
11064    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11065        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11066            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11067            if (pkg.applicationInfo.isDirectBootAware()) {
11068                // we're direct boot aware; set for all components
11069                for (PackageParser.Service s : pkg.services) {
11070                    s.info.encryptionAware = s.info.directBootAware = true;
11071                }
11072                for (PackageParser.Provider p : pkg.providers) {
11073                    p.info.encryptionAware = p.info.directBootAware = true;
11074                }
11075                for (PackageParser.Activity a : pkg.activities) {
11076                    a.info.encryptionAware = a.info.directBootAware = true;
11077                }
11078                for (PackageParser.Activity r : pkg.receivers) {
11079                    r.info.encryptionAware = r.info.directBootAware = true;
11080                }
11081            }
11082            if (compressedFileExists(pkg.baseCodePath)) {
11083                pkg.isStub = true;
11084            }
11085        } else {
11086            // Only allow system apps to be flagged as core apps.
11087            pkg.coreApp = false;
11088            // clear flags not applicable to regular apps
11089            pkg.applicationInfo.privateFlags &=
11090                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11091            pkg.applicationInfo.privateFlags &=
11092                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11093        }
11094        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11095
11096        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11097            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11098        }
11099
11100        if (!isSystemApp(pkg)) {
11101            // Only system apps can use these features.
11102            pkg.mOriginalPackages = null;
11103            pkg.mRealPackage = null;
11104            pkg.mAdoptPermissions = null;
11105        }
11106    }
11107
11108    /**
11109     * Asserts the parsed package is valid according to the given policy. If the
11110     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11111     * <p>
11112     * Implementation detail: This method must NOT have any side effects. It would
11113     * ideally be static, but, it requires locks to read system state.
11114     *
11115     * @throws PackageManagerException If the package fails any of the validation checks
11116     */
11117    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11118            throws PackageManagerException {
11119        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11120            assertCodePolicy(pkg);
11121        }
11122
11123        if (pkg.applicationInfo.getCodePath() == null ||
11124                pkg.applicationInfo.getResourcePath() == null) {
11125            // Bail out. The resource and code paths haven't been set.
11126            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11127                    "Code and resource paths haven't been set correctly");
11128        }
11129
11130        // Make sure we're not adding any bogus keyset info
11131        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11132        ksms.assertScannedPackageValid(pkg);
11133
11134        synchronized (mPackages) {
11135            // The special "android" package can only be defined once
11136            if (pkg.packageName.equals("android")) {
11137                if (mAndroidApplication != null) {
11138                    Slog.w(TAG, "*************************************************");
11139                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11140                    Slog.w(TAG, " codePath=" + pkg.codePath);
11141                    Slog.w(TAG, "*************************************************");
11142                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11143                            "Core android package being redefined.  Skipping.");
11144                }
11145            }
11146
11147            // A package name must be unique; don't allow duplicates
11148            if (mPackages.containsKey(pkg.packageName)) {
11149                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11150                        "Application package " + pkg.packageName
11151                        + " already installed.  Skipping duplicate.");
11152            }
11153
11154            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11155                // Static libs have a synthetic package name containing the version
11156                // but we still want the base name to be unique.
11157                if (mPackages.containsKey(pkg.manifestPackageName)) {
11158                    throw new PackageManagerException(
11159                            "Duplicate static shared lib provider package");
11160                }
11161
11162                // Static shared libraries should have at least O target SDK
11163                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11164                    throw new PackageManagerException(
11165                            "Packages declaring static-shared libs must target O SDK or higher");
11166                }
11167
11168                // Package declaring static a shared lib cannot be instant apps
11169                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11170                    throw new PackageManagerException(
11171                            "Packages declaring static-shared libs cannot be instant apps");
11172                }
11173
11174                // Package declaring static a shared lib cannot be renamed since the package
11175                // name is synthetic and apps can't code around package manager internals.
11176                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11177                    throw new PackageManagerException(
11178                            "Packages declaring static-shared libs cannot be renamed");
11179                }
11180
11181                // Package declaring static a shared lib cannot declare child packages
11182                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11183                    throw new PackageManagerException(
11184                            "Packages declaring static-shared libs cannot have child packages");
11185                }
11186
11187                // Package declaring static a shared lib cannot declare dynamic libs
11188                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11189                    throw new PackageManagerException(
11190                            "Packages declaring static-shared libs cannot declare dynamic libs");
11191                }
11192
11193                // Package declaring static a shared lib cannot declare shared users
11194                if (pkg.mSharedUserId != null) {
11195                    throw new PackageManagerException(
11196                            "Packages declaring static-shared libs cannot declare shared users");
11197                }
11198
11199                // Static shared libs cannot declare activities
11200                if (!pkg.activities.isEmpty()) {
11201                    throw new PackageManagerException(
11202                            "Static shared libs cannot declare activities");
11203                }
11204
11205                // Static shared libs cannot declare services
11206                if (!pkg.services.isEmpty()) {
11207                    throw new PackageManagerException(
11208                            "Static shared libs cannot declare services");
11209                }
11210
11211                // Static shared libs cannot declare providers
11212                if (!pkg.providers.isEmpty()) {
11213                    throw new PackageManagerException(
11214                            "Static shared libs cannot declare content providers");
11215                }
11216
11217                // Static shared libs cannot declare receivers
11218                if (!pkg.receivers.isEmpty()) {
11219                    throw new PackageManagerException(
11220                            "Static shared libs cannot declare broadcast receivers");
11221                }
11222
11223                // Static shared libs cannot declare permission groups
11224                if (!pkg.permissionGroups.isEmpty()) {
11225                    throw new PackageManagerException(
11226                            "Static shared libs cannot declare permission groups");
11227                }
11228
11229                // Static shared libs cannot declare permissions
11230                if (!pkg.permissions.isEmpty()) {
11231                    throw new PackageManagerException(
11232                            "Static shared libs cannot declare permissions");
11233                }
11234
11235                // Static shared libs cannot declare protected broadcasts
11236                if (pkg.protectedBroadcasts != null) {
11237                    throw new PackageManagerException(
11238                            "Static shared libs cannot declare protected broadcasts");
11239                }
11240
11241                // Static shared libs cannot be overlay targets
11242                if (pkg.mOverlayTarget != null) {
11243                    throw new PackageManagerException(
11244                            "Static shared libs cannot be overlay targets");
11245                }
11246
11247                // The version codes must be ordered as lib versions
11248                int minVersionCode = Integer.MIN_VALUE;
11249                int maxVersionCode = Integer.MAX_VALUE;
11250
11251                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11252                        pkg.staticSharedLibName);
11253                if (versionedLib != null) {
11254                    final int versionCount = versionedLib.size();
11255                    for (int i = 0; i < versionCount; i++) {
11256                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11257                        final int libVersionCode = libInfo.getDeclaringPackage()
11258                                .getVersionCode();
11259                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11260                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11261                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11262                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11263                        } else {
11264                            minVersionCode = maxVersionCode = libVersionCode;
11265                            break;
11266                        }
11267                    }
11268                }
11269                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11270                    throw new PackageManagerException("Static shared"
11271                            + " lib version codes must be ordered as lib versions");
11272                }
11273            }
11274
11275            // Only privileged apps and updated privileged apps can add child packages.
11276            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11277                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11278                    throw new PackageManagerException("Only privileged apps can add child "
11279                            + "packages. Ignoring package " + pkg.packageName);
11280                }
11281                final int childCount = pkg.childPackages.size();
11282                for (int i = 0; i < childCount; i++) {
11283                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11284                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11285                            childPkg.packageName)) {
11286                        throw new PackageManagerException("Can't override child of "
11287                                + "another disabled app. Ignoring package " + pkg.packageName);
11288                    }
11289                }
11290            }
11291
11292            // If we're only installing presumed-existing packages, require that the
11293            // scanned APK is both already known and at the path previously established
11294            // for it.  Previously unknown packages we pick up normally, but if we have an
11295            // a priori expectation about this package's install presence, enforce it.
11296            // With a singular exception for new system packages. When an OTA contains
11297            // a new system package, we allow the codepath to change from a system location
11298            // to the user-installed location. If we don't allow this change, any newer,
11299            // user-installed version of the application will be ignored.
11300            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11301                if (mExpectingBetter.containsKey(pkg.packageName)) {
11302                    logCriticalInfo(Log.WARN,
11303                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11304                } else {
11305                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11306                    if (known != null) {
11307                        if (DEBUG_PACKAGE_SCANNING) {
11308                            Log.d(TAG, "Examining " + pkg.codePath
11309                                    + " and requiring known paths " + known.codePathString
11310                                    + " & " + known.resourcePathString);
11311                        }
11312                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11313                                || !pkg.applicationInfo.getResourcePath().equals(
11314                                        known.resourcePathString)) {
11315                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11316                                    "Application package " + pkg.packageName
11317                                    + " found at " + pkg.applicationInfo.getCodePath()
11318                                    + " but expected at " + known.codePathString
11319                                    + "; ignoring.");
11320                        }
11321                    }
11322                }
11323            }
11324
11325            // Verify that this new package doesn't have any content providers
11326            // that conflict with existing packages.  Only do this if the
11327            // package isn't already installed, since we don't want to break
11328            // things that are installed.
11329            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11330                final int N = pkg.providers.size();
11331                int i;
11332                for (i=0; i<N; i++) {
11333                    PackageParser.Provider p = pkg.providers.get(i);
11334                    if (p.info.authority != null) {
11335                        String names[] = p.info.authority.split(";");
11336                        for (int j = 0; j < names.length; j++) {
11337                            if (mProvidersByAuthority.containsKey(names[j])) {
11338                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11339                                final String otherPackageName =
11340                                        ((other != null && other.getComponentName() != null) ?
11341                                                other.getComponentName().getPackageName() : "?");
11342                                throw new PackageManagerException(
11343                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11344                                        "Can't install because provider name " + names[j]
11345                                                + " (in package " + pkg.applicationInfo.packageName
11346                                                + ") is already used by " + otherPackageName);
11347                            }
11348                        }
11349                    }
11350                }
11351            }
11352        }
11353    }
11354
11355    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11356            int type, String declaringPackageName, int declaringVersionCode) {
11357        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11358        if (versionedLib == null) {
11359            versionedLib = new SparseArray<>();
11360            mSharedLibraries.put(name, versionedLib);
11361            if (type == SharedLibraryInfo.TYPE_STATIC) {
11362                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11363            }
11364        } else if (versionedLib.indexOfKey(version) >= 0) {
11365            return false;
11366        }
11367        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11368                version, type, declaringPackageName, declaringVersionCode);
11369        versionedLib.put(version, libEntry);
11370        return true;
11371    }
11372
11373    private boolean removeSharedLibraryLPw(String name, int version) {
11374        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11375        if (versionedLib == null) {
11376            return false;
11377        }
11378        final int libIdx = versionedLib.indexOfKey(version);
11379        if (libIdx < 0) {
11380            return false;
11381        }
11382        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11383        versionedLib.remove(version);
11384        if (versionedLib.size() <= 0) {
11385            mSharedLibraries.remove(name);
11386            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11387                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11388                        .getPackageName());
11389            }
11390        }
11391        return true;
11392    }
11393
11394    /**
11395     * Adds a scanned package to the system. When this method is finished, the package will
11396     * be available for query, resolution, etc...
11397     */
11398    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11399            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11400        final String pkgName = pkg.packageName;
11401        if (mCustomResolverComponentName != null &&
11402                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11403            setUpCustomResolverActivity(pkg);
11404        }
11405
11406        if (pkg.packageName.equals("android")) {
11407            synchronized (mPackages) {
11408                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11409                    // Set up information for our fall-back user intent resolution activity.
11410                    mPlatformPackage = pkg;
11411                    pkg.mVersionCode = mSdkVersion;
11412                    mAndroidApplication = pkg.applicationInfo;
11413                    if (!mResolverReplaced) {
11414                        mResolveActivity.applicationInfo = mAndroidApplication;
11415                        mResolveActivity.name = ResolverActivity.class.getName();
11416                        mResolveActivity.packageName = mAndroidApplication.packageName;
11417                        mResolveActivity.processName = "system:ui";
11418                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11419                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11420                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11421                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11422                        mResolveActivity.exported = true;
11423                        mResolveActivity.enabled = true;
11424                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11425                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11426                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11427                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11428                                | ActivityInfo.CONFIG_ORIENTATION
11429                                | ActivityInfo.CONFIG_KEYBOARD
11430                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11431                        mResolveInfo.activityInfo = mResolveActivity;
11432                        mResolveInfo.priority = 0;
11433                        mResolveInfo.preferredOrder = 0;
11434                        mResolveInfo.match = 0;
11435                        mResolveComponentName = new ComponentName(
11436                                mAndroidApplication.packageName, mResolveActivity.name);
11437                    }
11438                }
11439            }
11440        }
11441
11442        ArrayList<PackageParser.Package> clientLibPkgs = null;
11443        // writer
11444        synchronized (mPackages) {
11445            boolean hasStaticSharedLibs = false;
11446
11447            // Any app can add new static shared libraries
11448            if (pkg.staticSharedLibName != null) {
11449                // Static shared libs don't allow renaming as they have synthetic package
11450                // names to allow install of multiple versions, so use name from manifest.
11451                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11452                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11453                        pkg.manifestPackageName, pkg.mVersionCode)) {
11454                    hasStaticSharedLibs = true;
11455                } else {
11456                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11457                                + pkg.staticSharedLibName + " already exists; skipping");
11458                }
11459                // Static shared libs cannot be updated once installed since they
11460                // use synthetic package name which includes the version code, so
11461                // not need to update other packages's shared lib dependencies.
11462            }
11463
11464            if (!hasStaticSharedLibs
11465                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11466                // Only system apps can add new dynamic shared libraries.
11467                if (pkg.libraryNames != null) {
11468                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11469                        String name = pkg.libraryNames.get(i);
11470                        boolean allowed = false;
11471                        if (pkg.isUpdatedSystemApp()) {
11472                            // New library entries can only be added through the
11473                            // system image.  This is important to get rid of a lot
11474                            // of nasty edge cases: for example if we allowed a non-
11475                            // system update of the app to add a library, then uninstalling
11476                            // the update would make the library go away, and assumptions
11477                            // we made such as through app install filtering would now
11478                            // have allowed apps on the device which aren't compatible
11479                            // with it.  Better to just have the restriction here, be
11480                            // conservative, and create many fewer cases that can negatively
11481                            // impact the user experience.
11482                            final PackageSetting sysPs = mSettings
11483                                    .getDisabledSystemPkgLPr(pkg.packageName);
11484                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11485                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11486                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11487                                        allowed = true;
11488                                        break;
11489                                    }
11490                                }
11491                            }
11492                        } else {
11493                            allowed = true;
11494                        }
11495                        if (allowed) {
11496                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11497                                    SharedLibraryInfo.VERSION_UNDEFINED,
11498                                    SharedLibraryInfo.TYPE_DYNAMIC,
11499                                    pkg.packageName, pkg.mVersionCode)) {
11500                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11501                                        + name + " already exists; skipping");
11502                            }
11503                        } else {
11504                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11505                                    + name + " that is not declared on system image; skipping");
11506                        }
11507                    }
11508
11509                    if ((scanFlags & SCAN_BOOTING) == 0) {
11510                        // If we are not booting, we need to update any applications
11511                        // that are clients of our shared library.  If we are booting,
11512                        // this will all be done once the scan is complete.
11513                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11514                    }
11515                }
11516            }
11517        }
11518
11519        if ((scanFlags & SCAN_BOOTING) != 0) {
11520            // No apps can run during boot scan, so they don't need to be frozen
11521        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11522            // Caller asked to not kill app, so it's probably not frozen
11523        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11524            // Caller asked us to ignore frozen check for some reason; they
11525            // probably didn't know the package name
11526        } else {
11527            // We're doing major surgery on this package, so it better be frozen
11528            // right now to keep it from launching
11529            checkPackageFrozen(pkgName);
11530        }
11531
11532        // Also need to kill any apps that are dependent on the library.
11533        if (clientLibPkgs != null) {
11534            for (int i=0; i<clientLibPkgs.size(); i++) {
11535                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11536                killApplication(clientPkg.applicationInfo.packageName,
11537                        clientPkg.applicationInfo.uid, "update lib");
11538            }
11539        }
11540
11541        // writer
11542        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11543
11544        synchronized (mPackages) {
11545            // We don't expect installation to fail beyond this point
11546
11547            // Add the new setting to mSettings
11548            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11549            // Add the new setting to mPackages
11550            mPackages.put(pkg.applicationInfo.packageName, pkg);
11551            // Make sure we don't accidentally delete its data.
11552            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11553            while (iter.hasNext()) {
11554                PackageCleanItem item = iter.next();
11555                if (pkgName.equals(item.packageName)) {
11556                    iter.remove();
11557                }
11558            }
11559
11560            // Add the package's KeySets to the global KeySetManagerService
11561            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11562            ksms.addScannedPackageLPw(pkg);
11563
11564            int N = pkg.providers.size();
11565            StringBuilder r = null;
11566            int i;
11567            for (i=0; i<N; i++) {
11568                PackageParser.Provider p = pkg.providers.get(i);
11569                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11570                        p.info.processName);
11571                mProviders.addProvider(p);
11572                p.syncable = p.info.isSyncable;
11573                if (p.info.authority != null) {
11574                    String names[] = p.info.authority.split(";");
11575                    p.info.authority = null;
11576                    for (int j = 0; j < names.length; j++) {
11577                        if (j == 1 && p.syncable) {
11578                            // We only want the first authority for a provider to possibly be
11579                            // syncable, so if we already added this provider using a different
11580                            // authority clear the syncable flag. We copy the provider before
11581                            // changing it because the mProviders object contains a reference
11582                            // to a provider that we don't want to change.
11583                            // Only do this for the second authority since the resulting provider
11584                            // object can be the same for all future authorities for this provider.
11585                            p = new PackageParser.Provider(p);
11586                            p.syncable = false;
11587                        }
11588                        if (!mProvidersByAuthority.containsKey(names[j])) {
11589                            mProvidersByAuthority.put(names[j], p);
11590                            if (p.info.authority == null) {
11591                                p.info.authority = names[j];
11592                            } else {
11593                                p.info.authority = p.info.authority + ";" + names[j];
11594                            }
11595                            if (DEBUG_PACKAGE_SCANNING) {
11596                                if (chatty)
11597                                    Log.d(TAG, "Registered content provider: " + names[j]
11598                                            + ", className = " + p.info.name + ", isSyncable = "
11599                                            + p.info.isSyncable);
11600                            }
11601                        } else {
11602                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11603                            Slog.w(TAG, "Skipping provider name " + names[j] +
11604                                    " (in package " + pkg.applicationInfo.packageName +
11605                                    "): name already used by "
11606                                    + ((other != null && other.getComponentName() != null)
11607                                            ? other.getComponentName().getPackageName() : "?"));
11608                        }
11609                    }
11610                }
11611                if (chatty) {
11612                    if (r == null) {
11613                        r = new StringBuilder(256);
11614                    } else {
11615                        r.append(' ');
11616                    }
11617                    r.append(p.info.name);
11618                }
11619            }
11620            if (r != null) {
11621                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11622            }
11623
11624            N = pkg.services.size();
11625            r = null;
11626            for (i=0; i<N; i++) {
11627                PackageParser.Service s = pkg.services.get(i);
11628                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11629                        s.info.processName);
11630                mServices.addService(s);
11631                if (chatty) {
11632                    if (r == null) {
11633                        r = new StringBuilder(256);
11634                    } else {
11635                        r.append(' ');
11636                    }
11637                    r.append(s.info.name);
11638                }
11639            }
11640            if (r != null) {
11641                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11642            }
11643
11644            N = pkg.receivers.size();
11645            r = null;
11646            for (i=0; i<N; i++) {
11647                PackageParser.Activity a = pkg.receivers.get(i);
11648                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11649                        a.info.processName);
11650                mReceivers.addActivity(a, "receiver");
11651                if (chatty) {
11652                    if (r == null) {
11653                        r = new StringBuilder(256);
11654                    } else {
11655                        r.append(' ');
11656                    }
11657                    r.append(a.info.name);
11658                }
11659            }
11660            if (r != null) {
11661                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11662            }
11663
11664            N = pkg.activities.size();
11665            r = null;
11666            for (i=0; i<N; i++) {
11667                PackageParser.Activity a = pkg.activities.get(i);
11668                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11669                        a.info.processName);
11670                mActivities.addActivity(a, "activity");
11671                if (chatty) {
11672                    if (r == null) {
11673                        r = new StringBuilder(256);
11674                    } else {
11675                        r.append(' ');
11676                    }
11677                    r.append(a.info.name);
11678                }
11679            }
11680            if (r != null) {
11681                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11682            }
11683
11684            N = pkg.permissionGroups.size();
11685            r = null;
11686            for (i=0; i<N; i++) {
11687                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11688                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11689                final String curPackageName = cur == null ? null : cur.info.packageName;
11690                // Dont allow ephemeral apps to define new permission groups.
11691                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11692                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11693                            + pg.info.packageName
11694                            + " ignored: instant apps cannot define new permission groups.");
11695                    continue;
11696                }
11697                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11698                if (cur == null || isPackageUpdate) {
11699                    mPermissionGroups.put(pg.info.name, pg);
11700                    if (chatty) {
11701                        if (r == null) {
11702                            r = new StringBuilder(256);
11703                        } else {
11704                            r.append(' ');
11705                        }
11706                        if (isPackageUpdate) {
11707                            r.append("UPD:");
11708                        }
11709                        r.append(pg.info.name);
11710                    }
11711                } else {
11712                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11713                            + pg.info.packageName + " ignored: original from "
11714                            + cur.info.packageName);
11715                    if (chatty) {
11716                        if (r == null) {
11717                            r = new StringBuilder(256);
11718                        } else {
11719                            r.append(' ');
11720                        }
11721                        r.append("DUP:");
11722                        r.append(pg.info.name);
11723                    }
11724                }
11725            }
11726            if (r != null) {
11727                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11728            }
11729
11730            N = pkg.permissions.size();
11731            r = null;
11732            for (i=0; i<N; i++) {
11733                PackageParser.Permission p = pkg.permissions.get(i);
11734
11735                // Dont allow ephemeral apps to define new permissions.
11736                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11737                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11738                            + p.info.packageName
11739                            + " ignored: instant apps cannot define new permissions.");
11740                    continue;
11741                }
11742
11743                // Assume by default that we did not install this permission into the system.
11744                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11745
11746                // Now that permission groups have a special meaning, we ignore permission
11747                // groups for legacy apps to prevent unexpected behavior. In particular,
11748                // permissions for one app being granted to someone just because they happen
11749                // to be in a group defined by another app (before this had no implications).
11750                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11751                    p.group = mPermissionGroups.get(p.info.group);
11752                    // Warn for a permission in an unknown group.
11753                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11754                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11755                                + p.info.packageName + " in an unknown group " + p.info.group);
11756                    }
11757                }
11758
11759                ArrayMap<String, BasePermission> permissionMap =
11760                        p.tree ? mSettings.mPermissionTrees
11761                                : mSettings.mPermissions;
11762                BasePermission bp = permissionMap.get(p.info.name);
11763
11764                // Allow system apps to redefine non-system permissions
11765                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11766                    final boolean currentOwnerIsSystem = (bp.perm != null
11767                            && isSystemApp(bp.perm.owner));
11768                    if (isSystemApp(p.owner)) {
11769                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11770                            // It's a built-in permission and no owner, take ownership now
11771                            bp.packageSetting = pkgSetting;
11772                            bp.perm = p;
11773                            bp.uid = pkg.applicationInfo.uid;
11774                            bp.sourcePackage = p.info.packageName;
11775                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11776                        } else if (!currentOwnerIsSystem) {
11777                            String msg = "New decl " + p.owner + " of permission  "
11778                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11779                            reportSettingsProblem(Log.WARN, msg);
11780                            bp = null;
11781                        }
11782                    }
11783                }
11784
11785                if (bp == null) {
11786                    bp = new BasePermission(p.info.name, p.info.packageName,
11787                            BasePermission.TYPE_NORMAL);
11788                    permissionMap.put(p.info.name, bp);
11789                }
11790
11791                if (bp.perm == null) {
11792                    if (bp.sourcePackage == null
11793                            || bp.sourcePackage.equals(p.info.packageName)) {
11794                        BasePermission tree = findPermissionTreeLP(p.info.name);
11795                        if (tree == null
11796                                || tree.sourcePackage.equals(p.info.packageName)) {
11797                            bp.packageSetting = pkgSetting;
11798                            bp.perm = p;
11799                            bp.uid = pkg.applicationInfo.uid;
11800                            bp.sourcePackage = p.info.packageName;
11801                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11802                            if (chatty) {
11803                                if (r == null) {
11804                                    r = new StringBuilder(256);
11805                                } else {
11806                                    r.append(' ');
11807                                }
11808                                r.append(p.info.name);
11809                            }
11810                        } else {
11811                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11812                                    + p.info.packageName + " ignored: base tree "
11813                                    + tree.name + " is from package "
11814                                    + tree.sourcePackage);
11815                        }
11816                    } else {
11817                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11818                                + p.info.packageName + " ignored: original from "
11819                                + bp.sourcePackage);
11820                    }
11821                } else if (chatty) {
11822                    if (r == null) {
11823                        r = new StringBuilder(256);
11824                    } else {
11825                        r.append(' ');
11826                    }
11827                    r.append("DUP:");
11828                    r.append(p.info.name);
11829                }
11830                if (bp.perm == p) {
11831                    bp.protectionLevel = p.info.protectionLevel;
11832                }
11833            }
11834
11835            if (r != null) {
11836                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11837            }
11838
11839            N = pkg.instrumentation.size();
11840            r = null;
11841            for (i=0; i<N; i++) {
11842                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11843                a.info.packageName = pkg.applicationInfo.packageName;
11844                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11845                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11846                a.info.splitNames = pkg.splitNames;
11847                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11848                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11849                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11850                a.info.dataDir = pkg.applicationInfo.dataDir;
11851                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11852                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11853                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11854                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11855                mInstrumentation.put(a.getComponentName(), a);
11856                if (chatty) {
11857                    if (r == null) {
11858                        r = new StringBuilder(256);
11859                    } else {
11860                        r.append(' ');
11861                    }
11862                    r.append(a.info.name);
11863                }
11864            }
11865            if (r != null) {
11866                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11867            }
11868
11869            if (pkg.protectedBroadcasts != null) {
11870                N = pkg.protectedBroadcasts.size();
11871                synchronized (mProtectedBroadcasts) {
11872                    for (i = 0; i < N; i++) {
11873                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11874                    }
11875                }
11876            }
11877        }
11878
11879        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11880    }
11881
11882    /**
11883     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11884     * is derived purely on the basis of the contents of {@code scanFile} and
11885     * {@code cpuAbiOverride}.
11886     *
11887     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11888     */
11889    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11890                                 String cpuAbiOverride, boolean extractLibs,
11891                                 File appLib32InstallDir)
11892            throws PackageManagerException {
11893        // Give ourselves some initial paths; we'll come back for another
11894        // pass once we've determined ABI below.
11895        setNativeLibraryPaths(pkg, appLib32InstallDir);
11896
11897        // We would never need to extract libs for forward-locked and external packages,
11898        // since the container service will do it for us. We shouldn't attempt to
11899        // extract libs from system app when it was not updated.
11900        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11901                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11902            extractLibs = false;
11903        }
11904
11905        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11906        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11907
11908        NativeLibraryHelper.Handle handle = null;
11909        try {
11910            handle = NativeLibraryHelper.Handle.create(pkg);
11911            // TODO(multiArch): This can be null for apps that didn't go through the
11912            // usual installation process. We can calculate it again, like we
11913            // do during install time.
11914            //
11915            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11916            // unnecessary.
11917            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11918
11919            // Null out the abis so that they can be recalculated.
11920            pkg.applicationInfo.primaryCpuAbi = null;
11921            pkg.applicationInfo.secondaryCpuAbi = null;
11922            if (isMultiArch(pkg.applicationInfo)) {
11923                // Warn if we've set an abiOverride for multi-lib packages..
11924                // By definition, we need to copy both 32 and 64 bit libraries for
11925                // such packages.
11926                if (pkg.cpuAbiOverride != null
11927                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11928                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11929                }
11930
11931                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11932                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11933                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11934                    if (extractLibs) {
11935                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11936                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11937                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11938                                useIsaSpecificSubdirs);
11939                    } else {
11940                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11941                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11942                    }
11943                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11944                }
11945
11946                // Shared library native code should be in the APK zip aligned
11947                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11948                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11949                            "Shared library native lib extraction not supported");
11950                }
11951
11952                maybeThrowExceptionForMultiArchCopy(
11953                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11954
11955                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11956                    if (extractLibs) {
11957                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11958                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11959                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11960                                useIsaSpecificSubdirs);
11961                    } else {
11962                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11963                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11964                    }
11965                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11966                }
11967
11968                maybeThrowExceptionForMultiArchCopy(
11969                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11970
11971                if (abi64 >= 0) {
11972                    // Shared library native libs should be in the APK zip aligned
11973                    if (extractLibs && pkg.isLibrary()) {
11974                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11975                                "Shared library native lib extraction not supported");
11976                    }
11977                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11978                }
11979
11980                if (abi32 >= 0) {
11981                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11982                    if (abi64 >= 0) {
11983                        if (pkg.use32bitAbi) {
11984                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11985                            pkg.applicationInfo.primaryCpuAbi = abi;
11986                        } else {
11987                            pkg.applicationInfo.secondaryCpuAbi = abi;
11988                        }
11989                    } else {
11990                        pkg.applicationInfo.primaryCpuAbi = abi;
11991                    }
11992                }
11993            } else {
11994                String[] abiList = (cpuAbiOverride != null) ?
11995                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11996
11997                // Enable gross and lame hacks for apps that are built with old
11998                // SDK tools. We must scan their APKs for renderscript bitcode and
11999                // not launch them if it's present. Don't bother checking on devices
12000                // that don't have 64 bit support.
12001                boolean needsRenderScriptOverride = false;
12002                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
12003                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
12004                    abiList = Build.SUPPORTED_32_BIT_ABIS;
12005                    needsRenderScriptOverride = true;
12006                }
12007
12008                final int copyRet;
12009                if (extractLibs) {
12010                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12011                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12012                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
12013                } else {
12014                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12015                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
12016                }
12017                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12018
12019                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
12020                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12021                            "Error unpackaging native libs for app, errorCode=" + copyRet);
12022                }
12023
12024                if (copyRet >= 0) {
12025                    // Shared libraries that have native libs must be multi-architecture
12026                    if (pkg.isLibrary()) {
12027                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12028                                "Shared library with native libs must be multiarch");
12029                    }
12030                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12031                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12032                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12033                } else if (needsRenderScriptOverride) {
12034                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
12035                }
12036            }
12037        } catch (IOException ioe) {
12038            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12039        } finally {
12040            IoUtils.closeQuietly(handle);
12041        }
12042
12043        // Now that we've calculated the ABIs and determined if it's an internal app,
12044        // we will go ahead and populate the nativeLibraryPath.
12045        setNativeLibraryPaths(pkg, appLib32InstallDir);
12046    }
12047
12048    /**
12049     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12050     * i.e, so that all packages can be run inside a single process if required.
12051     *
12052     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12053     * this function will either try and make the ABI for all packages in {@code packagesForUser}
12054     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12055     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12056     * updating a package that belongs to a shared user.
12057     *
12058     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12059     * adds unnecessary complexity.
12060     */
12061    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12062            PackageParser.Package scannedPackage) {
12063        String requiredInstructionSet = null;
12064        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12065            requiredInstructionSet = VMRuntime.getInstructionSet(
12066                     scannedPackage.applicationInfo.primaryCpuAbi);
12067        }
12068
12069        PackageSetting requirer = null;
12070        for (PackageSetting ps : packagesForUser) {
12071            // If packagesForUser contains scannedPackage, we skip it. This will happen
12072            // when scannedPackage is an update of an existing package. Without this check,
12073            // we will never be able to change the ABI of any package belonging to a shared
12074            // user, even if it's compatible with other packages.
12075            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12076                if (ps.primaryCpuAbiString == null) {
12077                    continue;
12078                }
12079
12080                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12081                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12082                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12083                    // this but there's not much we can do.
12084                    String errorMessage = "Instruction set mismatch, "
12085                            + ((requirer == null) ? "[caller]" : requirer)
12086                            + " requires " + requiredInstructionSet + " whereas " + ps
12087                            + " requires " + instructionSet;
12088                    Slog.w(TAG, errorMessage);
12089                }
12090
12091                if (requiredInstructionSet == null) {
12092                    requiredInstructionSet = instructionSet;
12093                    requirer = ps;
12094                }
12095            }
12096        }
12097
12098        if (requiredInstructionSet != null) {
12099            String adjustedAbi;
12100            if (requirer != null) {
12101                // requirer != null implies that either scannedPackage was null or that scannedPackage
12102                // did not require an ABI, in which case we have to adjust scannedPackage to match
12103                // the ABI of the set (which is the same as requirer's ABI)
12104                adjustedAbi = requirer.primaryCpuAbiString;
12105                if (scannedPackage != null) {
12106                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12107                }
12108            } else {
12109                // requirer == null implies that we're updating all ABIs in the set to
12110                // match scannedPackage.
12111                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12112            }
12113
12114            for (PackageSetting ps : packagesForUser) {
12115                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12116                    if (ps.primaryCpuAbiString != null) {
12117                        continue;
12118                    }
12119
12120                    ps.primaryCpuAbiString = adjustedAbi;
12121                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12122                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12123                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12124                        if (DEBUG_ABI_SELECTION) {
12125                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12126                                    + " (requirer="
12127                                    + (requirer != null ? requirer.pkg : "null")
12128                                    + ", scannedPackage="
12129                                    + (scannedPackage != null ? scannedPackage : "null")
12130                                    + ")");
12131                        }
12132                        try {
12133                            mInstaller.rmdex(ps.codePathString,
12134                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12135                        } catch (InstallerException ignored) {
12136                        }
12137                    }
12138                }
12139            }
12140        }
12141    }
12142
12143    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12144        synchronized (mPackages) {
12145            mResolverReplaced = true;
12146            // Set up information for custom user intent resolution activity.
12147            mResolveActivity.applicationInfo = pkg.applicationInfo;
12148            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12149            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12150            mResolveActivity.processName = pkg.applicationInfo.packageName;
12151            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12152            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12153                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12154            mResolveActivity.theme = 0;
12155            mResolveActivity.exported = true;
12156            mResolveActivity.enabled = true;
12157            mResolveInfo.activityInfo = mResolveActivity;
12158            mResolveInfo.priority = 0;
12159            mResolveInfo.preferredOrder = 0;
12160            mResolveInfo.match = 0;
12161            mResolveComponentName = mCustomResolverComponentName;
12162            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12163                    mResolveComponentName);
12164        }
12165    }
12166
12167    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12168        if (installerActivity == null) {
12169            if (DEBUG_EPHEMERAL) {
12170                Slog.d(TAG, "Clear ephemeral installer activity");
12171            }
12172            mInstantAppInstallerActivity = null;
12173            return;
12174        }
12175
12176        if (DEBUG_EPHEMERAL) {
12177            Slog.d(TAG, "Set ephemeral installer activity: "
12178                    + installerActivity.getComponentName());
12179        }
12180        // Set up information for ephemeral installer activity
12181        mInstantAppInstallerActivity = installerActivity;
12182        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12183                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12184        mInstantAppInstallerActivity.exported = true;
12185        mInstantAppInstallerActivity.enabled = true;
12186        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12187        mInstantAppInstallerInfo.priority = 0;
12188        mInstantAppInstallerInfo.preferredOrder = 1;
12189        mInstantAppInstallerInfo.isDefault = true;
12190        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12191                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12192    }
12193
12194    private static String calculateBundledApkRoot(final String codePathString) {
12195        final File codePath = new File(codePathString);
12196        final File codeRoot;
12197        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12198            codeRoot = Environment.getRootDirectory();
12199        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12200            codeRoot = Environment.getOemDirectory();
12201        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12202            codeRoot = Environment.getVendorDirectory();
12203        } else {
12204            // Unrecognized code path; take its top real segment as the apk root:
12205            // e.g. /something/app/blah.apk => /something
12206            try {
12207                File f = codePath.getCanonicalFile();
12208                File parent = f.getParentFile();    // non-null because codePath is a file
12209                File tmp;
12210                while ((tmp = parent.getParentFile()) != null) {
12211                    f = parent;
12212                    parent = tmp;
12213                }
12214                codeRoot = f;
12215                Slog.w(TAG, "Unrecognized code path "
12216                        + codePath + " - using " + codeRoot);
12217            } catch (IOException e) {
12218                // Can't canonicalize the code path -- shenanigans?
12219                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12220                return Environment.getRootDirectory().getPath();
12221            }
12222        }
12223        return codeRoot.getPath();
12224    }
12225
12226    /**
12227     * Derive and set the location of native libraries for the given package,
12228     * which varies depending on where and how the package was installed.
12229     */
12230    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12231        final ApplicationInfo info = pkg.applicationInfo;
12232        final String codePath = pkg.codePath;
12233        final File codeFile = new File(codePath);
12234        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12235        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12236
12237        info.nativeLibraryRootDir = null;
12238        info.nativeLibraryRootRequiresIsa = false;
12239        info.nativeLibraryDir = null;
12240        info.secondaryNativeLibraryDir = null;
12241
12242        if (isApkFile(codeFile)) {
12243            // Monolithic install
12244            if (bundledApp) {
12245                // If "/system/lib64/apkname" exists, assume that is the per-package
12246                // native library directory to use; otherwise use "/system/lib/apkname".
12247                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12248                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12249                        getPrimaryInstructionSet(info));
12250
12251                // This is a bundled system app so choose the path based on the ABI.
12252                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12253                // is just the default path.
12254                final String apkName = deriveCodePathName(codePath);
12255                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12256                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12257                        apkName).getAbsolutePath();
12258
12259                if (info.secondaryCpuAbi != null) {
12260                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12261                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12262                            secondaryLibDir, apkName).getAbsolutePath();
12263                }
12264            } else if (asecApp) {
12265                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12266                        .getAbsolutePath();
12267            } else {
12268                final String apkName = deriveCodePathName(codePath);
12269                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12270                        .getAbsolutePath();
12271            }
12272
12273            info.nativeLibraryRootRequiresIsa = false;
12274            info.nativeLibraryDir = info.nativeLibraryRootDir;
12275        } else {
12276            // Cluster install
12277            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12278            info.nativeLibraryRootRequiresIsa = true;
12279
12280            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12281                    getPrimaryInstructionSet(info)).getAbsolutePath();
12282
12283            if (info.secondaryCpuAbi != null) {
12284                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12285                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12286            }
12287        }
12288    }
12289
12290    /**
12291     * Calculate the abis and roots for a bundled app. These can uniquely
12292     * be determined from the contents of the system partition, i.e whether
12293     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12294     * of this information, and instead assume that the system was built
12295     * sensibly.
12296     */
12297    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12298                                           PackageSetting pkgSetting) {
12299        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12300
12301        // If "/system/lib64/apkname" exists, assume that is the per-package
12302        // native library directory to use; otherwise use "/system/lib/apkname".
12303        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12304        setBundledAppAbi(pkg, apkRoot, apkName);
12305        // pkgSetting might be null during rescan following uninstall of updates
12306        // to a bundled app, so accommodate that possibility.  The settings in
12307        // that case will be established later from the parsed package.
12308        //
12309        // If the settings aren't null, sync them up with what we've just derived.
12310        // note that apkRoot isn't stored in the package settings.
12311        if (pkgSetting != null) {
12312            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12313            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12314        }
12315    }
12316
12317    /**
12318     * Deduces the ABI of a bundled app and sets the relevant fields on the
12319     * parsed pkg object.
12320     *
12321     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12322     *        under which system libraries are installed.
12323     * @param apkName the name of the installed package.
12324     */
12325    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12326        final File codeFile = new File(pkg.codePath);
12327
12328        final boolean has64BitLibs;
12329        final boolean has32BitLibs;
12330        if (isApkFile(codeFile)) {
12331            // Monolithic install
12332            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12333            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12334        } else {
12335            // Cluster install
12336            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12337            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12338                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12339                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12340                has64BitLibs = (new File(rootDir, isa)).exists();
12341            } else {
12342                has64BitLibs = false;
12343            }
12344            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12345                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12346                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12347                has32BitLibs = (new File(rootDir, isa)).exists();
12348            } else {
12349                has32BitLibs = false;
12350            }
12351        }
12352
12353        if (has64BitLibs && !has32BitLibs) {
12354            // The package has 64 bit libs, but not 32 bit libs. Its primary
12355            // ABI should be 64 bit. We can safely assume here that the bundled
12356            // native libraries correspond to the most preferred ABI in the list.
12357
12358            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12359            pkg.applicationInfo.secondaryCpuAbi = null;
12360        } else if (has32BitLibs && !has64BitLibs) {
12361            // The package has 32 bit libs but not 64 bit libs. Its primary
12362            // ABI should be 32 bit.
12363
12364            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12365            pkg.applicationInfo.secondaryCpuAbi = null;
12366        } else if (has32BitLibs && has64BitLibs) {
12367            // The application has both 64 and 32 bit bundled libraries. We check
12368            // here that the app declares multiArch support, and warn if it doesn't.
12369            //
12370            // We will be lenient here and record both ABIs. The primary will be the
12371            // ABI that's higher on the list, i.e, a device that's configured to prefer
12372            // 64 bit apps will see a 64 bit primary ABI,
12373
12374            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12375                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12376            }
12377
12378            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12379                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12380                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12381            } else {
12382                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12383                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12384            }
12385        } else {
12386            pkg.applicationInfo.primaryCpuAbi = null;
12387            pkg.applicationInfo.secondaryCpuAbi = null;
12388        }
12389    }
12390
12391    private void killApplication(String pkgName, int appId, String reason) {
12392        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12393    }
12394
12395    private void killApplication(String pkgName, int appId, int userId, String reason) {
12396        // Request the ActivityManager to kill the process(only for existing packages)
12397        // so that we do not end up in a confused state while the user is still using the older
12398        // version of the application while the new one gets installed.
12399        final long token = Binder.clearCallingIdentity();
12400        try {
12401            IActivityManager am = ActivityManager.getService();
12402            if (am != null) {
12403                try {
12404                    am.killApplication(pkgName, appId, userId, reason);
12405                } catch (RemoteException e) {
12406                }
12407            }
12408        } finally {
12409            Binder.restoreCallingIdentity(token);
12410        }
12411    }
12412
12413    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12414        // Remove the parent package setting
12415        PackageSetting ps = (PackageSetting) pkg.mExtras;
12416        if (ps != null) {
12417            removePackageLI(ps, chatty);
12418        }
12419        // Remove the child package setting
12420        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12421        for (int i = 0; i < childCount; i++) {
12422            PackageParser.Package childPkg = pkg.childPackages.get(i);
12423            ps = (PackageSetting) childPkg.mExtras;
12424            if (ps != null) {
12425                removePackageLI(ps, chatty);
12426            }
12427        }
12428    }
12429
12430    void removePackageLI(PackageSetting ps, boolean chatty) {
12431        if (DEBUG_INSTALL) {
12432            if (chatty)
12433                Log.d(TAG, "Removing package " + ps.name);
12434        }
12435
12436        // writer
12437        synchronized (mPackages) {
12438            mPackages.remove(ps.name);
12439            final PackageParser.Package pkg = ps.pkg;
12440            if (pkg != null) {
12441                cleanPackageDataStructuresLILPw(pkg, chatty);
12442            }
12443        }
12444    }
12445
12446    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12447        if (DEBUG_INSTALL) {
12448            if (chatty)
12449                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12450        }
12451
12452        // writer
12453        synchronized (mPackages) {
12454            // Remove the parent package
12455            mPackages.remove(pkg.applicationInfo.packageName);
12456            cleanPackageDataStructuresLILPw(pkg, chatty);
12457
12458            // Remove the child packages
12459            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12460            for (int i = 0; i < childCount; i++) {
12461                PackageParser.Package childPkg = pkg.childPackages.get(i);
12462                mPackages.remove(childPkg.applicationInfo.packageName);
12463                cleanPackageDataStructuresLILPw(childPkg, chatty);
12464            }
12465        }
12466    }
12467
12468    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12469        int N = pkg.providers.size();
12470        StringBuilder r = null;
12471        int i;
12472        for (i=0; i<N; i++) {
12473            PackageParser.Provider p = pkg.providers.get(i);
12474            mProviders.removeProvider(p);
12475            if (p.info.authority == null) {
12476
12477                /* There was another ContentProvider with this authority when
12478                 * this app was installed so this authority is null,
12479                 * Ignore it as we don't have to unregister the provider.
12480                 */
12481                continue;
12482            }
12483            String names[] = p.info.authority.split(";");
12484            for (int j = 0; j < names.length; j++) {
12485                if (mProvidersByAuthority.get(names[j]) == p) {
12486                    mProvidersByAuthority.remove(names[j]);
12487                    if (DEBUG_REMOVE) {
12488                        if (chatty)
12489                            Log.d(TAG, "Unregistered content provider: " + names[j]
12490                                    + ", className = " + p.info.name + ", isSyncable = "
12491                                    + p.info.isSyncable);
12492                    }
12493                }
12494            }
12495            if (DEBUG_REMOVE && chatty) {
12496                if (r == null) {
12497                    r = new StringBuilder(256);
12498                } else {
12499                    r.append(' ');
12500                }
12501                r.append(p.info.name);
12502            }
12503        }
12504        if (r != null) {
12505            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12506        }
12507
12508        N = pkg.services.size();
12509        r = null;
12510        for (i=0; i<N; i++) {
12511            PackageParser.Service s = pkg.services.get(i);
12512            mServices.removeService(s);
12513            if (chatty) {
12514                if (r == null) {
12515                    r = new StringBuilder(256);
12516                } else {
12517                    r.append(' ');
12518                }
12519                r.append(s.info.name);
12520            }
12521        }
12522        if (r != null) {
12523            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12524        }
12525
12526        N = pkg.receivers.size();
12527        r = null;
12528        for (i=0; i<N; i++) {
12529            PackageParser.Activity a = pkg.receivers.get(i);
12530            mReceivers.removeActivity(a, "receiver");
12531            if (DEBUG_REMOVE && chatty) {
12532                if (r == null) {
12533                    r = new StringBuilder(256);
12534                } else {
12535                    r.append(' ');
12536                }
12537                r.append(a.info.name);
12538            }
12539        }
12540        if (r != null) {
12541            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12542        }
12543
12544        N = pkg.activities.size();
12545        r = null;
12546        for (i=0; i<N; i++) {
12547            PackageParser.Activity a = pkg.activities.get(i);
12548            mActivities.removeActivity(a, "activity");
12549            if (DEBUG_REMOVE && chatty) {
12550                if (r == null) {
12551                    r = new StringBuilder(256);
12552                } else {
12553                    r.append(' ');
12554                }
12555                r.append(a.info.name);
12556            }
12557        }
12558        if (r != null) {
12559            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12560        }
12561
12562        N = pkg.permissions.size();
12563        r = null;
12564        for (i=0; i<N; i++) {
12565            PackageParser.Permission p = pkg.permissions.get(i);
12566            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12567            if (bp == null) {
12568                bp = mSettings.mPermissionTrees.get(p.info.name);
12569            }
12570            if (bp != null && bp.perm == p) {
12571                bp.perm = null;
12572                if (DEBUG_REMOVE && chatty) {
12573                    if (r == null) {
12574                        r = new StringBuilder(256);
12575                    } else {
12576                        r.append(' ');
12577                    }
12578                    r.append(p.info.name);
12579                }
12580            }
12581            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12582                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12583                if (appOpPkgs != null) {
12584                    appOpPkgs.remove(pkg.packageName);
12585                }
12586            }
12587        }
12588        if (r != null) {
12589            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12590        }
12591
12592        N = pkg.requestedPermissions.size();
12593        r = null;
12594        for (i=0; i<N; i++) {
12595            String perm = pkg.requestedPermissions.get(i);
12596            BasePermission bp = mSettings.mPermissions.get(perm);
12597            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12598                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12599                if (appOpPkgs != null) {
12600                    appOpPkgs.remove(pkg.packageName);
12601                    if (appOpPkgs.isEmpty()) {
12602                        mAppOpPermissionPackages.remove(perm);
12603                    }
12604                }
12605            }
12606        }
12607        if (r != null) {
12608            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12609        }
12610
12611        N = pkg.instrumentation.size();
12612        r = null;
12613        for (i=0; i<N; i++) {
12614            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12615            mInstrumentation.remove(a.getComponentName());
12616            if (DEBUG_REMOVE && chatty) {
12617                if (r == null) {
12618                    r = new StringBuilder(256);
12619                } else {
12620                    r.append(' ');
12621                }
12622                r.append(a.info.name);
12623            }
12624        }
12625        if (r != null) {
12626            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12627        }
12628
12629        r = null;
12630        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12631            // Only system apps can hold shared libraries.
12632            if (pkg.libraryNames != null) {
12633                for (i = 0; i < pkg.libraryNames.size(); i++) {
12634                    String name = pkg.libraryNames.get(i);
12635                    if (removeSharedLibraryLPw(name, 0)) {
12636                        if (DEBUG_REMOVE && chatty) {
12637                            if (r == null) {
12638                                r = new StringBuilder(256);
12639                            } else {
12640                                r.append(' ');
12641                            }
12642                            r.append(name);
12643                        }
12644                    }
12645                }
12646            }
12647        }
12648
12649        r = null;
12650
12651        // Any package can hold static shared libraries.
12652        if (pkg.staticSharedLibName != null) {
12653            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12654                if (DEBUG_REMOVE && chatty) {
12655                    if (r == null) {
12656                        r = new StringBuilder(256);
12657                    } else {
12658                        r.append(' ');
12659                    }
12660                    r.append(pkg.staticSharedLibName);
12661                }
12662            }
12663        }
12664
12665        if (r != null) {
12666            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12667        }
12668    }
12669
12670    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12671        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12672            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12673                return true;
12674            }
12675        }
12676        return false;
12677    }
12678
12679    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12680    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12681    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12682
12683    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12684        // Update the parent permissions
12685        updatePermissionsLPw(pkg.packageName, pkg, flags);
12686        // Update the child permissions
12687        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12688        for (int i = 0; i < childCount; i++) {
12689            PackageParser.Package childPkg = pkg.childPackages.get(i);
12690            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12691        }
12692    }
12693
12694    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12695            int flags) {
12696        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12697        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12698    }
12699
12700    private void updatePermissionsLPw(String changingPkg,
12701            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12702        // Make sure there are no dangling permission trees.
12703        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12704        while (it.hasNext()) {
12705            final BasePermission bp = it.next();
12706            if (bp.packageSetting == null) {
12707                // We may not yet have parsed the package, so just see if
12708                // we still know about its settings.
12709                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12710            }
12711            if (bp.packageSetting == null) {
12712                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12713                        + " from package " + bp.sourcePackage);
12714                it.remove();
12715            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12716                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12717                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12718                            + " from package " + bp.sourcePackage);
12719                    flags |= UPDATE_PERMISSIONS_ALL;
12720                    it.remove();
12721                }
12722            }
12723        }
12724
12725        // Make sure all dynamic permissions have been assigned to a package,
12726        // and make sure there are no dangling permissions.
12727        it = mSettings.mPermissions.values().iterator();
12728        while (it.hasNext()) {
12729            final BasePermission bp = it.next();
12730            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12731                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12732                        + bp.name + " pkg=" + bp.sourcePackage
12733                        + " info=" + bp.pendingInfo);
12734                if (bp.packageSetting == null && bp.pendingInfo != null) {
12735                    final BasePermission tree = findPermissionTreeLP(bp.name);
12736                    if (tree != null && tree.perm != null) {
12737                        bp.packageSetting = tree.packageSetting;
12738                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12739                                new PermissionInfo(bp.pendingInfo));
12740                        bp.perm.info.packageName = tree.perm.info.packageName;
12741                        bp.perm.info.name = bp.name;
12742                        bp.uid = tree.uid;
12743                    }
12744                }
12745            }
12746            if (bp.packageSetting == null) {
12747                // We may not yet have parsed the package, so just see if
12748                // we still know about its settings.
12749                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12750            }
12751            if (bp.packageSetting == null) {
12752                Slog.w(TAG, "Removing dangling permission: " + bp.name
12753                        + " from package " + bp.sourcePackage);
12754                it.remove();
12755            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12756                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12757                    Slog.i(TAG, "Removing old permission: " + bp.name
12758                            + " from package " + bp.sourcePackage);
12759                    flags |= UPDATE_PERMISSIONS_ALL;
12760                    it.remove();
12761                }
12762            }
12763        }
12764
12765        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12766        // Now update the permissions for all packages, in particular
12767        // replace the granted permissions of the system packages.
12768        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12769            for (PackageParser.Package pkg : mPackages.values()) {
12770                if (pkg != pkgInfo) {
12771                    // Only replace for packages on requested volume
12772                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12773                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12774                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12775                    grantPermissionsLPw(pkg, replace, changingPkg);
12776                }
12777            }
12778        }
12779
12780        if (pkgInfo != null) {
12781            // Only replace for packages on requested volume
12782            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12783            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12784                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12785            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12786        }
12787        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12788    }
12789
12790    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12791            String packageOfInterest) {
12792        // IMPORTANT: There are two types of permissions: install and runtime.
12793        // Install time permissions are granted when the app is installed to
12794        // all device users and users added in the future. Runtime permissions
12795        // are granted at runtime explicitly to specific users. Normal and signature
12796        // protected permissions are install time permissions. Dangerous permissions
12797        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12798        // otherwise they are runtime permissions. This function does not manage
12799        // runtime permissions except for the case an app targeting Lollipop MR1
12800        // being upgraded to target a newer SDK, in which case dangerous permissions
12801        // are transformed from install time to runtime ones.
12802
12803        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12804        if (ps == null) {
12805            return;
12806        }
12807
12808        PermissionsState permissionsState = ps.getPermissionsState();
12809        PermissionsState origPermissions = permissionsState;
12810
12811        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12812
12813        boolean runtimePermissionsRevoked = false;
12814        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12815
12816        boolean changedInstallPermission = false;
12817
12818        if (replace) {
12819            ps.installPermissionsFixed = false;
12820            if (!ps.isSharedUser()) {
12821                origPermissions = new PermissionsState(permissionsState);
12822                permissionsState.reset();
12823            } else {
12824                // We need to know only about runtime permission changes since the
12825                // calling code always writes the install permissions state but
12826                // the runtime ones are written only if changed. The only cases of
12827                // changed runtime permissions here are promotion of an install to
12828                // runtime and revocation of a runtime from a shared user.
12829                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12830                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12831                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12832                    runtimePermissionsRevoked = true;
12833                }
12834            }
12835        }
12836
12837        permissionsState.setGlobalGids(mGlobalGids);
12838
12839        final int N = pkg.requestedPermissions.size();
12840        for (int i=0; i<N; i++) {
12841            final String name = pkg.requestedPermissions.get(i);
12842            final BasePermission bp = mSettings.mPermissions.get(name);
12843            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12844                    >= Build.VERSION_CODES.M;
12845
12846            if (DEBUG_INSTALL) {
12847                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12848            }
12849
12850            if (bp == null || bp.packageSetting == null) {
12851                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12852                    if (DEBUG_PERMISSIONS) {
12853                        Slog.i(TAG, "Unknown permission " + name
12854                                + " in package " + pkg.packageName);
12855                    }
12856                }
12857                continue;
12858            }
12859
12860
12861            // Limit ephemeral apps to ephemeral allowed permissions.
12862            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12863                if (DEBUG_PERMISSIONS) {
12864                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12865                            + pkg.packageName);
12866                }
12867                continue;
12868            }
12869
12870            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12871                if (DEBUG_PERMISSIONS) {
12872                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12873                            + pkg.packageName);
12874                }
12875                continue;
12876            }
12877
12878            final String perm = bp.name;
12879            boolean allowedSig = false;
12880            int grant = GRANT_DENIED;
12881
12882            // Keep track of app op permissions.
12883            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12884                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12885                if (pkgs == null) {
12886                    pkgs = new ArraySet<>();
12887                    mAppOpPermissionPackages.put(bp.name, pkgs);
12888                }
12889                pkgs.add(pkg.packageName);
12890            }
12891
12892            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12893            switch (level) {
12894                case PermissionInfo.PROTECTION_NORMAL: {
12895                    // For all apps normal permissions are install time ones.
12896                    grant = GRANT_INSTALL;
12897                } break;
12898
12899                case PermissionInfo.PROTECTION_DANGEROUS: {
12900                    // If a permission review is required for legacy apps we represent
12901                    // their permissions as always granted runtime ones since we need
12902                    // to keep the review required permission flag per user while an
12903                    // install permission's state is shared across all users.
12904                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12905                        // For legacy apps dangerous permissions are install time ones.
12906                        grant = GRANT_INSTALL;
12907                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12908                        // For legacy apps that became modern, install becomes runtime.
12909                        grant = GRANT_UPGRADE;
12910                    } else if (mPromoteSystemApps
12911                            && isSystemApp(ps)
12912                            && mExistingSystemPackages.contains(ps.name)) {
12913                        // For legacy system apps, install becomes runtime.
12914                        // We cannot check hasInstallPermission() for system apps since those
12915                        // permissions were granted implicitly and not persisted pre-M.
12916                        grant = GRANT_UPGRADE;
12917                    } else {
12918                        // For modern apps keep runtime permissions unchanged.
12919                        grant = GRANT_RUNTIME;
12920                    }
12921                } break;
12922
12923                case PermissionInfo.PROTECTION_SIGNATURE: {
12924                    // For all apps signature permissions are install time ones.
12925                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12926                    if (allowedSig) {
12927                        grant = GRANT_INSTALL;
12928                    }
12929                } break;
12930            }
12931
12932            if (DEBUG_PERMISSIONS) {
12933                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12934            }
12935
12936            if (grant != GRANT_DENIED) {
12937                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12938                    // If this is an existing, non-system package, then
12939                    // we can't add any new permissions to it.
12940                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12941                        // Except...  if this is a permission that was added
12942                        // to the platform (note: need to only do this when
12943                        // updating the platform).
12944                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12945                            grant = GRANT_DENIED;
12946                        }
12947                    }
12948                }
12949
12950                switch (grant) {
12951                    case GRANT_INSTALL: {
12952                        // Revoke this as runtime permission to handle the case of
12953                        // a runtime permission being downgraded to an install one.
12954                        // Also in permission review mode we keep dangerous permissions
12955                        // for legacy apps
12956                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12957                            if (origPermissions.getRuntimePermissionState(
12958                                    bp.name, userId) != null) {
12959                                // Revoke the runtime permission and clear the flags.
12960                                origPermissions.revokeRuntimePermission(bp, userId);
12961                                origPermissions.updatePermissionFlags(bp, userId,
12962                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12963                                // If we revoked a permission permission, we have to write.
12964                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12965                                        changedRuntimePermissionUserIds, userId);
12966                            }
12967                        }
12968                        // Grant an install permission.
12969                        if (permissionsState.grantInstallPermission(bp) !=
12970                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12971                            changedInstallPermission = true;
12972                        }
12973                    } break;
12974
12975                    case GRANT_RUNTIME: {
12976                        // Grant previously granted runtime permissions.
12977                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12978                            PermissionState permissionState = origPermissions
12979                                    .getRuntimePermissionState(bp.name, userId);
12980                            int flags = permissionState != null
12981                                    ? permissionState.getFlags() : 0;
12982                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12983                                // Don't propagate the permission in a permission review mode if
12984                                // the former was revoked, i.e. marked to not propagate on upgrade.
12985                                // Note that in a permission review mode install permissions are
12986                                // represented as constantly granted runtime ones since we need to
12987                                // keep a per user state associated with the permission. Also the
12988                                // revoke on upgrade flag is no longer applicable and is reset.
12989                                final boolean revokeOnUpgrade = (flags & PackageManager
12990                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12991                                if (revokeOnUpgrade) {
12992                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12993                                    // Since we changed the flags, we have to write.
12994                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12995                                            changedRuntimePermissionUserIds, userId);
12996                                }
12997                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12998                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12999                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
13000                                        // If we cannot put the permission as it was,
13001                                        // we have to write.
13002                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13003                                                changedRuntimePermissionUserIds, userId);
13004                                    }
13005                                }
13006
13007                                // If the app supports runtime permissions no need for a review.
13008                                if (mPermissionReviewRequired
13009                                        && appSupportsRuntimePermissions
13010                                        && (flags & PackageManager
13011                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
13012                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
13013                                    // Since we changed the flags, we have to write.
13014                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13015                                            changedRuntimePermissionUserIds, userId);
13016                                }
13017                            } else if (mPermissionReviewRequired
13018                                    && !appSupportsRuntimePermissions) {
13019                                // For legacy apps that need a permission review, every new
13020                                // runtime permission is granted but it is pending a review.
13021                                // We also need to review only platform defined runtime
13022                                // permissions as these are the only ones the platform knows
13023                                // how to disable the API to simulate revocation as legacy
13024                                // apps don't expect to run with revoked permissions.
13025                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
13026                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13027                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13028                                        // We changed the flags, hence have to write.
13029                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13030                                                changedRuntimePermissionUserIds, userId);
13031                                    }
13032                                }
13033                                if (permissionsState.grantRuntimePermission(bp, userId)
13034                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13035                                    // We changed the permission, hence have to write.
13036                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13037                                            changedRuntimePermissionUserIds, userId);
13038                                }
13039                            }
13040                            // Propagate the permission flags.
13041                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13042                        }
13043                    } break;
13044
13045                    case GRANT_UPGRADE: {
13046                        // Grant runtime permissions for a previously held install permission.
13047                        PermissionState permissionState = origPermissions
13048                                .getInstallPermissionState(bp.name);
13049                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
13050
13051                        if (origPermissions.revokeInstallPermission(bp)
13052                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13053                            // We will be transferring the permission flags, so clear them.
13054                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13055                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
13056                            changedInstallPermission = true;
13057                        }
13058
13059                        // If the permission is not to be promoted to runtime we ignore it and
13060                        // also its other flags as they are not applicable to install permissions.
13061                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13062                            for (int userId : currentUserIds) {
13063                                if (permissionsState.grantRuntimePermission(bp, userId) !=
13064                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13065                                    // Transfer the permission flags.
13066                                    permissionsState.updatePermissionFlags(bp, userId,
13067                                            flags, flags);
13068                                    // If we granted the permission, we have to write.
13069                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13070                                            changedRuntimePermissionUserIds, userId);
13071                                }
13072                            }
13073                        }
13074                    } break;
13075
13076                    default: {
13077                        if (packageOfInterest == null
13078                                || packageOfInterest.equals(pkg.packageName)) {
13079                            if (DEBUG_PERMISSIONS) {
13080                                Slog.i(TAG, "Not granting permission " + perm
13081                                        + " to package " + pkg.packageName
13082                                        + " because it was previously installed without");
13083                            }
13084                        }
13085                    } break;
13086                }
13087            } else {
13088                if (permissionsState.revokeInstallPermission(bp) !=
13089                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13090                    // Also drop the permission flags.
13091                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13092                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13093                    changedInstallPermission = true;
13094                    Slog.i(TAG, "Un-granting permission " + perm
13095                            + " from package " + pkg.packageName
13096                            + " (protectionLevel=" + bp.protectionLevel
13097                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13098                            + ")");
13099                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13100                    // Don't print warning for app op permissions, since it is fine for them
13101                    // not to be granted, there is a UI for the user to decide.
13102                    if (DEBUG_PERMISSIONS
13103                            && (packageOfInterest == null
13104                                    || packageOfInterest.equals(pkg.packageName))) {
13105                        Slog.i(TAG, "Not granting permission " + perm
13106                                + " to package " + pkg.packageName
13107                                + " (protectionLevel=" + bp.protectionLevel
13108                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13109                                + ")");
13110                    }
13111                }
13112            }
13113        }
13114
13115        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13116                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13117            // This is the first that we have heard about this package, so the
13118            // permissions we have now selected are fixed until explicitly
13119            // changed.
13120            ps.installPermissionsFixed = true;
13121        }
13122
13123        // Persist the runtime permissions state for users with changes. If permissions
13124        // were revoked because no app in the shared user declares them we have to
13125        // write synchronously to avoid losing runtime permissions state.
13126        for (int userId : changedRuntimePermissionUserIds) {
13127            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13128        }
13129    }
13130
13131    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13132        boolean allowed = false;
13133        final int NP = PackageParser.NEW_PERMISSIONS.length;
13134        for (int ip=0; ip<NP; ip++) {
13135            final PackageParser.NewPermissionInfo npi
13136                    = PackageParser.NEW_PERMISSIONS[ip];
13137            if (npi.name.equals(perm)
13138                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13139                allowed = true;
13140                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13141                        + pkg.packageName);
13142                break;
13143            }
13144        }
13145        return allowed;
13146    }
13147
13148    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13149            BasePermission bp, PermissionsState origPermissions) {
13150        boolean privilegedPermission = (bp.protectionLevel
13151                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13152        boolean privappPermissionsDisable =
13153                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13154        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13155        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13156        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13157                && !platformPackage && platformPermission) {
13158            ArraySet<String> wlPermissions = SystemConfig.getInstance()
13159                    .getPrivAppPermissions(pkg.packageName);
13160            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
13161            if (!whitelisted) {
13162                Slog.w(TAG, "Privileged permission " + perm + " for package "
13163                        + pkg.packageName + " - not in privapp-permissions whitelist");
13164                // Only report violations for apps on system image
13165                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13166                    if (mPrivappPermissionsViolations == null) {
13167                        mPrivappPermissionsViolations = new ArraySet<>();
13168                    }
13169                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13170                }
13171                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13172                    return false;
13173                }
13174            }
13175        }
13176        boolean allowed = (compareSignatures(
13177                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13178                        == PackageManager.SIGNATURE_MATCH)
13179                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13180                        == PackageManager.SIGNATURE_MATCH);
13181        if (!allowed && privilegedPermission) {
13182            if (isSystemApp(pkg)) {
13183                // For updated system applications, a system permission
13184                // is granted only if it had been defined by the original application.
13185                if (pkg.isUpdatedSystemApp()) {
13186                    final PackageSetting sysPs = mSettings
13187                            .getDisabledSystemPkgLPr(pkg.packageName);
13188                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13189                        // If the original was granted this permission, we take
13190                        // that grant decision as read and propagate it to the
13191                        // update.
13192                        if (sysPs.isPrivileged()) {
13193                            allowed = true;
13194                        }
13195                    } else {
13196                        // The system apk may have been updated with an older
13197                        // version of the one on the data partition, but which
13198                        // granted a new system permission that it didn't have
13199                        // before.  In this case we do want to allow the app to
13200                        // now get the new permission if the ancestral apk is
13201                        // privileged to get it.
13202                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13203                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13204                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13205                                    allowed = true;
13206                                    break;
13207                                }
13208                            }
13209                        }
13210                        // Also if a privileged parent package on the system image or any of
13211                        // its children requested a privileged permission, the updated child
13212                        // packages can also get the permission.
13213                        if (pkg.parentPackage != null) {
13214                            final PackageSetting disabledSysParentPs = mSettings
13215                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13216                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13217                                    && disabledSysParentPs.isPrivileged()) {
13218                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13219                                    allowed = true;
13220                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13221                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13222                                    for (int i = 0; i < count; i++) {
13223                                        PackageParser.Package disabledSysChildPkg =
13224                                                disabledSysParentPs.pkg.childPackages.get(i);
13225                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13226                                                perm)) {
13227                                            allowed = true;
13228                                            break;
13229                                        }
13230                                    }
13231                                }
13232                            }
13233                        }
13234                    }
13235                } else {
13236                    allowed = isPrivilegedApp(pkg);
13237                }
13238            }
13239        }
13240        if (!allowed) {
13241            if (!allowed && (bp.protectionLevel
13242                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13243                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13244                // If this was a previously normal/dangerous permission that got moved
13245                // to a system permission as part of the runtime permission redesign, then
13246                // we still want to blindly grant it to old apps.
13247                allowed = true;
13248            }
13249            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13250                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13251                // If this permission is to be granted to the system installer and
13252                // this app is an installer, then it gets the permission.
13253                allowed = true;
13254            }
13255            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13256                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13257                // If this permission is to be granted to the system verifier and
13258                // this app is a verifier, then it gets the permission.
13259                allowed = true;
13260            }
13261            if (!allowed && (bp.protectionLevel
13262                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13263                    && isSystemApp(pkg)) {
13264                // Any pre-installed system app is allowed to get this permission.
13265                allowed = true;
13266            }
13267            if (!allowed && (bp.protectionLevel
13268                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13269                // For development permissions, a development permission
13270                // is granted only if it was already granted.
13271                allowed = origPermissions.hasInstallPermission(perm);
13272            }
13273            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13274                    && pkg.packageName.equals(mSetupWizardPackage)) {
13275                // If this permission is to be granted to the system setup wizard and
13276                // this app is a setup wizard, then it gets the permission.
13277                allowed = true;
13278            }
13279        }
13280        return allowed;
13281    }
13282
13283    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13284        final int permCount = pkg.requestedPermissions.size();
13285        for (int j = 0; j < permCount; j++) {
13286            String requestedPermission = pkg.requestedPermissions.get(j);
13287            if (permission.equals(requestedPermission)) {
13288                return true;
13289            }
13290        }
13291        return false;
13292    }
13293
13294    final class ActivityIntentResolver
13295            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13296        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13297                boolean defaultOnly, int userId) {
13298            if (!sUserManager.exists(userId)) return null;
13299            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13300            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13301        }
13302
13303        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13304                int userId) {
13305            if (!sUserManager.exists(userId)) return null;
13306            mFlags = flags;
13307            return super.queryIntent(intent, resolvedType,
13308                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13309                    userId);
13310        }
13311
13312        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13313                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13314            if (!sUserManager.exists(userId)) return null;
13315            if (packageActivities == null) {
13316                return null;
13317            }
13318            mFlags = flags;
13319            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13320            final int N = packageActivities.size();
13321            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13322                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13323
13324            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13325            for (int i = 0; i < N; ++i) {
13326                intentFilters = packageActivities.get(i).intents;
13327                if (intentFilters != null && intentFilters.size() > 0) {
13328                    PackageParser.ActivityIntentInfo[] array =
13329                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13330                    intentFilters.toArray(array);
13331                    listCut.add(array);
13332                }
13333            }
13334            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13335        }
13336
13337        /**
13338         * Finds a privileged activity that matches the specified activity names.
13339         */
13340        private PackageParser.Activity findMatchingActivity(
13341                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13342            for (PackageParser.Activity sysActivity : activityList) {
13343                if (sysActivity.info.name.equals(activityInfo.name)) {
13344                    return sysActivity;
13345                }
13346                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13347                    return sysActivity;
13348                }
13349                if (sysActivity.info.targetActivity != null) {
13350                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13351                        return sysActivity;
13352                    }
13353                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13354                        return sysActivity;
13355                    }
13356                }
13357            }
13358            return null;
13359        }
13360
13361        public class IterGenerator<E> {
13362            public Iterator<E> generate(ActivityIntentInfo info) {
13363                return null;
13364            }
13365        }
13366
13367        public class ActionIterGenerator extends IterGenerator<String> {
13368            @Override
13369            public Iterator<String> generate(ActivityIntentInfo info) {
13370                return info.actionsIterator();
13371            }
13372        }
13373
13374        public class CategoriesIterGenerator extends IterGenerator<String> {
13375            @Override
13376            public Iterator<String> generate(ActivityIntentInfo info) {
13377                return info.categoriesIterator();
13378            }
13379        }
13380
13381        public class SchemesIterGenerator extends IterGenerator<String> {
13382            @Override
13383            public Iterator<String> generate(ActivityIntentInfo info) {
13384                return info.schemesIterator();
13385            }
13386        }
13387
13388        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13389            @Override
13390            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13391                return info.authoritiesIterator();
13392            }
13393        }
13394
13395        /**
13396         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13397         * MODIFIED. Do not pass in a list that should not be changed.
13398         */
13399        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13400                IterGenerator<T> generator, Iterator<T> searchIterator) {
13401            // loop through the set of actions; every one must be found in the intent filter
13402            while (searchIterator.hasNext()) {
13403                // we must have at least one filter in the list to consider a match
13404                if (intentList.size() == 0) {
13405                    break;
13406                }
13407
13408                final T searchAction = searchIterator.next();
13409
13410                // loop through the set of intent filters
13411                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13412                while (intentIter.hasNext()) {
13413                    final ActivityIntentInfo intentInfo = intentIter.next();
13414                    boolean selectionFound = false;
13415
13416                    // loop through the intent filter's selection criteria; at least one
13417                    // of them must match the searched criteria
13418                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13419                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13420                        final T intentSelection = intentSelectionIter.next();
13421                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13422                            selectionFound = true;
13423                            break;
13424                        }
13425                    }
13426
13427                    // the selection criteria wasn't found in this filter's set; this filter
13428                    // is not a potential match
13429                    if (!selectionFound) {
13430                        intentIter.remove();
13431                    }
13432                }
13433            }
13434        }
13435
13436        private boolean isProtectedAction(ActivityIntentInfo filter) {
13437            final Iterator<String> actionsIter = filter.actionsIterator();
13438            while (actionsIter != null && actionsIter.hasNext()) {
13439                final String filterAction = actionsIter.next();
13440                if (PROTECTED_ACTIONS.contains(filterAction)) {
13441                    return true;
13442                }
13443            }
13444            return false;
13445        }
13446
13447        /**
13448         * Adjusts the priority of the given intent filter according to policy.
13449         * <p>
13450         * <ul>
13451         * <li>The priority for non privileged applications is capped to '0'</li>
13452         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13453         * <li>The priority for unbundled updates to privileged applications is capped to the
13454         *      priority defined on the system partition</li>
13455         * </ul>
13456         * <p>
13457         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13458         * allowed to obtain any priority on any action.
13459         */
13460        private void adjustPriority(
13461                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13462            // nothing to do; priority is fine as-is
13463            if (intent.getPriority() <= 0) {
13464                return;
13465            }
13466
13467            final ActivityInfo activityInfo = intent.activity.info;
13468            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13469
13470            final boolean privilegedApp =
13471                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13472            if (!privilegedApp) {
13473                // non-privileged applications can never define a priority >0
13474                if (DEBUG_FILTERS) {
13475                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13476                            + " package: " + applicationInfo.packageName
13477                            + " activity: " + intent.activity.className
13478                            + " origPrio: " + intent.getPriority());
13479                }
13480                intent.setPriority(0);
13481                return;
13482            }
13483
13484            if (systemActivities == null) {
13485                // the system package is not disabled; we're parsing the system partition
13486                if (isProtectedAction(intent)) {
13487                    if (mDeferProtectedFilters) {
13488                        // We can't deal with these just yet. No component should ever obtain a
13489                        // >0 priority for a protected actions, with ONE exception -- the setup
13490                        // wizard. The setup wizard, however, cannot be known until we're able to
13491                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13492                        // until all intent filters have been processed. Chicken, meet egg.
13493                        // Let the filter temporarily have a high priority and rectify the
13494                        // priorities after all system packages have been scanned.
13495                        mProtectedFilters.add(intent);
13496                        if (DEBUG_FILTERS) {
13497                            Slog.i(TAG, "Protected action; save for later;"
13498                                    + " package: " + applicationInfo.packageName
13499                                    + " activity: " + intent.activity.className
13500                                    + " origPrio: " + intent.getPriority());
13501                        }
13502                        return;
13503                    } else {
13504                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13505                            Slog.i(TAG, "No setup wizard;"
13506                                + " All protected intents capped to priority 0");
13507                        }
13508                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13509                            if (DEBUG_FILTERS) {
13510                                Slog.i(TAG, "Found setup wizard;"
13511                                    + " allow priority " + intent.getPriority() + ";"
13512                                    + " package: " + intent.activity.info.packageName
13513                                    + " activity: " + intent.activity.className
13514                                    + " priority: " + intent.getPriority());
13515                            }
13516                            // setup wizard gets whatever it wants
13517                            return;
13518                        }
13519                        if (DEBUG_FILTERS) {
13520                            Slog.i(TAG, "Protected action; cap priority to 0;"
13521                                    + " package: " + intent.activity.info.packageName
13522                                    + " activity: " + intent.activity.className
13523                                    + " origPrio: " + intent.getPriority());
13524                        }
13525                        intent.setPriority(0);
13526                        return;
13527                    }
13528                }
13529                // privileged apps on the system image get whatever priority they request
13530                return;
13531            }
13532
13533            // privileged app unbundled update ... try to find the same activity
13534            final PackageParser.Activity foundActivity =
13535                    findMatchingActivity(systemActivities, activityInfo);
13536            if (foundActivity == null) {
13537                // this is a new activity; it cannot obtain >0 priority
13538                if (DEBUG_FILTERS) {
13539                    Slog.i(TAG, "New activity; cap priority to 0;"
13540                            + " package: " + applicationInfo.packageName
13541                            + " activity: " + intent.activity.className
13542                            + " origPrio: " + intent.getPriority());
13543                }
13544                intent.setPriority(0);
13545                return;
13546            }
13547
13548            // found activity, now check for filter equivalence
13549
13550            // a shallow copy is enough; we modify the list, not its contents
13551            final List<ActivityIntentInfo> intentListCopy =
13552                    new ArrayList<>(foundActivity.intents);
13553            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13554
13555            // find matching action subsets
13556            final Iterator<String> actionsIterator = intent.actionsIterator();
13557            if (actionsIterator != null) {
13558                getIntentListSubset(
13559                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13560                if (intentListCopy.size() == 0) {
13561                    // no more intents to match; we're not equivalent
13562                    if (DEBUG_FILTERS) {
13563                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13564                                + " package: " + applicationInfo.packageName
13565                                + " activity: " + intent.activity.className
13566                                + " origPrio: " + intent.getPriority());
13567                    }
13568                    intent.setPriority(0);
13569                    return;
13570                }
13571            }
13572
13573            // find matching category subsets
13574            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13575            if (categoriesIterator != null) {
13576                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13577                        categoriesIterator);
13578                if (intentListCopy.size() == 0) {
13579                    // no more intents to match; we're not equivalent
13580                    if (DEBUG_FILTERS) {
13581                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13582                                + " package: " + applicationInfo.packageName
13583                                + " activity: " + intent.activity.className
13584                                + " origPrio: " + intent.getPriority());
13585                    }
13586                    intent.setPriority(0);
13587                    return;
13588                }
13589            }
13590
13591            // find matching schemes subsets
13592            final Iterator<String> schemesIterator = intent.schemesIterator();
13593            if (schemesIterator != null) {
13594                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13595                        schemesIterator);
13596                if (intentListCopy.size() == 0) {
13597                    // no more intents to match; we're not equivalent
13598                    if (DEBUG_FILTERS) {
13599                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13600                                + " package: " + applicationInfo.packageName
13601                                + " activity: " + intent.activity.className
13602                                + " origPrio: " + intent.getPriority());
13603                    }
13604                    intent.setPriority(0);
13605                    return;
13606                }
13607            }
13608
13609            // find matching authorities subsets
13610            final Iterator<IntentFilter.AuthorityEntry>
13611                    authoritiesIterator = intent.authoritiesIterator();
13612            if (authoritiesIterator != null) {
13613                getIntentListSubset(intentListCopy,
13614                        new AuthoritiesIterGenerator(),
13615                        authoritiesIterator);
13616                if (intentListCopy.size() == 0) {
13617                    // no more intents to match; we're not equivalent
13618                    if (DEBUG_FILTERS) {
13619                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13620                                + " package: " + applicationInfo.packageName
13621                                + " activity: " + intent.activity.className
13622                                + " origPrio: " + intent.getPriority());
13623                    }
13624                    intent.setPriority(0);
13625                    return;
13626                }
13627            }
13628
13629            // we found matching filter(s); app gets the max priority of all intents
13630            int cappedPriority = 0;
13631            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13632                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13633            }
13634            if (intent.getPriority() > cappedPriority) {
13635                if (DEBUG_FILTERS) {
13636                    Slog.i(TAG, "Found matching filter(s);"
13637                            + " cap priority to " + cappedPriority + ";"
13638                            + " package: " + applicationInfo.packageName
13639                            + " activity: " + intent.activity.className
13640                            + " origPrio: " + intent.getPriority());
13641                }
13642                intent.setPriority(cappedPriority);
13643                return;
13644            }
13645            // all this for nothing; the requested priority was <= what was on the system
13646        }
13647
13648        public final void addActivity(PackageParser.Activity a, String type) {
13649            mActivities.put(a.getComponentName(), a);
13650            if (DEBUG_SHOW_INFO)
13651                Log.v(
13652                TAG, "  " + type + " " +
13653                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13654            if (DEBUG_SHOW_INFO)
13655                Log.v(TAG, "    Class=" + a.info.name);
13656            final int NI = a.intents.size();
13657            for (int j=0; j<NI; j++) {
13658                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13659                if ("activity".equals(type)) {
13660                    final PackageSetting ps =
13661                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13662                    final List<PackageParser.Activity> systemActivities =
13663                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13664                    adjustPriority(systemActivities, intent);
13665                }
13666                if (DEBUG_SHOW_INFO) {
13667                    Log.v(TAG, "    IntentFilter:");
13668                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13669                }
13670                if (!intent.debugCheck()) {
13671                    Log.w(TAG, "==> For Activity " + a.info.name);
13672                }
13673                addFilter(intent);
13674            }
13675        }
13676
13677        public final void removeActivity(PackageParser.Activity a, String type) {
13678            mActivities.remove(a.getComponentName());
13679            if (DEBUG_SHOW_INFO) {
13680                Log.v(TAG, "  " + type + " "
13681                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13682                                : a.info.name) + ":");
13683                Log.v(TAG, "    Class=" + a.info.name);
13684            }
13685            final int NI = a.intents.size();
13686            for (int j=0; j<NI; j++) {
13687                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13688                if (DEBUG_SHOW_INFO) {
13689                    Log.v(TAG, "    IntentFilter:");
13690                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13691                }
13692                removeFilter(intent);
13693            }
13694        }
13695
13696        @Override
13697        protected boolean allowFilterResult(
13698                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13699            ActivityInfo filterAi = filter.activity.info;
13700            for (int i=dest.size()-1; i>=0; i--) {
13701                ActivityInfo destAi = dest.get(i).activityInfo;
13702                if (destAi.name == filterAi.name
13703                        && destAi.packageName == filterAi.packageName) {
13704                    return false;
13705                }
13706            }
13707            return true;
13708        }
13709
13710        @Override
13711        protected ActivityIntentInfo[] newArray(int size) {
13712            return new ActivityIntentInfo[size];
13713        }
13714
13715        @Override
13716        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13717            if (!sUserManager.exists(userId)) return true;
13718            PackageParser.Package p = filter.activity.owner;
13719            if (p != null) {
13720                PackageSetting ps = (PackageSetting)p.mExtras;
13721                if (ps != null) {
13722                    // System apps are never considered stopped for purposes of
13723                    // filtering, because there may be no way for the user to
13724                    // actually re-launch them.
13725                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13726                            && ps.getStopped(userId);
13727                }
13728            }
13729            return false;
13730        }
13731
13732        @Override
13733        protected boolean isPackageForFilter(String packageName,
13734                PackageParser.ActivityIntentInfo info) {
13735            return packageName.equals(info.activity.owner.packageName);
13736        }
13737
13738        @Override
13739        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13740                int match, int userId) {
13741            if (!sUserManager.exists(userId)) return null;
13742            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13743                return null;
13744            }
13745            final PackageParser.Activity activity = info.activity;
13746            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13747            if (ps == null) {
13748                return null;
13749            }
13750            final PackageUserState userState = ps.readUserState(userId);
13751            ActivityInfo ai =
13752                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13753            if (ai == null) {
13754                return null;
13755            }
13756            final boolean matchExplicitlyVisibleOnly =
13757                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13758            final boolean matchVisibleToInstantApp =
13759                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13760            final boolean componentVisible =
13761                    matchVisibleToInstantApp
13762                    && info.isVisibleToInstantApp()
13763                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13764            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13765            // throw out filters that aren't visible to ephemeral apps
13766            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13767                return null;
13768            }
13769            // throw out instant app filters if we're not explicitly requesting them
13770            if (!matchInstantApp && userState.instantApp) {
13771                return null;
13772            }
13773            // throw out instant app filters if updates are available; will trigger
13774            // instant app resolution
13775            if (userState.instantApp && ps.isUpdateAvailable()) {
13776                return null;
13777            }
13778            final ResolveInfo res = new ResolveInfo();
13779            res.activityInfo = ai;
13780            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13781                res.filter = info;
13782            }
13783            if (info != null) {
13784                res.handleAllWebDataURI = info.handleAllWebDataURI();
13785            }
13786            res.priority = info.getPriority();
13787            res.preferredOrder = activity.owner.mPreferredOrder;
13788            //System.out.println("Result: " + res.activityInfo.className +
13789            //                   " = " + res.priority);
13790            res.match = match;
13791            res.isDefault = info.hasDefault;
13792            res.labelRes = info.labelRes;
13793            res.nonLocalizedLabel = info.nonLocalizedLabel;
13794            if (userNeedsBadging(userId)) {
13795                res.noResourceId = true;
13796            } else {
13797                res.icon = info.icon;
13798            }
13799            res.iconResourceId = info.icon;
13800            res.system = res.activityInfo.applicationInfo.isSystemApp();
13801            res.isInstantAppAvailable = userState.instantApp;
13802            return res;
13803        }
13804
13805        @Override
13806        protected void sortResults(List<ResolveInfo> results) {
13807            Collections.sort(results, mResolvePrioritySorter);
13808        }
13809
13810        @Override
13811        protected void dumpFilter(PrintWriter out, String prefix,
13812                PackageParser.ActivityIntentInfo filter) {
13813            out.print(prefix); out.print(
13814                    Integer.toHexString(System.identityHashCode(filter.activity)));
13815                    out.print(' ');
13816                    filter.activity.printComponentShortName(out);
13817                    out.print(" filter ");
13818                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13819        }
13820
13821        @Override
13822        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13823            return filter.activity;
13824        }
13825
13826        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13827            PackageParser.Activity activity = (PackageParser.Activity)label;
13828            out.print(prefix); out.print(
13829                    Integer.toHexString(System.identityHashCode(activity)));
13830                    out.print(' ');
13831                    activity.printComponentShortName(out);
13832            if (count > 1) {
13833                out.print(" ("); out.print(count); out.print(" filters)");
13834            }
13835            out.println();
13836        }
13837
13838        // Keys are String (activity class name), values are Activity.
13839        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13840                = new ArrayMap<ComponentName, PackageParser.Activity>();
13841        private int mFlags;
13842    }
13843
13844    private final class ServiceIntentResolver
13845            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13846        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13847                boolean defaultOnly, int userId) {
13848            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13849            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13850        }
13851
13852        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13853                int userId) {
13854            if (!sUserManager.exists(userId)) return null;
13855            mFlags = flags;
13856            return super.queryIntent(intent, resolvedType,
13857                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13858                    userId);
13859        }
13860
13861        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13862                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13863            if (!sUserManager.exists(userId)) return null;
13864            if (packageServices == null) {
13865                return null;
13866            }
13867            mFlags = flags;
13868            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13869            final int N = packageServices.size();
13870            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13871                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13872
13873            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13874            for (int i = 0; i < N; ++i) {
13875                intentFilters = packageServices.get(i).intents;
13876                if (intentFilters != null && intentFilters.size() > 0) {
13877                    PackageParser.ServiceIntentInfo[] array =
13878                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13879                    intentFilters.toArray(array);
13880                    listCut.add(array);
13881                }
13882            }
13883            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13884        }
13885
13886        public final void addService(PackageParser.Service s) {
13887            mServices.put(s.getComponentName(), s);
13888            if (DEBUG_SHOW_INFO) {
13889                Log.v(TAG, "  "
13890                        + (s.info.nonLocalizedLabel != null
13891                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13892                Log.v(TAG, "    Class=" + s.info.name);
13893            }
13894            final int NI = s.intents.size();
13895            int j;
13896            for (j=0; j<NI; j++) {
13897                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13898                if (DEBUG_SHOW_INFO) {
13899                    Log.v(TAG, "    IntentFilter:");
13900                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13901                }
13902                if (!intent.debugCheck()) {
13903                    Log.w(TAG, "==> For Service " + s.info.name);
13904                }
13905                addFilter(intent);
13906            }
13907        }
13908
13909        public final void removeService(PackageParser.Service s) {
13910            mServices.remove(s.getComponentName());
13911            if (DEBUG_SHOW_INFO) {
13912                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13913                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13914                Log.v(TAG, "    Class=" + s.info.name);
13915            }
13916            final int NI = s.intents.size();
13917            int j;
13918            for (j=0; j<NI; j++) {
13919                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13920                if (DEBUG_SHOW_INFO) {
13921                    Log.v(TAG, "    IntentFilter:");
13922                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13923                }
13924                removeFilter(intent);
13925            }
13926        }
13927
13928        @Override
13929        protected boolean allowFilterResult(
13930                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13931            ServiceInfo filterSi = filter.service.info;
13932            for (int i=dest.size()-1; i>=0; i--) {
13933                ServiceInfo destAi = dest.get(i).serviceInfo;
13934                if (destAi.name == filterSi.name
13935                        && destAi.packageName == filterSi.packageName) {
13936                    return false;
13937                }
13938            }
13939            return true;
13940        }
13941
13942        @Override
13943        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13944            return new PackageParser.ServiceIntentInfo[size];
13945        }
13946
13947        @Override
13948        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13949            if (!sUserManager.exists(userId)) return true;
13950            PackageParser.Package p = filter.service.owner;
13951            if (p != null) {
13952                PackageSetting ps = (PackageSetting)p.mExtras;
13953                if (ps != null) {
13954                    // System apps are never considered stopped for purposes of
13955                    // filtering, because there may be no way for the user to
13956                    // actually re-launch them.
13957                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13958                            && ps.getStopped(userId);
13959                }
13960            }
13961            return false;
13962        }
13963
13964        @Override
13965        protected boolean isPackageForFilter(String packageName,
13966                PackageParser.ServiceIntentInfo info) {
13967            return packageName.equals(info.service.owner.packageName);
13968        }
13969
13970        @Override
13971        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13972                int match, int userId) {
13973            if (!sUserManager.exists(userId)) return null;
13974            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13975            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13976                return null;
13977            }
13978            final PackageParser.Service service = info.service;
13979            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13980            if (ps == null) {
13981                return null;
13982            }
13983            final PackageUserState userState = ps.readUserState(userId);
13984            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13985                    userState, userId);
13986            if (si == null) {
13987                return null;
13988            }
13989            final boolean matchVisibleToInstantApp =
13990                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13991            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13992            // throw out filters that aren't visible to ephemeral apps
13993            if (matchVisibleToInstantApp
13994                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13995                return null;
13996            }
13997            // throw out ephemeral filters if we're not explicitly requesting them
13998            if (!isInstantApp && userState.instantApp) {
13999                return null;
14000            }
14001            // throw out instant app filters if updates are available; will trigger
14002            // instant app resolution
14003            if (userState.instantApp && ps.isUpdateAvailable()) {
14004                return null;
14005            }
14006            final ResolveInfo res = new ResolveInfo();
14007            res.serviceInfo = si;
14008            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
14009                res.filter = filter;
14010            }
14011            res.priority = info.getPriority();
14012            res.preferredOrder = service.owner.mPreferredOrder;
14013            res.match = match;
14014            res.isDefault = info.hasDefault;
14015            res.labelRes = info.labelRes;
14016            res.nonLocalizedLabel = info.nonLocalizedLabel;
14017            res.icon = info.icon;
14018            res.system = res.serviceInfo.applicationInfo.isSystemApp();
14019            return res;
14020        }
14021
14022        @Override
14023        protected void sortResults(List<ResolveInfo> results) {
14024            Collections.sort(results, mResolvePrioritySorter);
14025        }
14026
14027        @Override
14028        protected void dumpFilter(PrintWriter out, String prefix,
14029                PackageParser.ServiceIntentInfo filter) {
14030            out.print(prefix); out.print(
14031                    Integer.toHexString(System.identityHashCode(filter.service)));
14032                    out.print(' ');
14033                    filter.service.printComponentShortName(out);
14034                    out.print(" filter ");
14035                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14036        }
14037
14038        @Override
14039        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14040            return filter.service;
14041        }
14042
14043        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14044            PackageParser.Service service = (PackageParser.Service)label;
14045            out.print(prefix); out.print(
14046                    Integer.toHexString(System.identityHashCode(service)));
14047                    out.print(' ');
14048                    service.printComponentShortName(out);
14049            if (count > 1) {
14050                out.print(" ("); out.print(count); out.print(" filters)");
14051            }
14052            out.println();
14053        }
14054
14055//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14056//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14057//            final List<ResolveInfo> retList = Lists.newArrayList();
14058//            while (i.hasNext()) {
14059//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14060//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14061//                    retList.add(resolveInfo);
14062//                }
14063//            }
14064//            return retList;
14065//        }
14066
14067        // Keys are String (activity class name), values are Activity.
14068        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14069                = new ArrayMap<ComponentName, PackageParser.Service>();
14070        private int mFlags;
14071    }
14072
14073    private final class ProviderIntentResolver
14074            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14075        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14076                boolean defaultOnly, int userId) {
14077            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14078            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14079        }
14080
14081        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14082                int userId) {
14083            if (!sUserManager.exists(userId))
14084                return null;
14085            mFlags = flags;
14086            return super.queryIntent(intent, resolvedType,
14087                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14088                    userId);
14089        }
14090
14091        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14092                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14093            if (!sUserManager.exists(userId))
14094                return null;
14095            if (packageProviders == null) {
14096                return null;
14097            }
14098            mFlags = flags;
14099            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14100            final int N = packageProviders.size();
14101            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14102                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14103
14104            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14105            for (int i = 0; i < N; ++i) {
14106                intentFilters = packageProviders.get(i).intents;
14107                if (intentFilters != null && intentFilters.size() > 0) {
14108                    PackageParser.ProviderIntentInfo[] array =
14109                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14110                    intentFilters.toArray(array);
14111                    listCut.add(array);
14112                }
14113            }
14114            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14115        }
14116
14117        public final void addProvider(PackageParser.Provider p) {
14118            if (mProviders.containsKey(p.getComponentName())) {
14119                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14120                return;
14121            }
14122
14123            mProviders.put(p.getComponentName(), p);
14124            if (DEBUG_SHOW_INFO) {
14125                Log.v(TAG, "  "
14126                        + (p.info.nonLocalizedLabel != null
14127                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14128                Log.v(TAG, "    Class=" + p.info.name);
14129            }
14130            final int NI = p.intents.size();
14131            int j;
14132            for (j = 0; j < NI; j++) {
14133                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14134                if (DEBUG_SHOW_INFO) {
14135                    Log.v(TAG, "    IntentFilter:");
14136                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14137                }
14138                if (!intent.debugCheck()) {
14139                    Log.w(TAG, "==> For Provider " + p.info.name);
14140                }
14141                addFilter(intent);
14142            }
14143        }
14144
14145        public final void removeProvider(PackageParser.Provider p) {
14146            mProviders.remove(p.getComponentName());
14147            if (DEBUG_SHOW_INFO) {
14148                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14149                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14150                Log.v(TAG, "    Class=" + p.info.name);
14151            }
14152            final int NI = p.intents.size();
14153            int j;
14154            for (j = 0; j < NI; j++) {
14155                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14156                if (DEBUG_SHOW_INFO) {
14157                    Log.v(TAG, "    IntentFilter:");
14158                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14159                }
14160                removeFilter(intent);
14161            }
14162        }
14163
14164        @Override
14165        protected boolean allowFilterResult(
14166                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14167            ProviderInfo filterPi = filter.provider.info;
14168            for (int i = dest.size() - 1; i >= 0; i--) {
14169                ProviderInfo destPi = dest.get(i).providerInfo;
14170                if (destPi.name == filterPi.name
14171                        && destPi.packageName == filterPi.packageName) {
14172                    return false;
14173                }
14174            }
14175            return true;
14176        }
14177
14178        @Override
14179        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14180            return new PackageParser.ProviderIntentInfo[size];
14181        }
14182
14183        @Override
14184        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14185            if (!sUserManager.exists(userId))
14186                return true;
14187            PackageParser.Package p = filter.provider.owner;
14188            if (p != null) {
14189                PackageSetting ps = (PackageSetting) p.mExtras;
14190                if (ps != null) {
14191                    // System apps are never considered stopped for purposes of
14192                    // filtering, because there may be no way for the user to
14193                    // actually re-launch them.
14194                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14195                            && ps.getStopped(userId);
14196                }
14197            }
14198            return false;
14199        }
14200
14201        @Override
14202        protected boolean isPackageForFilter(String packageName,
14203                PackageParser.ProviderIntentInfo info) {
14204            return packageName.equals(info.provider.owner.packageName);
14205        }
14206
14207        @Override
14208        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14209                int match, int userId) {
14210            if (!sUserManager.exists(userId))
14211                return null;
14212            final PackageParser.ProviderIntentInfo info = filter;
14213            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14214                return null;
14215            }
14216            final PackageParser.Provider provider = info.provider;
14217            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14218            if (ps == null) {
14219                return null;
14220            }
14221            final PackageUserState userState = ps.readUserState(userId);
14222            final boolean matchVisibleToInstantApp =
14223                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14224            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14225            // throw out filters that aren't visible to instant applications
14226            if (matchVisibleToInstantApp
14227                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14228                return null;
14229            }
14230            // throw out instant application filters if we're not explicitly requesting them
14231            if (!isInstantApp && userState.instantApp) {
14232                return null;
14233            }
14234            // throw out instant application filters if updates are available; will trigger
14235            // instant application resolution
14236            if (userState.instantApp && ps.isUpdateAvailable()) {
14237                return null;
14238            }
14239            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14240                    userState, userId);
14241            if (pi == null) {
14242                return null;
14243            }
14244            final ResolveInfo res = new ResolveInfo();
14245            res.providerInfo = pi;
14246            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14247                res.filter = filter;
14248            }
14249            res.priority = info.getPriority();
14250            res.preferredOrder = provider.owner.mPreferredOrder;
14251            res.match = match;
14252            res.isDefault = info.hasDefault;
14253            res.labelRes = info.labelRes;
14254            res.nonLocalizedLabel = info.nonLocalizedLabel;
14255            res.icon = info.icon;
14256            res.system = res.providerInfo.applicationInfo.isSystemApp();
14257            return res;
14258        }
14259
14260        @Override
14261        protected void sortResults(List<ResolveInfo> results) {
14262            Collections.sort(results, mResolvePrioritySorter);
14263        }
14264
14265        @Override
14266        protected void dumpFilter(PrintWriter out, String prefix,
14267                PackageParser.ProviderIntentInfo filter) {
14268            out.print(prefix);
14269            out.print(
14270                    Integer.toHexString(System.identityHashCode(filter.provider)));
14271            out.print(' ');
14272            filter.provider.printComponentShortName(out);
14273            out.print(" filter ");
14274            out.println(Integer.toHexString(System.identityHashCode(filter)));
14275        }
14276
14277        @Override
14278        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14279            return filter.provider;
14280        }
14281
14282        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14283            PackageParser.Provider provider = (PackageParser.Provider)label;
14284            out.print(prefix); out.print(
14285                    Integer.toHexString(System.identityHashCode(provider)));
14286                    out.print(' ');
14287                    provider.printComponentShortName(out);
14288            if (count > 1) {
14289                out.print(" ("); out.print(count); out.print(" filters)");
14290            }
14291            out.println();
14292        }
14293
14294        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14295                = new ArrayMap<ComponentName, PackageParser.Provider>();
14296        private int mFlags;
14297    }
14298
14299    static final class EphemeralIntentResolver
14300            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14301        /**
14302         * The result that has the highest defined order. Ordering applies on a
14303         * per-package basis. Mapping is from package name to Pair of order and
14304         * EphemeralResolveInfo.
14305         * <p>
14306         * NOTE: This is implemented as a field variable for convenience and efficiency.
14307         * By having a field variable, we're able to track filter ordering as soon as
14308         * a non-zero order is defined. Otherwise, multiple loops across the result set
14309         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14310         * this needs to be contained entirely within {@link #filterResults}.
14311         */
14312        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14313
14314        @Override
14315        protected AuxiliaryResolveInfo[] newArray(int size) {
14316            return new AuxiliaryResolveInfo[size];
14317        }
14318
14319        @Override
14320        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14321            return true;
14322        }
14323
14324        @Override
14325        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14326                int userId) {
14327            if (!sUserManager.exists(userId)) {
14328                return null;
14329            }
14330            final String packageName = responseObj.resolveInfo.getPackageName();
14331            final Integer order = responseObj.getOrder();
14332            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14333                    mOrderResult.get(packageName);
14334            // ordering is enabled and this item's order isn't high enough
14335            if (lastOrderResult != null && lastOrderResult.first >= order) {
14336                return null;
14337            }
14338            final InstantAppResolveInfo res = responseObj.resolveInfo;
14339            if (order > 0) {
14340                // non-zero order, enable ordering
14341                mOrderResult.put(packageName, new Pair<>(order, res));
14342            }
14343            return responseObj;
14344        }
14345
14346        @Override
14347        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14348            // only do work if ordering is enabled [most of the time it won't be]
14349            if (mOrderResult.size() == 0) {
14350                return;
14351            }
14352            int resultSize = results.size();
14353            for (int i = 0; i < resultSize; i++) {
14354                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14355                final String packageName = info.getPackageName();
14356                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14357                if (savedInfo == null) {
14358                    // package doesn't having ordering
14359                    continue;
14360                }
14361                if (savedInfo.second == info) {
14362                    // circled back to the highest ordered item; remove from order list
14363                    mOrderResult.remove(savedInfo);
14364                    if (mOrderResult.size() == 0) {
14365                        // no more ordered items
14366                        break;
14367                    }
14368                    continue;
14369                }
14370                // item has a worse order, remove it from the result list
14371                results.remove(i);
14372                resultSize--;
14373                i--;
14374            }
14375        }
14376    }
14377
14378    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14379            new Comparator<ResolveInfo>() {
14380        public int compare(ResolveInfo r1, ResolveInfo r2) {
14381            int v1 = r1.priority;
14382            int v2 = r2.priority;
14383            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14384            if (v1 != v2) {
14385                return (v1 > v2) ? -1 : 1;
14386            }
14387            v1 = r1.preferredOrder;
14388            v2 = r2.preferredOrder;
14389            if (v1 != v2) {
14390                return (v1 > v2) ? -1 : 1;
14391            }
14392            if (r1.isDefault != r2.isDefault) {
14393                return r1.isDefault ? -1 : 1;
14394            }
14395            v1 = r1.match;
14396            v2 = r2.match;
14397            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14398            if (v1 != v2) {
14399                return (v1 > v2) ? -1 : 1;
14400            }
14401            if (r1.system != r2.system) {
14402                return r1.system ? -1 : 1;
14403            }
14404            if (r1.activityInfo != null) {
14405                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14406            }
14407            if (r1.serviceInfo != null) {
14408                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14409            }
14410            if (r1.providerInfo != null) {
14411                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14412            }
14413            return 0;
14414        }
14415    };
14416
14417    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14418            new Comparator<ProviderInfo>() {
14419        public int compare(ProviderInfo p1, ProviderInfo p2) {
14420            final int v1 = p1.initOrder;
14421            final int v2 = p2.initOrder;
14422            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14423        }
14424    };
14425
14426    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14427            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14428            final int[] userIds) {
14429        mHandler.post(new Runnable() {
14430            @Override
14431            public void run() {
14432                try {
14433                    final IActivityManager am = ActivityManager.getService();
14434                    if (am == null) return;
14435                    final int[] resolvedUserIds;
14436                    if (userIds == null) {
14437                        resolvedUserIds = am.getRunningUserIds();
14438                    } else {
14439                        resolvedUserIds = userIds;
14440                    }
14441                    for (int id : resolvedUserIds) {
14442                        final Intent intent = new Intent(action,
14443                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14444                        if (extras != null) {
14445                            intent.putExtras(extras);
14446                        }
14447                        if (targetPkg != null) {
14448                            intent.setPackage(targetPkg);
14449                        }
14450                        // Modify the UID when posting to other users
14451                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14452                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14453                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14454                            intent.putExtra(Intent.EXTRA_UID, uid);
14455                        }
14456                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14457                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14458                        if (DEBUG_BROADCASTS) {
14459                            RuntimeException here = new RuntimeException("here");
14460                            here.fillInStackTrace();
14461                            Slog.d(TAG, "Sending to user " + id + ": "
14462                                    + intent.toShortString(false, true, false, false)
14463                                    + " " + intent.getExtras(), here);
14464                        }
14465                        am.broadcastIntent(null, intent, null, finishedReceiver,
14466                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14467                                null, finishedReceiver != null, false, id);
14468                    }
14469                } catch (RemoteException ex) {
14470                }
14471            }
14472        });
14473    }
14474
14475    /**
14476     * Check if the external storage media is available. This is true if there
14477     * is a mounted external storage medium or if the external storage is
14478     * emulated.
14479     */
14480    private boolean isExternalMediaAvailable() {
14481        return mMediaMounted || Environment.isExternalStorageEmulated();
14482    }
14483
14484    @Override
14485    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14486        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14487            return null;
14488        }
14489        // writer
14490        synchronized (mPackages) {
14491            if (!isExternalMediaAvailable()) {
14492                // If the external storage is no longer mounted at this point,
14493                // the caller may not have been able to delete all of this
14494                // packages files and can not delete any more.  Bail.
14495                return null;
14496            }
14497            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14498            if (lastPackage != null) {
14499                pkgs.remove(lastPackage);
14500            }
14501            if (pkgs.size() > 0) {
14502                return pkgs.get(0);
14503            }
14504        }
14505        return null;
14506    }
14507
14508    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14509        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14510                userId, andCode ? 1 : 0, packageName);
14511        if (mSystemReady) {
14512            msg.sendToTarget();
14513        } else {
14514            if (mPostSystemReadyMessages == null) {
14515                mPostSystemReadyMessages = new ArrayList<>();
14516            }
14517            mPostSystemReadyMessages.add(msg);
14518        }
14519    }
14520
14521    void startCleaningPackages() {
14522        // reader
14523        if (!isExternalMediaAvailable()) {
14524            return;
14525        }
14526        synchronized (mPackages) {
14527            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14528                return;
14529            }
14530        }
14531        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14532        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14533        IActivityManager am = ActivityManager.getService();
14534        if (am != null) {
14535            int dcsUid = -1;
14536            synchronized (mPackages) {
14537                if (!mDefaultContainerWhitelisted) {
14538                    mDefaultContainerWhitelisted = true;
14539                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14540                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14541                }
14542            }
14543            try {
14544                if (dcsUid > 0) {
14545                    am.backgroundWhitelistUid(dcsUid);
14546                }
14547                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14548                        UserHandle.USER_SYSTEM);
14549            } catch (RemoteException e) {
14550            }
14551        }
14552    }
14553
14554    @Override
14555    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14556            int installFlags, String installerPackageName, int userId) {
14557        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14558
14559        final int callingUid = Binder.getCallingUid();
14560        enforceCrossUserPermission(callingUid, userId,
14561                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14562
14563        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14564            try {
14565                if (observer != null) {
14566                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14567                }
14568            } catch (RemoteException re) {
14569            }
14570            return;
14571        }
14572
14573        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14574            installFlags |= PackageManager.INSTALL_FROM_ADB;
14575
14576        } else {
14577            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14578            // about installerPackageName.
14579
14580            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14581            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14582        }
14583
14584        UserHandle user;
14585        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14586            user = UserHandle.ALL;
14587        } else {
14588            user = new UserHandle(userId);
14589        }
14590
14591        // Only system components can circumvent runtime permissions when installing.
14592        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14593                && mContext.checkCallingOrSelfPermission(Manifest.permission
14594                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14595            throw new SecurityException("You need the "
14596                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14597                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14598        }
14599
14600        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14601                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14602            throw new IllegalArgumentException(
14603                    "New installs into ASEC containers no longer supported");
14604        }
14605
14606        final File originFile = new File(originPath);
14607        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14608
14609        final Message msg = mHandler.obtainMessage(INIT_COPY);
14610        final VerificationInfo verificationInfo = new VerificationInfo(
14611                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14612        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14613                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14614                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14615                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14616        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14617        msg.obj = params;
14618
14619        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14620                System.identityHashCode(msg.obj));
14621        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14622                System.identityHashCode(msg.obj));
14623
14624        mHandler.sendMessage(msg);
14625    }
14626
14627
14628    /**
14629     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14630     * it is acting on behalf on an enterprise or the user).
14631     *
14632     * Note that the ordering of the conditionals in this method is important. The checks we perform
14633     * are as follows, in this order:
14634     *
14635     * 1) If the install is being performed by a system app, we can trust the app to have set the
14636     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14637     *    what it is.
14638     * 2) If the install is being performed by a device or profile owner app, the install reason
14639     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14640     *    set the install reason correctly. If the app targets an older SDK version where install
14641     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14642     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14643     * 3) In all other cases, the install is being performed by a regular app that is neither part
14644     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14645     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14646     *    set to enterprise policy and if so, change it to unknown instead.
14647     */
14648    private int fixUpInstallReason(String installerPackageName, int installerUid,
14649            int installReason) {
14650        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14651                == PERMISSION_GRANTED) {
14652            // If the install is being performed by a system app, we trust that app to have set the
14653            // install reason correctly.
14654            return installReason;
14655        }
14656
14657        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14658            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14659        if (dpm != null) {
14660            ComponentName owner = null;
14661            try {
14662                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14663                if (owner == null) {
14664                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14665                }
14666            } catch (RemoteException e) {
14667            }
14668            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14669                // If the install is being performed by a device or profile owner, the install
14670                // reason should be enterprise policy.
14671                return PackageManager.INSTALL_REASON_POLICY;
14672            }
14673        }
14674
14675        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14676            // If the install is being performed by a regular app (i.e. neither system app nor
14677            // device or profile owner), we have no reason to believe that the app is acting on
14678            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14679            // change it to unknown instead.
14680            return PackageManager.INSTALL_REASON_UNKNOWN;
14681        }
14682
14683        // If the install is being performed by a regular app and the install reason was set to any
14684        // value but enterprise policy, leave the install reason unchanged.
14685        return installReason;
14686    }
14687
14688    void installStage(String packageName, File stagedDir, String stagedCid,
14689            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14690            String installerPackageName, int installerUid, UserHandle user,
14691            Certificate[][] certificates) {
14692        if (DEBUG_EPHEMERAL) {
14693            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14694                Slog.d(TAG, "Ephemeral install of " + packageName);
14695            }
14696        }
14697        final VerificationInfo verificationInfo = new VerificationInfo(
14698                sessionParams.originatingUri, sessionParams.referrerUri,
14699                sessionParams.originatingUid, installerUid);
14700
14701        final OriginInfo origin;
14702        if (stagedDir != null) {
14703            origin = OriginInfo.fromStagedFile(stagedDir);
14704        } else {
14705            origin = OriginInfo.fromStagedContainer(stagedCid);
14706        }
14707
14708        final Message msg = mHandler.obtainMessage(INIT_COPY);
14709        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14710                sessionParams.installReason);
14711        final InstallParams params = new InstallParams(origin, null, observer,
14712                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14713                verificationInfo, user, sessionParams.abiOverride,
14714                sessionParams.grantedRuntimePermissions, certificates, installReason);
14715        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14716        msg.obj = params;
14717
14718        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14719                System.identityHashCode(msg.obj));
14720        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14721                System.identityHashCode(msg.obj));
14722
14723        mHandler.sendMessage(msg);
14724    }
14725
14726    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14727            int userId) {
14728        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14729        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14730                false /*startReceiver*/, pkgSetting.appId, userId);
14731
14732        // Send a session commit broadcast
14733        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14734        info.installReason = pkgSetting.getInstallReason(userId);
14735        info.appPackageName = packageName;
14736        sendSessionCommitBroadcast(info, userId);
14737    }
14738
14739    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14740            boolean includeStopped, int appId, int... userIds) {
14741        if (ArrayUtils.isEmpty(userIds)) {
14742            return;
14743        }
14744        Bundle extras = new Bundle(1);
14745        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14746        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14747
14748        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14749                packageName, extras, 0, null, null, userIds);
14750        if (sendBootCompleted) {
14751            mHandler.post(() -> {
14752                        for (int userId : userIds) {
14753                            sendBootCompletedBroadcastToSystemApp(
14754                                    packageName, includeStopped, userId);
14755                        }
14756                    }
14757            );
14758        }
14759    }
14760
14761    /**
14762     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14763     * automatically without needing an explicit launch.
14764     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14765     */
14766    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14767            int userId) {
14768        // If user is not running, the app didn't miss any broadcast
14769        if (!mUserManagerInternal.isUserRunning(userId)) {
14770            return;
14771        }
14772        final IActivityManager am = ActivityManager.getService();
14773        try {
14774            // Deliver LOCKED_BOOT_COMPLETED first
14775            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14776                    .setPackage(packageName);
14777            if (includeStopped) {
14778                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14779            }
14780            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14781            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14782                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14783
14784            // Deliver BOOT_COMPLETED only if user is unlocked
14785            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14786                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14787                if (includeStopped) {
14788                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14789                }
14790                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14791                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14792            }
14793        } catch (RemoteException e) {
14794            throw e.rethrowFromSystemServer();
14795        }
14796    }
14797
14798    @Override
14799    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14800            int userId) {
14801        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14802        PackageSetting pkgSetting;
14803        final int callingUid = Binder.getCallingUid();
14804        enforceCrossUserPermission(callingUid, userId,
14805                true /* requireFullPermission */, true /* checkShell */,
14806                "setApplicationHiddenSetting for user " + userId);
14807
14808        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14809            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14810            return false;
14811        }
14812
14813        long callingId = Binder.clearCallingIdentity();
14814        try {
14815            boolean sendAdded = false;
14816            boolean sendRemoved = false;
14817            // writer
14818            synchronized (mPackages) {
14819                pkgSetting = mSettings.mPackages.get(packageName);
14820                if (pkgSetting == null) {
14821                    return false;
14822                }
14823                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14824                    return false;
14825                }
14826                // Do not allow "android" is being disabled
14827                if ("android".equals(packageName)) {
14828                    Slog.w(TAG, "Cannot hide package: android");
14829                    return false;
14830                }
14831                // Cannot hide static shared libs as they are considered
14832                // a part of the using app (emulating static linking). Also
14833                // static libs are installed always on internal storage.
14834                PackageParser.Package pkg = mPackages.get(packageName);
14835                if (pkg != null && pkg.staticSharedLibName != null) {
14836                    Slog.w(TAG, "Cannot hide package: " + packageName
14837                            + " providing static shared library: "
14838                            + pkg.staticSharedLibName);
14839                    return false;
14840                }
14841                // Only allow protected packages to hide themselves.
14842                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14843                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14844                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14845                    return false;
14846                }
14847
14848                if (pkgSetting.getHidden(userId) != hidden) {
14849                    pkgSetting.setHidden(hidden, userId);
14850                    mSettings.writePackageRestrictionsLPr(userId);
14851                    if (hidden) {
14852                        sendRemoved = true;
14853                    } else {
14854                        sendAdded = true;
14855                    }
14856                }
14857            }
14858            if (sendAdded) {
14859                sendPackageAddedForUser(packageName, pkgSetting, userId);
14860                return true;
14861            }
14862            if (sendRemoved) {
14863                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14864                        "hiding pkg");
14865                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14866                return true;
14867            }
14868        } finally {
14869            Binder.restoreCallingIdentity(callingId);
14870        }
14871        return false;
14872    }
14873
14874    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14875            int userId) {
14876        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14877        info.removedPackage = packageName;
14878        info.installerPackageName = pkgSetting.installerPackageName;
14879        info.removedUsers = new int[] {userId};
14880        info.broadcastUsers = new int[] {userId};
14881        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14882        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14883    }
14884
14885    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14886        if (pkgList.length > 0) {
14887            Bundle extras = new Bundle(1);
14888            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14889
14890            sendPackageBroadcast(
14891                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14892                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14893                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14894                    new int[] {userId});
14895        }
14896    }
14897
14898    /**
14899     * Returns true if application is not found or there was an error. Otherwise it returns
14900     * the hidden state of the package for the given user.
14901     */
14902    @Override
14903    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14904        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14905        final int callingUid = Binder.getCallingUid();
14906        enforceCrossUserPermission(callingUid, userId,
14907                true /* requireFullPermission */, false /* checkShell */,
14908                "getApplicationHidden for user " + userId);
14909        PackageSetting ps;
14910        long callingId = Binder.clearCallingIdentity();
14911        try {
14912            // writer
14913            synchronized (mPackages) {
14914                ps = mSettings.mPackages.get(packageName);
14915                if (ps == null) {
14916                    return true;
14917                }
14918                if (filterAppAccessLPr(ps, callingUid, userId)) {
14919                    return true;
14920                }
14921                return ps.getHidden(userId);
14922            }
14923        } finally {
14924            Binder.restoreCallingIdentity(callingId);
14925        }
14926    }
14927
14928    /**
14929     * @hide
14930     */
14931    @Override
14932    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14933            int installReason) {
14934        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14935                null);
14936        PackageSetting pkgSetting;
14937        final int callingUid = Binder.getCallingUid();
14938        enforceCrossUserPermission(callingUid, userId,
14939                true /* requireFullPermission */, true /* checkShell */,
14940                "installExistingPackage for user " + userId);
14941        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14942            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14943        }
14944
14945        long callingId = Binder.clearCallingIdentity();
14946        try {
14947            boolean installed = false;
14948            final boolean instantApp =
14949                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14950            final boolean fullApp =
14951                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14952
14953            // writer
14954            synchronized (mPackages) {
14955                pkgSetting = mSettings.mPackages.get(packageName);
14956                if (pkgSetting == null) {
14957                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14958                }
14959                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14960                    // only allow the existing package to be used if it's installed as a full
14961                    // application for at least one user
14962                    boolean installAllowed = false;
14963                    for (int checkUserId : sUserManager.getUserIds()) {
14964                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14965                        if (installAllowed) {
14966                            break;
14967                        }
14968                    }
14969                    if (!installAllowed) {
14970                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14971                    }
14972                }
14973                if (!pkgSetting.getInstalled(userId)) {
14974                    pkgSetting.setInstalled(true, userId);
14975                    pkgSetting.setHidden(false, userId);
14976                    pkgSetting.setInstallReason(installReason, userId);
14977                    mSettings.writePackageRestrictionsLPr(userId);
14978                    mSettings.writeKernelMappingLPr(pkgSetting);
14979                    installed = true;
14980                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14981                    // upgrade app from instant to full; we don't allow app downgrade
14982                    installed = true;
14983                }
14984                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14985            }
14986
14987            if (installed) {
14988                if (pkgSetting.pkg != null) {
14989                    synchronized (mInstallLock) {
14990                        // We don't need to freeze for a brand new install
14991                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14992                    }
14993                }
14994                sendPackageAddedForUser(packageName, pkgSetting, userId);
14995                synchronized (mPackages) {
14996                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14997                }
14998            }
14999        } finally {
15000            Binder.restoreCallingIdentity(callingId);
15001        }
15002
15003        return PackageManager.INSTALL_SUCCEEDED;
15004    }
15005
15006    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
15007            boolean instantApp, boolean fullApp) {
15008        // no state specified; do nothing
15009        if (!instantApp && !fullApp) {
15010            return;
15011        }
15012        if (userId != UserHandle.USER_ALL) {
15013            if (instantApp && !pkgSetting.getInstantApp(userId)) {
15014                pkgSetting.setInstantApp(true /*instantApp*/, userId);
15015            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15016                pkgSetting.setInstantApp(false /*instantApp*/, userId);
15017            }
15018        } else {
15019            for (int currentUserId : sUserManager.getUserIds()) {
15020                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
15021                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
15022                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
15023                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
15024                }
15025            }
15026        }
15027    }
15028
15029    boolean isUserRestricted(int userId, String restrictionKey) {
15030        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15031        if (restrictions.getBoolean(restrictionKey, false)) {
15032            Log.w(TAG, "User is restricted: " + restrictionKey);
15033            return true;
15034        }
15035        return false;
15036    }
15037
15038    @Override
15039    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15040            int userId) {
15041        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15042        final int callingUid = Binder.getCallingUid();
15043        enforceCrossUserPermission(callingUid, userId,
15044                true /* requireFullPermission */, true /* checkShell */,
15045                "setPackagesSuspended for user " + userId);
15046
15047        if (ArrayUtils.isEmpty(packageNames)) {
15048            return packageNames;
15049        }
15050
15051        // List of package names for whom the suspended state has changed.
15052        List<String> changedPackages = new ArrayList<>(packageNames.length);
15053        // List of package names for whom the suspended state is not set as requested in this
15054        // method.
15055        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15056        long callingId = Binder.clearCallingIdentity();
15057        try {
15058            for (int i = 0; i < packageNames.length; i++) {
15059                String packageName = packageNames[i];
15060                boolean changed = false;
15061                final int appId;
15062                synchronized (mPackages) {
15063                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15064                    if (pkgSetting == null
15065                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15066                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15067                                + "\". Skipping suspending/un-suspending.");
15068                        unactionedPackages.add(packageName);
15069                        continue;
15070                    }
15071                    appId = pkgSetting.appId;
15072                    if (pkgSetting.getSuspended(userId) != suspended) {
15073                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15074                            unactionedPackages.add(packageName);
15075                            continue;
15076                        }
15077                        pkgSetting.setSuspended(suspended, userId);
15078                        mSettings.writePackageRestrictionsLPr(userId);
15079                        changed = true;
15080                        changedPackages.add(packageName);
15081                    }
15082                }
15083
15084                if (changed && suspended) {
15085                    killApplication(packageName, UserHandle.getUid(userId, appId),
15086                            "suspending package");
15087                }
15088            }
15089        } finally {
15090            Binder.restoreCallingIdentity(callingId);
15091        }
15092
15093        if (!changedPackages.isEmpty()) {
15094            sendPackagesSuspendedForUser(changedPackages.toArray(
15095                    new String[changedPackages.size()]), userId, suspended);
15096        }
15097
15098        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15099    }
15100
15101    @Override
15102    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15103        final int callingUid = Binder.getCallingUid();
15104        enforceCrossUserPermission(callingUid, userId,
15105                true /* requireFullPermission */, false /* checkShell */,
15106                "isPackageSuspendedForUser for user " + userId);
15107        synchronized (mPackages) {
15108            final PackageSetting ps = mSettings.mPackages.get(packageName);
15109            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15110                throw new IllegalArgumentException("Unknown target package: " + packageName);
15111            }
15112            return ps.getSuspended(userId);
15113        }
15114    }
15115
15116    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15117        if (isPackageDeviceAdmin(packageName, userId)) {
15118            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15119                    + "\": has an active device admin");
15120            return false;
15121        }
15122
15123        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15124        if (packageName.equals(activeLauncherPackageName)) {
15125            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15126                    + "\": contains the active launcher");
15127            return false;
15128        }
15129
15130        if (packageName.equals(mRequiredInstallerPackage)) {
15131            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15132                    + "\": required for package installation");
15133            return false;
15134        }
15135
15136        if (packageName.equals(mRequiredUninstallerPackage)) {
15137            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15138                    + "\": required for package uninstallation");
15139            return false;
15140        }
15141
15142        if (packageName.equals(mRequiredVerifierPackage)) {
15143            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15144                    + "\": required for package verification");
15145            return false;
15146        }
15147
15148        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15149            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15150                    + "\": is the default dialer");
15151            return false;
15152        }
15153
15154        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15155            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15156                    + "\": protected package");
15157            return false;
15158        }
15159
15160        // Cannot suspend static shared libs as they are considered
15161        // a part of the using app (emulating static linking). Also
15162        // static libs are installed always on internal storage.
15163        PackageParser.Package pkg = mPackages.get(packageName);
15164        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15165            Slog.w(TAG, "Cannot suspend package: " + packageName
15166                    + " providing static shared library: "
15167                    + pkg.staticSharedLibName);
15168            return false;
15169        }
15170
15171        return true;
15172    }
15173
15174    private String getActiveLauncherPackageName(int userId) {
15175        Intent intent = new Intent(Intent.ACTION_MAIN);
15176        intent.addCategory(Intent.CATEGORY_HOME);
15177        ResolveInfo resolveInfo = resolveIntent(
15178                intent,
15179                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15180                PackageManager.MATCH_DEFAULT_ONLY,
15181                userId);
15182
15183        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15184    }
15185
15186    private String getDefaultDialerPackageName(int userId) {
15187        synchronized (mPackages) {
15188            return mSettings.getDefaultDialerPackageNameLPw(userId);
15189        }
15190    }
15191
15192    @Override
15193    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15194        mContext.enforceCallingOrSelfPermission(
15195                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15196                "Only package verification agents can verify applications");
15197
15198        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15199        final PackageVerificationResponse response = new PackageVerificationResponse(
15200                verificationCode, Binder.getCallingUid());
15201        msg.arg1 = id;
15202        msg.obj = response;
15203        mHandler.sendMessage(msg);
15204    }
15205
15206    @Override
15207    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15208            long millisecondsToDelay) {
15209        mContext.enforceCallingOrSelfPermission(
15210                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15211                "Only package verification agents can extend verification timeouts");
15212
15213        final PackageVerificationState state = mPendingVerification.get(id);
15214        final PackageVerificationResponse response = new PackageVerificationResponse(
15215                verificationCodeAtTimeout, Binder.getCallingUid());
15216
15217        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15218            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15219        }
15220        if (millisecondsToDelay < 0) {
15221            millisecondsToDelay = 0;
15222        }
15223        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15224                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15225            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15226        }
15227
15228        if ((state != null) && !state.timeoutExtended()) {
15229            state.extendTimeout();
15230
15231            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15232            msg.arg1 = id;
15233            msg.obj = response;
15234            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15235        }
15236    }
15237
15238    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15239            int verificationCode, UserHandle user) {
15240        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15241        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15242        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15243        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15244        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15245
15246        mContext.sendBroadcastAsUser(intent, user,
15247                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15248    }
15249
15250    private ComponentName matchComponentForVerifier(String packageName,
15251            List<ResolveInfo> receivers) {
15252        ActivityInfo targetReceiver = null;
15253
15254        final int NR = receivers.size();
15255        for (int i = 0; i < NR; i++) {
15256            final ResolveInfo info = receivers.get(i);
15257            if (info.activityInfo == null) {
15258                continue;
15259            }
15260
15261            if (packageName.equals(info.activityInfo.packageName)) {
15262                targetReceiver = info.activityInfo;
15263                break;
15264            }
15265        }
15266
15267        if (targetReceiver == null) {
15268            return null;
15269        }
15270
15271        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15272    }
15273
15274    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15275            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15276        if (pkgInfo.verifiers.length == 0) {
15277            return null;
15278        }
15279
15280        final int N = pkgInfo.verifiers.length;
15281        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15282        for (int i = 0; i < N; i++) {
15283            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15284
15285            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15286                    receivers);
15287            if (comp == null) {
15288                continue;
15289            }
15290
15291            final int verifierUid = getUidForVerifier(verifierInfo);
15292            if (verifierUid == -1) {
15293                continue;
15294            }
15295
15296            if (DEBUG_VERIFY) {
15297                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15298                        + " with the correct signature");
15299            }
15300            sufficientVerifiers.add(comp);
15301            verificationState.addSufficientVerifier(verifierUid);
15302        }
15303
15304        return sufficientVerifiers;
15305    }
15306
15307    private int getUidForVerifier(VerifierInfo verifierInfo) {
15308        synchronized (mPackages) {
15309            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15310            if (pkg == null) {
15311                return -1;
15312            } else if (pkg.mSignatures.length != 1) {
15313                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15314                        + " has more than one signature; ignoring");
15315                return -1;
15316            }
15317
15318            /*
15319             * If the public key of the package's signature does not match
15320             * our expected public key, then this is a different package and
15321             * we should skip.
15322             */
15323
15324            final byte[] expectedPublicKey;
15325            try {
15326                final Signature verifierSig = pkg.mSignatures[0];
15327                final PublicKey publicKey = verifierSig.getPublicKey();
15328                expectedPublicKey = publicKey.getEncoded();
15329            } catch (CertificateException e) {
15330                return -1;
15331            }
15332
15333            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15334
15335            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15336                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15337                        + " does not have the expected public key; ignoring");
15338                return -1;
15339            }
15340
15341            return pkg.applicationInfo.uid;
15342        }
15343    }
15344
15345    @Override
15346    public void finishPackageInstall(int token, boolean didLaunch) {
15347        enforceSystemOrRoot("Only the system is allowed to finish installs");
15348
15349        if (DEBUG_INSTALL) {
15350            Slog.v(TAG, "BM finishing package install for " + token);
15351        }
15352        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15353
15354        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15355        mHandler.sendMessage(msg);
15356    }
15357
15358    /**
15359     * Get the verification agent timeout.  Used for both the APK verifier and the
15360     * intent filter verifier.
15361     *
15362     * @return verification timeout in milliseconds
15363     */
15364    private long getVerificationTimeout() {
15365        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15366                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15367                DEFAULT_VERIFICATION_TIMEOUT);
15368    }
15369
15370    /**
15371     * Get the default verification agent response code.
15372     *
15373     * @return default verification response code
15374     */
15375    private int getDefaultVerificationResponse(UserHandle user) {
15376        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15377            return PackageManager.VERIFICATION_REJECT;
15378        }
15379        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15380                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15381                DEFAULT_VERIFICATION_RESPONSE);
15382    }
15383
15384    /**
15385     * Check whether or not package verification has been enabled.
15386     *
15387     * @return true if verification should be performed
15388     */
15389    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15390        if (!DEFAULT_VERIFY_ENABLE) {
15391            return false;
15392        }
15393
15394        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15395
15396        // Check if installing from ADB
15397        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15398            // Do not run verification in a test harness environment
15399            if (ActivityManager.isRunningInTestHarness()) {
15400                return false;
15401            }
15402            if (ensureVerifyAppsEnabled) {
15403                return true;
15404            }
15405            // Check if the developer does not want package verification for ADB installs
15406            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15407                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15408                return false;
15409            }
15410        } else {
15411            // only when not installed from ADB, skip verification for instant apps when
15412            // the installer and verifier are the same.
15413            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15414                if (mInstantAppInstallerActivity != null
15415                        && mInstantAppInstallerActivity.packageName.equals(
15416                                mRequiredVerifierPackage)) {
15417                    try {
15418                        mContext.getSystemService(AppOpsManager.class)
15419                                .checkPackage(installerUid, mRequiredVerifierPackage);
15420                        if (DEBUG_VERIFY) {
15421                            Slog.i(TAG, "disable verification for instant app");
15422                        }
15423                        return false;
15424                    } catch (SecurityException ignore) { }
15425                }
15426            }
15427        }
15428
15429        if (ensureVerifyAppsEnabled) {
15430            return true;
15431        }
15432
15433        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15434                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15435    }
15436
15437    @Override
15438    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15439            throws RemoteException {
15440        mContext.enforceCallingOrSelfPermission(
15441                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15442                "Only intentfilter verification agents can verify applications");
15443
15444        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15445        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15446                Binder.getCallingUid(), verificationCode, failedDomains);
15447        msg.arg1 = id;
15448        msg.obj = response;
15449        mHandler.sendMessage(msg);
15450    }
15451
15452    @Override
15453    public int getIntentVerificationStatus(String packageName, int userId) {
15454        final int callingUid = Binder.getCallingUid();
15455        if (UserHandle.getUserId(callingUid) != userId) {
15456            mContext.enforceCallingOrSelfPermission(
15457                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15458                    "getIntentVerificationStatus" + userId);
15459        }
15460        if (getInstantAppPackageName(callingUid) != null) {
15461            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15462        }
15463        synchronized (mPackages) {
15464            final PackageSetting ps = mSettings.mPackages.get(packageName);
15465            if (ps == null
15466                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15467                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15468            }
15469            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15470        }
15471    }
15472
15473    @Override
15474    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15475        mContext.enforceCallingOrSelfPermission(
15476                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15477
15478        boolean result = false;
15479        synchronized (mPackages) {
15480            final PackageSetting ps = mSettings.mPackages.get(packageName);
15481            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15482                return false;
15483            }
15484            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15485        }
15486        if (result) {
15487            scheduleWritePackageRestrictionsLocked(userId);
15488        }
15489        return result;
15490    }
15491
15492    @Override
15493    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15494            String packageName) {
15495        final int callingUid = Binder.getCallingUid();
15496        if (getInstantAppPackageName(callingUid) != null) {
15497            return ParceledListSlice.emptyList();
15498        }
15499        synchronized (mPackages) {
15500            final PackageSetting ps = mSettings.mPackages.get(packageName);
15501            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15502                return ParceledListSlice.emptyList();
15503            }
15504            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15505        }
15506    }
15507
15508    @Override
15509    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15510        if (TextUtils.isEmpty(packageName)) {
15511            return ParceledListSlice.emptyList();
15512        }
15513        final int callingUid = Binder.getCallingUid();
15514        final int callingUserId = UserHandle.getUserId(callingUid);
15515        synchronized (mPackages) {
15516            PackageParser.Package pkg = mPackages.get(packageName);
15517            if (pkg == null || pkg.activities == null) {
15518                return ParceledListSlice.emptyList();
15519            }
15520            if (pkg.mExtras == null) {
15521                return ParceledListSlice.emptyList();
15522            }
15523            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15524            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15525                return ParceledListSlice.emptyList();
15526            }
15527            final int count = pkg.activities.size();
15528            ArrayList<IntentFilter> result = new ArrayList<>();
15529            for (int n=0; n<count; n++) {
15530                PackageParser.Activity activity = pkg.activities.get(n);
15531                if (activity.intents != null && activity.intents.size() > 0) {
15532                    result.addAll(activity.intents);
15533                }
15534            }
15535            return new ParceledListSlice<>(result);
15536        }
15537    }
15538
15539    @Override
15540    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15541        mContext.enforceCallingOrSelfPermission(
15542                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15543        if (UserHandle.getCallingUserId() != userId) {
15544            mContext.enforceCallingOrSelfPermission(
15545                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15546        }
15547
15548        synchronized (mPackages) {
15549            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15550            if (packageName != null) {
15551                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15552                        packageName, userId);
15553            }
15554            return result;
15555        }
15556    }
15557
15558    @Override
15559    public String getDefaultBrowserPackageName(int userId) {
15560        if (UserHandle.getCallingUserId() != userId) {
15561            mContext.enforceCallingOrSelfPermission(
15562                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15563        }
15564        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15565            return null;
15566        }
15567        synchronized (mPackages) {
15568            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15569        }
15570    }
15571
15572    /**
15573     * Get the "allow unknown sources" setting.
15574     *
15575     * @return the current "allow unknown sources" setting
15576     */
15577    private int getUnknownSourcesSettings() {
15578        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15579                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15580                -1);
15581    }
15582
15583    @Override
15584    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15585        final int callingUid = Binder.getCallingUid();
15586        if (getInstantAppPackageName(callingUid) != null) {
15587            return;
15588        }
15589        // writer
15590        synchronized (mPackages) {
15591            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15592            if (targetPackageSetting == null
15593                    || filterAppAccessLPr(
15594                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15595                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15596            }
15597
15598            PackageSetting installerPackageSetting;
15599            if (installerPackageName != null) {
15600                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15601                if (installerPackageSetting == null) {
15602                    throw new IllegalArgumentException("Unknown installer package: "
15603                            + installerPackageName);
15604                }
15605            } else {
15606                installerPackageSetting = null;
15607            }
15608
15609            Signature[] callerSignature;
15610            Object obj = mSettings.getUserIdLPr(callingUid);
15611            if (obj != null) {
15612                if (obj instanceof SharedUserSetting) {
15613                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15614                } else if (obj instanceof PackageSetting) {
15615                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15616                } else {
15617                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15618                }
15619            } else {
15620                throw new SecurityException("Unknown calling UID: " + callingUid);
15621            }
15622
15623            // Verify: can't set installerPackageName to a package that is
15624            // not signed with the same cert as the caller.
15625            if (installerPackageSetting != null) {
15626                if (compareSignatures(callerSignature,
15627                        installerPackageSetting.signatures.mSignatures)
15628                        != PackageManager.SIGNATURE_MATCH) {
15629                    throw new SecurityException(
15630                            "Caller does not have same cert as new installer package "
15631                            + installerPackageName);
15632                }
15633            }
15634
15635            // Verify: if target already has an installer package, it must
15636            // be signed with the same cert as the caller.
15637            if (targetPackageSetting.installerPackageName != null) {
15638                PackageSetting setting = mSettings.mPackages.get(
15639                        targetPackageSetting.installerPackageName);
15640                // If the currently set package isn't valid, then it's always
15641                // okay to change it.
15642                if (setting != null) {
15643                    if (compareSignatures(callerSignature,
15644                            setting.signatures.mSignatures)
15645                            != PackageManager.SIGNATURE_MATCH) {
15646                        throw new SecurityException(
15647                                "Caller does not have same cert as old installer package "
15648                                + targetPackageSetting.installerPackageName);
15649                    }
15650                }
15651            }
15652
15653            // Okay!
15654            targetPackageSetting.installerPackageName = installerPackageName;
15655            if (installerPackageName != null) {
15656                mSettings.mInstallerPackages.add(installerPackageName);
15657            }
15658            scheduleWriteSettingsLocked();
15659        }
15660    }
15661
15662    @Override
15663    public void setApplicationCategoryHint(String packageName, int categoryHint,
15664            String callerPackageName) {
15665        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15666            throw new SecurityException("Instant applications don't have access to this method");
15667        }
15668        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15669                callerPackageName);
15670        synchronized (mPackages) {
15671            PackageSetting ps = mSettings.mPackages.get(packageName);
15672            if (ps == null) {
15673                throw new IllegalArgumentException("Unknown target package " + packageName);
15674            }
15675            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15676                throw new IllegalArgumentException("Unknown target package " + packageName);
15677            }
15678            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15679                throw new IllegalArgumentException("Calling package " + callerPackageName
15680                        + " is not installer for " + packageName);
15681            }
15682
15683            if (ps.categoryHint != categoryHint) {
15684                ps.categoryHint = categoryHint;
15685                scheduleWriteSettingsLocked();
15686            }
15687        }
15688    }
15689
15690    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15691        // Queue up an async operation since the package installation may take a little while.
15692        mHandler.post(new Runnable() {
15693            public void run() {
15694                mHandler.removeCallbacks(this);
15695                 // Result object to be returned
15696                PackageInstalledInfo res = new PackageInstalledInfo();
15697                res.setReturnCode(currentStatus);
15698                res.uid = -1;
15699                res.pkg = null;
15700                res.removedInfo = null;
15701                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15702                    args.doPreInstall(res.returnCode);
15703                    synchronized (mInstallLock) {
15704                        installPackageTracedLI(args, res);
15705                    }
15706                    args.doPostInstall(res.returnCode, res.uid);
15707                }
15708
15709                // A restore should be performed at this point if (a) the install
15710                // succeeded, (b) the operation is not an update, and (c) the new
15711                // package has not opted out of backup participation.
15712                final boolean update = res.removedInfo != null
15713                        && res.removedInfo.removedPackage != null;
15714                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15715                boolean doRestore = !update
15716                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15717
15718                // Set up the post-install work request bookkeeping.  This will be used
15719                // and cleaned up by the post-install event handling regardless of whether
15720                // there's a restore pass performed.  Token values are >= 1.
15721                int token;
15722                if (mNextInstallToken < 0) mNextInstallToken = 1;
15723                token = mNextInstallToken++;
15724
15725                PostInstallData data = new PostInstallData(args, res);
15726                mRunningInstalls.put(token, data);
15727                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15728
15729                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15730                    // Pass responsibility to the Backup Manager.  It will perform a
15731                    // restore if appropriate, then pass responsibility back to the
15732                    // Package Manager to run the post-install observer callbacks
15733                    // and broadcasts.
15734                    IBackupManager bm = IBackupManager.Stub.asInterface(
15735                            ServiceManager.getService(Context.BACKUP_SERVICE));
15736                    if (bm != null) {
15737                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15738                                + " to BM for possible restore");
15739                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15740                        try {
15741                            // TODO: http://b/22388012
15742                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15743                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15744                            } else {
15745                                doRestore = false;
15746                            }
15747                        } catch (RemoteException e) {
15748                            // can't happen; the backup manager is local
15749                        } catch (Exception e) {
15750                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15751                            doRestore = false;
15752                        }
15753                    } else {
15754                        Slog.e(TAG, "Backup Manager not found!");
15755                        doRestore = false;
15756                    }
15757                }
15758
15759                if (!doRestore) {
15760                    // No restore possible, or the Backup Manager was mysteriously not
15761                    // available -- just fire the post-install work request directly.
15762                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15763
15764                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15765
15766                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15767                    mHandler.sendMessage(msg);
15768                }
15769            }
15770        });
15771    }
15772
15773    /**
15774     * Callback from PackageSettings whenever an app is first transitioned out of the
15775     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15776     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15777     * here whether the app is the target of an ongoing install, and only send the
15778     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15779     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15780     * handling.
15781     */
15782    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15783        // Serialize this with the rest of the install-process message chain.  In the
15784        // restore-at-install case, this Runnable will necessarily run before the
15785        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15786        // are coherent.  In the non-restore case, the app has already completed install
15787        // and been launched through some other means, so it is not in a problematic
15788        // state for observers to see the FIRST_LAUNCH signal.
15789        mHandler.post(new Runnable() {
15790            @Override
15791            public void run() {
15792                for (int i = 0; i < mRunningInstalls.size(); i++) {
15793                    final PostInstallData data = mRunningInstalls.valueAt(i);
15794                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15795                        continue;
15796                    }
15797                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15798                        // right package; but is it for the right user?
15799                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15800                            if (userId == data.res.newUsers[uIndex]) {
15801                                if (DEBUG_BACKUP) {
15802                                    Slog.i(TAG, "Package " + pkgName
15803                                            + " being restored so deferring FIRST_LAUNCH");
15804                                }
15805                                return;
15806                            }
15807                        }
15808                    }
15809                }
15810                // didn't find it, so not being restored
15811                if (DEBUG_BACKUP) {
15812                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15813                }
15814                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15815            }
15816        });
15817    }
15818
15819    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15820        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15821                installerPkg, null, userIds);
15822    }
15823
15824    private abstract class HandlerParams {
15825        private static final int MAX_RETRIES = 4;
15826
15827        /**
15828         * Number of times startCopy() has been attempted and had a non-fatal
15829         * error.
15830         */
15831        private int mRetries = 0;
15832
15833        /** User handle for the user requesting the information or installation. */
15834        private final UserHandle mUser;
15835        String traceMethod;
15836        int traceCookie;
15837
15838        HandlerParams(UserHandle user) {
15839            mUser = user;
15840        }
15841
15842        UserHandle getUser() {
15843            return mUser;
15844        }
15845
15846        HandlerParams setTraceMethod(String traceMethod) {
15847            this.traceMethod = traceMethod;
15848            return this;
15849        }
15850
15851        HandlerParams setTraceCookie(int traceCookie) {
15852            this.traceCookie = traceCookie;
15853            return this;
15854        }
15855
15856        final boolean startCopy() {
15857            boolean res;
15858            try {
15859                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15860
15861                if (++mRetries > MAX_RETRIES) {
15862                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15863                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15864                    handleServiceError();
15865                    return false;
15866                } else {
15867                    handleStartCopy();
15868                    res = true;
15869                }
15870            } catch (RemoteException e) {
15871                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15872                mHandler.sendEmptyMessage(MCS_RECONNECT);
15873                res = false;
15874            }
15875            handleReturnCode();
15876            return res;
15877        }
15878
15879        final void serviceError() {
15880            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15881            handleServiceError();
15882            handleReturnCode();
15883        }
15884
15885        abstract void handleStartCopy() throws RemoteException;
15886        abstract void handleServiceError();
15887        abstract void handleReturnCode();
15888    }
15889
15890    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15891        for (File path : paths) {
15892            try {
15893                mcs.clearDirectory(path.getAbsolutePath());
15894            } catch (RemoteException e) {
15895            }
15896        }
15897    }
15898
15899    static class OriginInfo {
15900        /**
15901         * Location where install is coming from, before it has been
15902         * copied/renamed into place. This could be a single monolithic APK
15903         * file, or a cluster directory. This location may be untrusted.
15904         */
15905        final File file;
15906        final String cid;
15907
15908        /**
15909         * Flag indicating that {@link #file} or {@link #cid} has already been
15910         * staged, meaning downstream users don't need to defensively copy the
15911         * contents.
15912         */
15913        final boolean staged;
15914
15915        /**
15916         * Flag indicating that {@link #file} or {@link #cid} is an already
15917         * installed app that is being moved.
15918         */
15919        final boolean existing;
15920
15921        final String resolvedPath;
15922        final File resolvedFile;
15923
15924        static OriginInfo fromNothing() {
15925            return new OriginInfo(null, null, false, false);
15926        }
15927
15928        static OriginInfo fromUntrustedFile(File file) {
15929            return new OriginInfo(file, null, false, false);
15930        }
15931
15932        static OriginInfo fromExistingFile(File file) {
15933            return new OriginInfo(file, null, false, true);
15934        }
15935
15936        static OriginInfo fromStagedFile(File file) {
15937            return new OriginInfo(file, null, true, false);
15938        }
15939
15940        static OriginInfo fromStagedContainer(String cid) {
15941            return new OriginInfo(null, cid, true, false);
15942        }
15943
15944        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15945            this.file = file;
15946            this.cid = cid;
15947            this.staged = staged;
15948            this.existing = existing;
15949
15950            if (cid != null) {
15951                resolvedPath = PackageHelper.getSdDir(cid);
15952                resolvedFile = new File(resolvedPath);
15953            } else if (file != null) {
15954                resolvedPath = file.getAbsolutePath();
15955                resolvedFile = file;
15956            } else {
15957                resolvedPath = null;
15958                resolvedFile = null;
15959            }
15960        }
15961    }
15962
15963    static class MoveInfo {
15964        final int moveId;
15965        final String fromUuid;
15966        final String toUuid;
15967        final String packageName;
15968        final String dataAppName;
15969        final int appId;
15970        final String seinfo;
15971        final int targetSdkVersion;
15972
15973        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15974                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15975            this.moveId = moveId;
15976            this.fromUuid = fromUuid;
15977            this.toUuid = toUuid;
15978            this.packageName = packageName;
15979            this.dataAppName = dataAppName;
15980            this.appId = appId;
15981            this.seinfo = seinfo;
15982            this.targetSdkVersion = targetSdkVersion;
15983        }
15984    }
15985
15986    static class VerificationInfo {
15987        /** A constant used to indicate that a uid value is not present. */
15988        public static final int NO_UID = -1;
15989
15990        /** URI referencing where the package was downloaded from. */
15991        final Uri originatingUri;
15992
15993        /** HTTP referrer URI associated with the originatingURI. */
15994        final Uri referrer;
15995
15996        /** UID of the application that the install request originated from. */
15997        final int originatingUid;
15998
15999        /** UID of application requesting the install */
16000        final int installerUid;
16001
16002        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
16003            this.originatingUri = originatingUri;
16004            this.referrer = referrer;
16005            this.originatingUid = originatingUid;
16006            this.installerUid = installerUid;
16007        }
16008    }
16009
16010    class InstallParams extends HandlerParams {
16011        final OriginInfo origin;
16012        final MoveInfo move;
16013        final IPackageInstallObserver2 observer;
16014        int installFlags;
16015        final String installerPackageName;
16016        final String volumeUuid;
16017        private InstallArgs mArgs;
16018        private int mRet;
16019        final String packageAbiOverride;
16020        final String[] grantedRuntimePermissions;
16021        final VerificationInfo verificationInfo;
16022        final Certificate[][] certificates;
16023        final int installReason;
16024
16025        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16026                int installFlags, String installerPackageName, String volumeUuid,
16027                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16028                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16029            super(user);
16030            this.origin = origin;
16031            this.move = move;
16032            this.observer = observer;
16033            this.installFlags = installFlags;
16034            this.installerPackageName = installerPackageName;
16035            this.volumeUuid = volumeUuid;
16036            this.verificationInfo = verificationInfo;
16037            this.packageAbiOverride = packageAbiOverride;
16038            this.grantedRuntimePermissions = grantedPermissions;
16039            this.certificates = certificates;
16040            this.installReason = installReason;
16041        }
16042
16043        @Override
16044        public String toString() {
16045            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16046                    + " file=" + origin.file + " cid=" + origin.cid + "}";
16047        }
16048
16049        private int installLocationPolicy(PackageInfoLite pkgLite) {
16050            String packageName = pkgLite.packageName;
16051            int installLocation = pkgLite.installLocation;
16052            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16053            // reader
16054            synchronized (mPackages) {
16055                // Currently installed package which the new package is attempting to replace or
16056                // null if no such package is installed.
16057                PackageParser.Package installedPkg = mPackages.get(packageName);
16058                // Package which currently owns the data which the new package will own if installed.
16059                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16060                // will be null whereas dataOwnerPkg will contain information about the package
16061                // which was uninstalled while keeping its data.
16062                PackageParser.Package dataOwnerPkg = installedPkg;
16063                if (dataOwnerPkg  == null) {
16064                    PackageSetting ps = mSettings.mPackages.get(packageName);
16065                    if (ps != null) {
16066                        dataOwnerPkg = ps.pkg;
16067                    }
16068                }
16069
16070                if (dataOwnerPkg != null) {
16071                    // If installed, the package will get access to data left on the device by its
16072                    // predecessor. As a security measure, this is permited only if this is not a
16073                    // version downgrade or if the predecessor package is marked as debuggable and
16074                    // a downgrade is explicitly requested.
16075                    //
16076                    // On debuggable platform builds, downgrades are permitted even for
16077                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16078                    // not offer security guarantees and thus it's OK to disable some security
16079                    // mechanisms to make debugging/testing easier on those builds. However, even on
16080                    // debuggable builds downgrades of packages are permitted only if requested via
16081                    // installFlags. This is because we aim to keep the behavior of debuggable
16082                    // platform builds as close as possible to the behavior of non-debuggable
16083                    // platform builds.
16084                    final boolean downgradeRequested =
16085                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16086                    final boolean packageDebuggable =
16087                                (dataOwnerPkg.applicationInfo.flags
16088                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16089                    final boolean downgradePermitted =
16090                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16091                    if (!downgradePermitted) {
16092                        try {
16093                            checkDowngrade(dataOwnerPkg, pkgLite);
16094                        } catch (PackageManagerException e) {
16095                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16096                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16097                        }
16098                    }
16099                }
16100
16101                if (installedPkg != null) {
16102                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16103                        // Check for updated system application.
16104                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16105                            if (onSd) {
16106                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16107                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16108                            }
16109                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16110                        } else {
16111                            if (onSd) {
16112                                // Install flag overrides everything.
16113                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16114                            }
16115                            // If current upgrade specifies particular preference
16116                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16117                                // Application explicitly specified internal.
16118                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16119                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16120                                // App explictly prefers external. Let policy decide
16121                            } else {
16122                                // Prefer previous location
16123                                if (isExternal(installedPkg)) {
16124                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16125                                }
16126                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16127                            }
16128                        }
16129                    } else {
16130                        // Invalid install. Return error code
16131                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16132                    }
16133                }
16134            }
16135            // All the special cases have been taken care of.
16136            // Return result based on recommended install location.
16137            if (onSd) {
16138                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16139            }
16140            return pkgLite.recommendedInstallLocation;
16141        }
16142
16143        /*
16144         * Invoke remote method to get package information and install
16145         * location values. Override install location based on default
16146         * policy if needed and then create install arguments based
16147         * on the install location.
16148         */
16149        public void handleStartCopy() throws RemoteException {
16150            int ret = PackageManager.INSTALL_SUCCEEDED;
16151
16152            // If we're already staged, we've firmly committed to an install location
16153            if (origin.staged) {
16154                if (origin.file != null) {
16155                    installFlags |= PackageManager.INSTALL_INTERNAL;
16156                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16157                } else if (origin.cid != null) {
16158                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16159                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16160                } else {
16161                    throw new IllegalStateException("Invalid stage location");
16162                }
16163            }
16164
16165            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16166            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16167            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16168            PackageInfoLite pkgLite = null;
16169
16170            if (onInt && onSd) {
16171                // Check if both bits are set.
16172                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16173                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16174            } else if (onSd && ephemeral) {
16175                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16176                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16177            } else {
16178                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16179                        packageAbiOverride);
16180
16181                if (DEBUG_EPHEMERAL && ephemeral) {
16182                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16183                }
16184
16185                /*
16186                 * If we have too little free space, try to free cache
16187                 * before giving up.
16188                 */
16189                if (!origin.staged && pkgLite.recommendedInstallLocation
16190                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16191                    // TODO: focus freeing disk space on the target device
16192                    final StorageManager storage = StorageManager.from(mContext);
16193                    final long lowThreshold = storage.getStorageLowBytes(
16194                            Environment.getDataDirectory());
16195
16196                    final long sizeBytes = mContainerService.calculateInstalledSize(
16197                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16198
16199                    try {
16200                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16201                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16202                                installFlags, packageAbiOverride);
16203                    } catch (InstallerException e) {
16204                        Slog.w(TAG, "Failed to free cache", e);
16205                    }
16206
16207                    /*
16208                     * The cache free must have deleted the file we
16209                     * downloaded to install.
16210                     *
16211                     * TODO: fix the "freeCache" call to not delete
16212                     *       the file we care about.
16213                     */
16214                    if (pkgLite.recommendedInstallLocation
16215                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16216                        pkgLite.recommendedInstallLocation
16217                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16218                    }
16219                }
16220            }
16221
16222            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16223                int loc = pkgLite.recommendedInstallLocation;
16224                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16225                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16226                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16227                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16228                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16229                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16230                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16231                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16232                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16233                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16234                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16235                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16236                } else {
16237                    // Override with defaults if needed.
16238                    loc = installLocationPolicy(pkgLite);
16239                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16240                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16241                    } else if (!onSd && !onInt) {
16242                        // Override install location with flags
16243                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16244                            // Set the flag to install on external media.
16245                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16246                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16247                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16248                            if (DEBUG_EPHEMERAL) {
16249                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16250                            }
16251                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16252                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16253                                    |PackageManager.INSTALL_INTERNAL);
16254                        } else {
16255                            // Make sure the flag for installing on external
16256                            // media is unset
16257                            installFlags |= PackageManager.INSTALL_INTERNAL;
16258                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16259                        }
16260                    }
16261                }
16262            }
16263
16264            final InstallArgs args = createInstallArgs(this);
16265            mArgs = args;
16266
16267            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16268                // TODO: http://b/22976637
16269                // Apps installed for "all" users use the device owner to verify the app
16270                UserHandle verifierUser = getUser();
16271                if (verifierUser == UserHandle.ALL) {
16272                    verifierUser = UserHandle.SYSTEM;
16273                }
16274
16275                /*
16276                 * Determine if we have any installed package verifiers. If we
16277                 * do, then we'll defer to them to verify the packages.
16278                 */
16279                final int requiredUid = mRequiredVerifierPackage == null ? -1
16280                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16281                                verifierUser.getIdentifier());
16282                final int installerUid =
16283                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16284                if (!origin.existing && requiredUid != -1
16285                        && isVerificationEnabled(
16286                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16287                    final Intent verification = new Intent(
16288                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16289                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16290                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16291                            PACKAGE_MIME_TYPE);
16292                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16293
16294                    // Query all live verifiers based on current user state
16295                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16296                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16297                            false /*allowDynamicSplits*/);
16298
16299                    if (DEBUG_VERIFY) {
16300                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16301                                + verification.toString() + " with " + pkgLite.verifiers.length
16302                                + " optional verifiers");
16303                    }
16304
16305                    final int verificationId = mPendingVerificationToken++;
16306
16307                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16308
16309                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16310                            installerPackageName);
16311
16312                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16313                            installFlags);
16314
16315                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16316                            pkgLite.packageName);
16317
16318                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16319                            pkgLite.versionCode);
16320
16321                    if (verificationInfo != null) {
16322                        if (verificationInfo.originatingUri != null) {
16323                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16324                                    verificationInfo.originatingUri);
16325                        }
16326                        if (verificationInfo.referrer != null) {
16327                            verification.putExtra(Intent.EXTRA_REFERRER,
16328                                    verificationInfo.referrer);
16329                        }
16330                        if (verificationInfo.originatingUid >= 0) {
16331                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16332                                    verificationInfo.originatingUid);
16333                        }
16334                        if (verificationInfo.installerUid >= 0) {
16335                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16336                                    verificationInfo.installerUid);
16337                        }
16338                    }
16339
16340                    final PackageVerificationState verificationState = new PackageVerificationState(
16341                            requiredUid, args);
16342
16343                    mPendingVerification.append(verificationId, verificationState);
16344
16345                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16346                            receivers, verificationState);
16347
16348                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16349                    final long idleDuration = getVerificationTimeout();
16350
16351                    /*
16352                     * If any sufficient verifiers were listed in the package
16353                     * manifest, attempt to ask them.
16354                     */
16355                    if (sufficientVerifiers != null) {
16356                        final int N = sufficientVerifiers.size();
16357                        if (N == 0) {
16358                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16359                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16360                        } else {
16361                            for (int i = 0; i < N; i++) {
16362                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16363                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16364                                        verifierComponent.getPackageName(), idleDuration,
16365                                        verifierUser.getIdentifier(), false, "package verifier");
16366
16367                                final Intent sufficientIntent = new Intent(verification);
16368                                sufficientIntent.setComponent(verifierComponent);
16369                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16370                            }
16371                        }
16372                    }
16373
16374                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16375                            mRequiredVerifierPackage, receivers);
16376                    if (ret == PackageManager.INSTALL_SUCCEEDED
16377                            && mRequiredVerifierPackage != null) {
16378                        Trace.asyncTraceBegin(
16379                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16380                        /*
16381                         * Send the intent to the required verification agent,
16382                         * but only start the verification timeout after the
16383                         * target BroadcastReceivers have run.
16384                         */
16385                        verification.setComponent(requiredVerifierComponent);
16386                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16387                                mRequiredVerifierPackage, idleDuration,
16388                                verifierUser.getIdentifier(), false, "package verifier");
16389                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16390                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16391                                new BroadcastReceiver() {
16392                                    @Override
16393                                    public void onReceive(Context context, Intent intent) {
16394                                        final Message msg = mHandler
16395                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16396                                        msg.arg1 = verificationId;
16397                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16398                                    }
16399                                }, null, 0, null, null);
16400
16401                        /*
16402                         * We don't want the copy to proceed until verification
16403                         * succeeds, so null out this field.
16404                         */
16405                        mArgs = null;
16406                    }
16407                } else {
16408                    /*
16409                     * No package verification is enabled, so immediately start
16410                     * the remote call to initiate copy using temporary file.
16411                     */
16412                    ret = args.copyApk(mContainerService, true);
16413                }
16414            }
16415
16416            mRet = ret;
16417        }
16418
16419        @Override
16420        void handleReturnCode() {
16421            // If mArgs is null, then MCS couldn't be reached. When it
16422            // reconnects, it will try again to install. At that point, this
16423            // will succeed.
16424            if (mArgs != null) {
16425                processPendingInstall(mArgs, mRet);
16426            }
16427        }
16428
16429        @Override
16430        void handleServiceError() {
16431            mArgs = createInstallArgs(this);
16432            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16433        }
16434
16435        public boolean isForwardLocked() {
16436            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16437        }
16438    }
16439
16440    /**
16441     * Used during creation of InstallArgs
16442     *
16443     * @param installFlags package installation flags
16444     * @return true if should be installed on external storage
16445     */
16446    private static boolean installOnExternalAsec(int installFlags) {
16447        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16448            return false;
16449        }
16450        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16451            return true;
16452        }
16453        return false;
16454    }
16455
16456    /**
16457     * Used during creation of InstallArgs
16458     *
16459     * @param installFlags package installation flags
16460     * @return true if should be installed as forward locked
16461     */
16462    private static boolean installForwardLocked(int installFlags) {
16463        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16464    }
16465
16466    private InstallArgs createInstallArgs(InstallParams params) {
16467        if (params.move != null) {
16468            return new MoveInstallArgs(params);
16469        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16470            return new AsecInstallArgs(params);
16471        } else {
16472            return new FileInstallArgs(params);
16473        }
16474    }
16475
16476    /**
16477     * Create args that describe an existing installed package. Typically used
16478     * when cleaning up old installs, or used as a move source.
16479     */
16480    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16481            String resourcePath, String[] instructionSets) {
16482        final boolean isInAsec;
16483        if (installOnExternalAsec(installFlags)) {
16484            /* Apps on SD card are always in ASEC containers. */
16485            isInAsec = true;
16486        } else if (installForwardLocked(installFlags)
16487                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16488            /*
16489             * Forward-locked apps are only in ASEC containers if they're the
16490             * new style
16491             */
16492            isInAsec = true;
16493        } else {
16494            isInAsec = false;
16495        }
16496
16497        if (isInAsec) {
16498            return new AsecInstallArgs(codePath, instructionSets,
16499                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16500        } else {
16501            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16502        }
16503    }
16504
16505    static abstract class InstallArgs {
16506        /** @see InstallParams#origin */
16507        final OriginInfo origin;
16508        /** @see InstallParams#move */
16509        final MoveInfo move;
16510
16511        final IPackageInstallObserver2 observer;
16512        // Always refers to PackageManager flags only
16513        final int installFlags;
16514        final String installerPackageName;
16515        final String volumeUuid;
16516        final UserHandle user;
16517        final String abiOverride;
16518        final String[] installGrantPermissions;
16519        /** If non-null, drop an async trace when the install completes */
16520        final String traceMethod;
16521        final int traceCookie;
16522        final Certificate[][] certificates;
16523        final int installReason;
16524
16525        // The list of instruction sets supported by this app. This is currently
16526        // only used during the rmdex() phase to clean up resources. We can get rid of this
16527        // if we move dex files under the common app path.
16528        /* nullable */ String[] instructionSets;
16529
16530        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16531                int installFlags, String installerPackageName, String volumeUuid,
16532                UserHandle user, String[] instructionSets,
16533                String abiOverride, String[] installGrantPermissions,
16534                String traceMethod, int traceCookie, Certificate[][] certificates,
16535                int installReason) {
16536            this.origin = origin;
16537            this.move = move;
16538            this.installFlags = installFlags;
16539            this.observer = observer;
16540            this.installerPackageName = installerPackageName;
16541            this.volumeUuid = volumeUuid;
16542            this.user = user;
16543            this.instructionSets = instructionSets;
16544            this.abiOverride = abiOverride;
16545            this.installGrantPermissions = installGrantPermissions;
16546            this.traceMethod = traceMethod;
16547            this.traceCookie = traceCookie;
16548            this.certificates = certificates;
16549            this.installReason = installReason;
16550        }
16551
16552        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16553        abstract int doPreInstall(int status);
16554
16555        /**
16556         * Rename package into final resting place. All paths on the given
16557         * scanned package should be updated to reflect the rename.
16558         */
16559        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16560        abstract int doPostInstall(int status, int uid);
16561
16562        /** @see PackageSettingBase#codePathString */
16563        abstract String getCodePath();
16564        /** @see PackageSettingBase#resourcePathString */
16565        abstract String getResourcePath();
16566
16567        // Need installer lock especially for dex file removal.
16568        abstract void cleanUpResourcesLI();
16569        abstract boolean doPostDeleteLI(boolean delete);
16570
16571        /**
16572         * Called before the source arguments are copied. This is used mostly
16573         * for MoveParams when it needs to read the source file to put it in the
16574         * destination.
16575         */
16576        int doPreCopy() {
16577            return PackageManager.INSTALL_SUCCEEDED;
16578        }
16579
16580        /**
16581         * Called after the source arguments are copied. This is used mostly for
16582         * MoveParams when it needs to read the source file to put it in the
16583         * destination.
16584         */
16585        int doPostCopy(int uid) {
16586            return PackageManager.INSTALL_SUCCEEDED;
16587        }
16588
16589        protected boolean isFwdLocked() {
16590            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16591        }
16592
16593        protected boolean isExternalAsec() {
16594            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16595        }
16596
16597        protected boolean isEphemeral() {
16598            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16599        }
16600
16601        UserHandle getUser() {
16602            return user;
16603        }
16604    }
16605
16606    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16607        if (!allCodePaths.isEmpty()) {
16608            if (instructionSets == null) {
16609                throw new IllegalStateException("instructionSet == null");
16610            }
16611            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16612            for (String codePath : allCodePaths) {
16613                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16614                    try {
16615                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16616                    } catch (InstallerException ignored) {
16617                    }
16618                }
16619            }
16620        }
16621    }
16622
16623    /**
16624     * Logic to handle installation of non-ASEC applications, including copying
16625     * and renaming logic.
16626     */
16627    class FileInstallArgs extends InstallArgs {
16628        private File codeFile;
16629        private File resourceFile;
16630
16631        // Example topology:
16632        // /data/app/com.example/base.apk
16633        // /data/app/com.example/split_foo.apk
16634        // /data/app/com.example/lib/arm/libfoo.so
16635        // /data/app/com.example/lib/arm64/libfoo.so
16636        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16637
16638        /** New install */
16639        FileInstallArgs(InstallParams params) {
16640            super(params.origin, params.move, params.observer, params.installFlags,
16641                    params.installerPackageName, params.volumeUuid,
16642                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16643                    params.grantedRuntimePermissions,
16644                    params.traceMethod, params.traceCookie, params.certificates,
16645                    params.installReason);
16646            if (isFwdLocked()) {
16647                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16648            }
16649        }
16650
16651        /** Existing install */
16652        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16653            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16654                    null, null, null, 0, null /*certificates*/,
16655                    PackageManager.INSTALL_REASON_UNKNOWN);
16656            this.codeFile = (codePath != null) ? new File(codePath) : null;
16657            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16658        }
16659
16660        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16661            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16662            try {
16663                return doCopyApk(imcs, temp);
16664            } finally {
16665                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16666            }
16667        }
16668
16669        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16670            if (origin.staged) {
16671                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16672                codeFile = origin.file;
16673                resourceFile = origin.file;
16674                return PackageManager.INSTALL_SUCCEEDED;
16675            }
16676
16677            try {
16678                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16679                final File tempDir =
16680                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16681                codeFile = tempDir;
16682                resourceFile = tempDir;
16683            } catch (IOException e) {
16684                Slog.w(TAG, "Failed to create copy file: " + e);
16685                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16686            }
16687
16688            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16689                @Override
16690                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16691                    if (!FileUtils.isValidExtFilename(name)) {
16692                        throw new IllegalArgumentException("Invalid filename: " + name);
16693                    }
16694                    try {
16695                        final File file = new File(codeFile, name);
16696                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16697                                O_RDWR | O_CREAT, 0644);
16698                        Os.chmod(file.getAbsolutePath(), 0644);
16699                        return new ParcelFileDescriptor(fd);
16700                    } catch (ErrnoException e) {
16701                        throw new RemoteException("Failed to open: " + e.getMessage());
16702                    }
16703                }
16704            };
16705
16706            int ret = PackageManager.INSTALL_SUCCEEDED;
16707            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16708            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16709                Slog.e(TAG, "Failed to copy package");
16710                return ret;
16711            }
16712
16713            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16714            NativeLibraryHelper.Handle handle = null;
16715            try {
16716                handle = NativeLibraryHelper.Handle.create(codeFile);
16717                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16718                        abiOverride);
16719            } catch (IOException e) {
16720                Slog.e(TAG, "Copying native libraries failed", e);
16721                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16722            } finally {
16723                IoUtils.closeQuietly(handle);
16724            }
16725
16726            return ret;
16727        }
16728
16729        int doPreInstall(int status) {
16730            if (status != PackageManager.INSTALL_SUCCEEDED) {
16731                cleanUp();
16732            }
16733            return status;
16734        }
16735
16736        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16737            if (status != PackageManager.INSTALL_SUCCEEDED) {
16738                cleanUp();
16739                return false;
16740            }
16741
16742            final File targetDir = codeFile.getParentFile();
16743            final File beforeCodeFile = codeFile;
16744            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16745
16746            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16747            try {
16748                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16749            } catch (ErrnoException e) {
16750                Slog.w(TAG, "Failed to rename", e);
16751                return false;
16752            }
16753
16754            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16755                Slog.w(TAG, "Failed to restorecon");
16756                return false;
16757            }
16758
16759            // Reflect the rename internally
16760            codeFile = afterCodeFile;
16761            resourceFile = afterCodeFile;
16762
16763            // Reflect the rename in scanned details
16764            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16765            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16766                    afterCodeFile, pkg.baseCodePath));
16767            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16768                    afterCodeFile, pkg.splitCodePaths));
16769
16770            // Reflect the rename in app info
16771            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16772            pkg.setApplicationInfoCodePath(pkg.codePath);
16773            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16774            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16775            pkg.setApplicationInfoResourcePath(pkg.codePath);
16776            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16777            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16778
16779            return true;
16780        }
16781
16782        int doPostInstall(int status, int uid) {
16783            if (status != PackageManager.INSTALL_SUCCEEDED) {
16784                cleanUp();
16785            }
16786            return status;
16787        }
16788
16789        @Override
16790        String getCodePath() {
16791            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16792        }
16793
16794        @Override
16795        String getResourcePath() {
16796            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16797        }
16798
16799        private boolean cleanUp() {
16800            if (codeFile == null || !codeFile.exists()) {
16801                return false;
16802            }
16803
16804            removeCodePathLI(codeFile);
16805
16806            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16807                resourceFile.delete();
16808            }
16809
16810            return true;
16811        }
16812
16813        void cleanUpResourcesLI() {
16814            // Try enumerating all code paths before deleting
16815            List<String> allCodePaths = Collections.EMPTY_LIST;
16816            if (codeFile != null && codeFile.exists()) {
16817                try {
16818                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16819                    allCodePaths = pkg.getAllCodePaths();
16820                } catch (PackageParserException e) {
16821                    // Ignored; we tried our best
16822                }
16823            }
16824
16825            cleanUp();
16826            removeDexFiles(allCodePaths, instructionSets);
16827        }
16828
16829        boolean doPostDeleteLI(boolean delete) {
16830            // XXX err, shouldn't we respect the delete flag?
16831            cleanUpResourcesLI();
16832            return true;
16833        }
16834    }
16835
16836    private boolean isAsecExternal(String cid) {
16837        final String asecPath = PackageHelper.getSdFilesystem(cid);
16838        return !asecPath.startsWith(mAsecInternalPath);
16839    }
16840
16841    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16842            PackageManagerException {
16843        if (copyRet < 0) {
16844            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16845                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16846                throw new PackageManagerException(copyRet, message);
16847            }
16848        }
16849    }
16850
16851    /**
16852     * Extract the StorageManagerService "container ID" from the full code path of an
16853     * .apk.
16854     */
16855    static String cidFromCodePath(String fullCodePath) {
16856        int eidx = fullCodePath.lastIndexOf("/");
16857        String subStr1 = fullCodePath.substring(0, eidx);
16858        int sidx = subStr1.lastIndexOf("/");
16859        return subStr1.substring(sidx+1, eidx);
16860    }
16861
16862    /**
16863     * Logic to handle installation of ASEC applications, including copying and
16864     * renaming logic.
16865     */
16866    class AsecInstallArgs extends InstallArgs {
16867        static final String RES_FILE_NAME = "pkg.apk";
16868        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16869
16870        String cid;
16871        String packagePath;
16872        String resourcePath;
16873
16874        /** New install */
16875        AsecInstallArgs(InstallParams params) {
16876            super(params.origin, params.move, params.observer, params.installFlags,
16877                    params.installerPackageName, params.volumeUuid,
16878                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16879                    params.grantedRuntimePermissions,
16880                    params.traceMethod, params.traceCookie, params.certificates,
16881                    params.installReason);
16882        }
16883
16884        /** Existing install */
16885        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16886                        boolean isExternal, boolean isForwardLocked) {
16887            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16888                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16889                    instructionSets, null, null, null, 0, null /*certificates*/,
16890                    PackageManager.INSTALL_REASON_UNKNOWN);
16891            // Hackily pretend we're still looking at a full code path
16892            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16893                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16894            }
16895
16896            // Extract cid from fullCodePath
16897            int eidx = fullCodePath.lastIndexOf("/");
16898            String subStr1 = fullCodePath.substring(0, eidx);
16899            int sidx = subStr1.lastIndexOf("/");
16900            cid = subStr1.substring(sidx+1, eidx);
16901            setMountPath(subStr1);
16902        }
16903
16904        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16905            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16906                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16907                    instructionSets, null, null, null, 0, null /*certificates*/,
16908                    PackageManager.INSTALL_REASON_UNKNOWN);
16909            this.cid = cid;
16910            setMountPath(PackageHelper.getSdDir(cid));
16911        }
16912
16913        void createCopyFile() {
16914            cid = mInstallerService.allocateExternalStageCidLegacy();
16915        }
16916
16917        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16918            if (origin.staged && origin.cid != null) {
16919                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16920                cid = origin.cid;
16921                setMountPath(PackageHelper.getSdDir(cid));
16922                return PackageManager.INSTALL_SUCCEEDED;
16923            }
16924
16925            if (temp) {
16926                createCopyFile();
16927            } else {
16928                /*
16929                 * Pre-emptively destroy the container since it's destroyed if
16930                 * copying fails due to it existing anyway.
16931                 */
16932                PackageHelper.destroySdDir(cid);
16933            }
16934
16935            final String newMountPath = imcs.copyPackageToContainer(
16936                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16937                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16938
16939            if (newMountPath != null) {
16940                setMountPath(newMountPath);
16941                return PackageManager.INSTALL_SUCCEEDED;
16942            } else {
16943                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16944            }
16945        }
16946
16947        @Override
16948        String getCodePath() {
16949            return packagePath;
16950        }
16951
16952        @Override
16953        String getResourcePath() {
16954            return resourcePath;
16955        }
16956
16957        int doPreInstall(int status) {
16958            if (status != PackageManager.INSTALL_SUCCEEDED) {
16959                // Destroy container
16960                PackageHelper.destroySdDir(cid);
16961            } else {
16962                boolean mounted = PackageHelper.isContainerMounted(cid);
16963                if (!mounted) {
16964                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16965                            Process.SYSTEM_UID);
16966                    if (newMountPath != null) {
16967                        setMountPath(newMountPath);
16968                    } else {
16969                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16970                    }
16971                }
16972            }
16973            return status;
16974        }
16975
16976        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16977            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16978            String newMountPath = null;
16979            if (PackageHelper.isContainerMounted(cid)) {
16980                // Unmount the container
16981                if (!PackageHelper.unMountSdDir(cid)) {
16982                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16983                    return false;
16984                }
16985            }
16986            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16987                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16988                        " which might be stale. Will try to clean up.");
16989                // Clean up the stale container and proceed to recreate.
16990                if (!PackageHelper.destroySdDir(newCacheId)) {
16991                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16992                    return false;
16993                }
16994                // Successfully cleaned up stale container. Try to rename again.
16995                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16996                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16997                            + " inspite of cleaning it up.");
16998                    return false;
16999                }
17000            }
17001            if (!PackageHelper.isContainerMounted(newCacheId)) {
17002                Slog.w(TAG, "Mounting container " + newCacheId);
17003                newMountPath = PackageHelper.mountSdDir(newCacheId,
17004                        getEncryptKey(), Process.SYSTEM_UID);
17005            } else {
17006                newMountPath = PackageHelper.getSdDir(newCacheId);
17007            }
17008            if (newMountPath == null) {
17009                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
17010                return false;
17011            }
17012            Log.i(TAG, "Succesfully renamed " + cid +
17013                    " to " + newCacheId +
17014                    " at new path: " + newMountPath);
17015            cid = newCacheId;
17016
17017            final File beforeCodeFile = new File(packagePath);
17018            setMountPath(newMountPath);
17019            final File afterCodeFile = new File(packagePath);
17020
17021            // Reflect the rename in scanned details
17022            pkg.setCodePath(afterCodeFile.getAbsolutePath());
17023            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
17024                    afterCodeFile, pkg.baseCodePath));
17025            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
17026                    afterCodeFile, pkg.splitCodePaths));
17027
17028            // Reflect the rename in app info
17029            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17030            pkg.setApplicationInfoCodePath(pkg.codePath);
17031            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17032            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17033            pkg.setApplicationInfoResourcePath(pkg.codePath);
17034            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17035            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17036
17037            return true;
17038        }
17039
17040        private void setMountPath(String mountPath) {
17041            final File mountFile = new File(mountPath);
17042
17043            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17044            if (monolithicFile.exists()) {
17045                packagePath = monolithicFile.getAbsolutePath();
17046                if (isFwdLocked()) {
17047                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17048                } else {
17049                    resourcePath = packagePath;
17050                }
17051            } else {
17052                packagePath = mountFile.getAbsolutePath();
17053                resourcePath = packagePath;
17054            }
17055        }
17056
17057        int doPostInstall(int status, int uid) {
17058            if (status != PackageManager.INSTALL_SUCCEEDED) {
17059                cleanUp();
17060            } else {
17061                final int groupOwner;
17062                final String protectedFile;
17063                if (isFwdLocked()) {
17064                    groupOwner = UserHandle.getSharedAppGid(uid);
17065                    protectedFile = RES_FILE_NAME;
17066                } else {
17067                    groupOwner = -1;
17068                    protectedFile = null;
17069                }
17070
17071                if (uid < Process.FIRST_APPLICATION_UID
17072                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17073                    Slog.e(TAG, "Failed to finalize " + cid);
17074                    PackageHelper.destroySdDir(cid);
17075                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17076                }
17077
17078                boolean mounted = PackageHelper.isContainerMounted(cid);
17079                if (!mounted) {
17080                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17081                }
17082            }
17083            return status;
17084        }
17085
17086        private void cleanUp() {
17087            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17088
17089            // Destroy secure container
17090            PackageHelper.destroySdDir(cid);
17091        }
17092
17093        private List<String> getAllCodePaths() {
17094            final File codeFile = new File(getCodePath());
17095            if (codeFile != null && codeFile.exists()) {
17096                try {
17097                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17098                    return pkg.getAllCodePaths();
17099                } catch (PackageParserException e) {
17100                    // Ignored; we tried our best
17101                }
17102            }
17103            return Collections.EMPTY_LIST;
17104        }
17105
17106        void cleanUpResourcesLI() {
17107            // Enumerate all code paths before deleting
17108            cleanUpResourcesLI(getAllCodePaths());
17109        }
17110
17111        private void cleanUpResourcesLI(List<String> allCodePaths) {
17112            cleanUp();
17113            removeDexFiles(allCodePaths, instructionSets);
17114        }
17115
17116        String getPackageName() {
17117            return getAsecPackageName(cid);
17118        }
17119
17120        boolean doPostDeleteLI(boolean delete) {
17121            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17122            final List<String> allCodePaths = getAllCodePaths();
17123            boolean mounted = PackageHelper.isContainerMounted(cid);
17124            if (mounted) {
17125                // Unmount first
17126                if (PackageHelper.unMountSdDir(cid)) {
17127                    mounted = false;
17128                }
17129            }
17130            if (!mounted && delete) {
17131                cleanUpResourcesLI(allCodePaths);
17132            }
17133            return !mounted;
17134        }
17135
17136        @Override
17137        int doPreCopy() {
17138            if (isFwdLocked()) {
17139                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17140                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17141                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17142                }
17143            }
17144
17145            return PackageManager.INSTALL_SUCCEEDED;
17146        }
17147
17148        @Override
17149        int doPostCopy(int uid) {
17150            if (isFwdLocked()) {
17151                if (uid < Process.FIRST_APPLICATION_UID
17152                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17153                                RES_FILE_NAME)) {
17154                    Slog.e(TAG, "Failed to finalize " + cid);
17155                    PackageHelper.destroySdDir(cid);
17156                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17157                }
17158            }
17159
17160            return PackageManager.INSTALL_SUCCEEDED;
17161        }
17162    }
17163
17164    /**
17165     * Logic to handle movement of existing installed applications.
17166     */
17167    class MoveInstallArgs extends InstallArgs {
17168        private File codeFile;
17169        private File resourceFile;
17170
17171        /** New install */
17172        MoveInstallArgs(InstallParams params) {
17173            super(params.origin, params.move, params.observer, params.installFlags,
17174                    params.installerPackageName, params.volumeUuid,
17175                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17176                    params.grantedRuntimePermissions,
17177                    params.traceMethod, params.traceCookie, params.certificates,
17178                    params.installReason);
17179        }
17180
17181        int copyApk(IMediaContainerService imcs, boolean temp) {
17182            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17183                    + move.fromUuid + " to " + move.toUuid);
17184            synchronized (mInstaller) {
17185                try {
17186                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17187                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17188                } catch (InstallerException e) {
17189                    Slog.w(TAG, "Failed to move app", e);
17190                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17191                }
17192            }
17193
17194            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17195            resourceFile = codeFile;
17196            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17197
17198            return PackageManager.INSTALL_SUCCEEDED;
17199        }
17200
17201        int doPreInstall(int status) {
17202            if (status != PackageManager.INSTALL_SUCCEEDED) {
17203                cleanUp(move.toUuid);
17204            }
17205            return status;
17206        }
17207
17208        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17209            if (status != PackageManager.INSTALL_SUCCEEDED) {
17210                cleanUp(move.toUuid);
17211                return false;
17212            }
17213
17214            // Reflect the move in app info
17215            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17216            pkg.setApplicationInfoCodePath(pkg.codePath);
17217            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17218            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17219            pkg.setApplicationInfoResourcePath(pkg.codePath);
17220            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17221            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17222
17223            return true;
17224        }
17225
17226        int doPostInstall(int status, int uid) {
17227            if (status == PackageManager.INSTALL_SUCCEEDED) {
17228                cleanUp(move.fromUuid);
17229            } else {
17230                cleanUp(move.toUuid);
17231            }
17232            return status;
17233        }
17234
17235        @Override
17236        String getCodePath() {
17237            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17238        }
17239
17240        @Override
17241        String getResourcePath() {
17242            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17243        }
17244
17245        private boolean cleanUp(String volumeUuid) {
17246            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17247                    move.dataAppName);
17248            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17249            final int[] userIds = sUserManager.getUserIds();
17250            synchronized (mInstallLock) {
17251                // Clean up both app data and code
17252                // All package moves are frozen until finished
17253                for (int userId : userIds) {
17254                    try {
17255                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17256                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17257                    } catch (InstallerException e) {
17258                        Slog.w(TAG, String.valueOf(e));
17259                    }
17260                }
17261                removeCodePathLI(codeFile);
17262            }
17263            return true;
17264        }
17265
17266        void cleanUpResourcesLI() {
17267            throw new UnsupportedOperationException();
17268        }
17269
17270        boolean doPostDeleteLI(boolean delete) {
17271            throw new UnsupportedOperationException();
17272        }
17273    }
17274
17275    static String getAsecPackageName(String packageCid) {
17276        int idx = packageCid.lastIndexOf("-");
17277        if (idx == -1) {
17278            return packageCid;
17279        }
17280        return packageCid.substring(0, idx);
17281    }
17282
17283    // Utility method used to create code paths based on package name and available index.
17284    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17285        String idxStr = "";
17286        int idx = 1;
17287        // Fall back to default value of idx=1 if prefix is not
17288        // part of oldCodePath
17289        if (oldCodePath != null) {
17290            String subStr = oldCodePath;
17291            // Drop the suffix right away
17292            if (suffix != null && subStr.endsWith(suffix)) {
17293                subStr = subStr.substring(0, subStr.length() - suffix.length());
17294            }
17295            // If oldCodePath already contains prefix find out the
17296            // ending index to either increment or decrement.
17297            int sidx = subStr.lastIndexOf(prefix);
17298            if (sidx != -1) {
17299                subStr = subStr.substring(sidx + prefix.length());
17300                if (subStr != null) {
17301                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17302                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17303                    }
17304                    try {
17305                        idx = Integer.parseInt(subStr);
17306                        if (idx <= 1) {
17307                            idx++;
17308                        } else {
17309                            idx--;
17310                        }
17311                    } catch(NumberFormatException e) {
17312                    }
17313                }
17314            }
17315        }
17316        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17317        return prefix + idxStr;
17318    }
17319
17320    private File getNextCodePath(File targetDir, String packageName) {
17321        File result;
17322        SecureRandom random = new SecureRandom();
17323        byte[] bytes = new byte[16];
17324        do {
17325            random.nextBytes(bytes);
17326            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17327            result = new File(targetDir, packageName + "-" + suffix);
17328        } while (result.exists());
17329        return result;
17330    }
17331
17332    // Utility method that returns the relative package path with respect
17333    // to the installation directory. Like say for /data/data/com.test-1.apk
17334    // string com.test-1 is returned.
17335    static String deriveCodePathName(String codePath) {
17336        if (codePath == null) {
17337            return null;
17338        }
17339        final File codeFile = new File(codePath);
17340        final String name = codeFile.getName();
17341        if (codeFile.isDirectory()) {
17342            return name;
17343        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17344            final int lastDot = name.lastIndexOf('.');
17345            return name.substring(0, lastDot);
17346        } else {
17347            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17348            return null;
17349        }
17350    }
17351
17352    static class PackageInstalledInfo {
17353        String name;
17354        int uid;
17355        // The set of users that originally had this package installed.
17356        int[] origUsers;
17357        // The set of users that now have this package installed.
17358        int[] newUsers;
17359        PackageParser.Package pkg;
17360        int returnCode;
17361        String returnMsg;
17362        PackageRemovedInfo removedInfo;
17363        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17364
17365        public void setError(int code, String msg) {
17366            setReturnCode(code);
17367            setReturnMessage(msg);
17368            Slog.w(TAG, msg);
17369        }
17370
17371        public void setError(String msg, PackageParserException e) {
17372            setReturnCode(e.error);
17373            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17374            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17375            for (int i = 0; i < childCount; i++) {
17376                addedChildPackages.valueAt(i).setError(msg, e);
17377            }
17378            Slog.w(TAG, msg, e);
17379        }
17380
17381        public void setError(String msg, PackageManagerException e) {
17382            returnCode = e.error;
17383            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17384            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17385            for (int i = 0; i < childCount; i++) {
17386                addedChildPackages.valueAt(i).setError(msg, e);
17387            }
17388            Slog.w(TAG, msg, e);
17389        }
17390
17391        public void setReturnCode(int returnCode) {
17392            this.returnCode = returnCode;
17393            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17394            for (int i = 0; i < childCount; i++) {
17395                addedChildPackages.valueAt(i).returnCode = returnCode;
17396            }
17397        }
17398
17399        private void setReturnMessage(String returnMsg) {
17400            this.returnMsg = returnMsg;
17401            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17402            for (int i = 0; i < childCount; i++) {
17403                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17404            }
17405        }
17406
17407        // In some error cases we want to convey more info back to the observer
17408        String origPackage;
17409        String origPermission;
17410    }
17411
17412    /*
17413     * Install a non-existing package.
17414     */
17415    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17416            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17417            PackageInstalledInfo res, int installReason) {
17418        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17419
17420        // Remember this for later, in case we need to rollback this install
17421        String pkgName = pkg.packageName;
17422
17423        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17424
17425        synchronized(mPackages) {
17426            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17427            if (renamedPackage != null) {
17428                // A package with the same name is already installed, though
17429                // it has been renamed to an older name.  The package we
17430                // are trying to install should be installed as an update to
17431                // the existing one, but that has not been requested, so bail.
17432                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17433                        + " without first uninstalling package running as "
17434                        + renamedPackage);
17435                return;
17436            }
17437            if (mPackages.containsKey(pkgName)) {
17438                // Don't allow installation over an existing package with the same name.
17439                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17440                        + " without first uninstalling.");
17441                return;
17442            }
17443        }
17444
17445        try {
17446            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17447                    System.currentTimeMillis(), user);
17448
17449            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17450
17451            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17452                prepareAppDataAfterInstallLIF(newPackage);
17453
17454            } else {
17455                // Remove package from internal structures, but keep around any
17456                // data that might have already existed
17457                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17458                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17459            }
17460        } catch (PackageManagerException e) {
17461            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17462        }
17463
17464        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17465    }
17466
17467    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17468        // Can't rotate keys during boot or if sharedUser.
17469        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17470                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17471            return false;
17472        }
17473        // app is using upgradeKeySets; make sure all are valid
17474        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17475        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17476        for (int i = 0; i < upgradeKeySets.length; i++) {
17477            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17478                Slog.wtf(TAG, "Package "
17479                         + (oldPs.name != null ? oldPs.name : "<null>")
17480                         + " contains upgrade-key-set reference to unknown key-set: "
17481                         + upgradeKeySets[i]
17482                         + " reverting to signatures check.");
17483                return false;
17484            }
17485        }
17486        return true;
17487    }
17488
17489    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17490        // Upgrade keysets are being used.  Determine if new package has a superset of the
17491        // required keys.
17492        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17493        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17494        for (int i = 0; i < upgradeKeySets.length; i++) {
17495            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17496            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17497                return true;
17498            }
17499        }
17500        return false;
17501    }
17502
17503    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17504        try (DigestInputStream digestStream =
17505                new DigestInputStream(new FileInputStream(file), digest)) {
17506            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17507        }
17508    }
17509
17510    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17511            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17512            int installReason) {
17513        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17514
17515        final PackageParser.Package oldPackage;
17516        final PackageSetting ps;
17517        final String pkgName = pkg.packageName;
17518        final int[] allUsers;
17519        final int[] installedUsers;
17520
17521        synchronized(mPackages) {
17522            oldPackage = mPackages.get(pkgName);
17523            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17524
17525            // don't allow upgrade to target a release SDK from a pre-release SDK
17526            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17527                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17528            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17529                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17530            if (oldTargetsPreRelease
17531                    && !newTargetsPreRelease
17532                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17533                Slog.w(TAG, "Can't install package targeting released sdk");
17534                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17535                return;
17536            }
17537
17538            ps = mSettings.mPackages.get(pkgName);
17539
17540            // verify signatures are valid
17541            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17542                if (!checkUpgradeKeySetLP(ps, pkg)) {
17543                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17544                            "New package not signed by keys specified by upgrade-keysets: "
17545                                    + pkgName);
17546                    return;
17547                }
17548            } else {
17549                // default to original signature matching
17550                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17551                        != PackageManager.SIGNATURE_MATCH) {
17552                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17553                            "New package has a different signature: " + pkgName);
17554                    return;
17555                }
17556            }
17557
17558            // don't allow a system upgrade unless the upgrade hash matches
17559            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17560                byte[] digestBytes = null;
17561                try {
17562                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17563                    updateDigest(digest, new File(pkg.baseCodePath));
17564                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17565                        for (String path : pkg.splitCodePaths) {
17566                            updateDigest(digest, new File(path));
17567                        }
17568                    }
17569                    digestBytes = digest.digest();
17570                } catch (NoSuchAlgorithmException | IOException e) {
17571                    res.setError(INSTALL_FAILED_INVALID_APK,
17572                            "Could not compute hash: " + pkgName);
17573                    return;
17574                }
17575                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17576                    res.setError(INSTALL_FAILED_INVALID_APK,
17577                            "New package fails restrict-update check: " + pkgName);
17578                    return;
17579                }
17580                // retain upgrade restriction
17581                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17582            }
17583
17584            // Check for shared user id changes
17585            String invalidPackageName =
17586                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17587            if (invalidPackageName != null) {
17588                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17589                        "Package " + invalidPackageName + " tried to change user "
17590                                + oldPackage.mSharedUserId);
17591                return;
17592            }
17593
17594            // In case of rollback, remember per-user/profile install state
17595            allUsers = sUserManager.getUserIds();
17596            installedUsers = ps.queryInstalledUsers(allUsers, true);
17597
17598            // don't allow an upgrade from full to ephemeral
17599            if (isInstantApp) {
17600                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17601                    for (int currentUser : allUsers) {
17602                        if (!ps.getInstantApp(currentUser)) {
17603                            // can't downgrade from full to instant
17604                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17605                                    + " for user: " + currentUser);
17606                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17607                            return;
17608                        }
17609                    }
17610                } else if (!ps.getInstantApp(user.getIdentifier())) {
17611                    // can't downgrade from full to instant
17612                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17613                            + " for user: " + user.getIdentifier());
17614                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17615                    return;
17616                }
17617            }
17618        }
17619
17620        // Update what is removed
17621        res.removedInfo = new PackageRemovedInfo(this);
17622        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17623        res.removedInfo.removedPackage = oldPackage.packageName;
17624        res.removedInfo.installerPackageName = ps.installerPackageName;
17625        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17626        res.removedInfo.isUpdate = true;
17627        res.removedInfo.origUsers = installedUsers;
17628        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17629        for (int i = 0; i < installedUsers.length; i++) {
17630            final int userId = installedUsers[i];
17631            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17632        }
17633
17634        final int childCount = (oldPackage.childPackages != null)
17635                ? oldPackage.childPackages.size() : 0;
17636        for (int i = 0; i < childCount; i++) {
17637            boolean childPackageUpdated = false;
17638            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17639            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17640            if (res.addedChildPackages != null) {
17641                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17642                if (childRes != null) {
17643                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17644                    childRes.removedInfo.removedPackage = childPkg.packageName;
17645                    if (childPs != null) {
17646                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17647                    }
17648                    childRes.removedInfo.isUpdate = true;
17649                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17650                    childPackageUpdated = true;
17651                }
17652            }
17653            if (!childPackageUpdated) {
17654                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17655                childRemovedRes.removedPackage = childPkg.packageName;
17656                if (childPs != null) {
17657                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17658                }
17659                childRemovedRes.isUpdate = false;
17660                childRemovedRes.dataRemoved = true;
17661                synchronized (mPackages) {
17662                    if (childPs != null) {
17663                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17664                    }
17665                }
17666                if (res.removedInfo.removedChildPackages == null) {
17667                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17668                }
17669                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17670            }
17671        }
17672
17673        boolean sysPkg = (isSystemApp(oldPackage));
17674        if (sysPkg) {
17675            // Set the system/privileged flags as needed
17676            final boolean privileged =
17677                    (oldPackage.applicationInfo.privateFlags
17678                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17679            final int systemPolicyFlags = policyFlags
17680                    | PackageParser.PARSE_IS_SYSTEM
17681                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17682
17683            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17684                    user, allUsers, installerPackageName, res, installReason);
17685        } else {
17686            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17687                    user, allUsers, installerPackageName, res, installReason);
17688        }
17689    }
17690
17691    @Override
17692    public List<String> getPreviousCodePaths(String packageName) {
17693        final int callingUid = Binder.getCallingUid();
17694        final List<String> result = new ArrayList<>();
17695        if (getInstantAppPackageName(callingUid) != null) {
17696            return result;
17697        }
17698        final PackageSetting ps = mSettings.mPackages.get(packageName);
17699        if (ps != null
17700                && ps.oldCodePaths != null
17701                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17702            result.addAll(ps.oldCodePaths);
17703        }
17704        return result;
17705    }
17706
17707    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17708            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17709            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17710            int installReason) {
17711        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17712                + deletedPackage);
17713
17714        String pkgName = deletedPackage.packageName;
17715        boolean deletedPkg = true;
17716        boolean addedPkg = false;
17717        boolean updatedSettings = false;
17718        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17719        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17720                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17721
17722        final long origUpdateTime = (pkg.mExtras != null)
17723                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17724
17725        // First delete the existing package while retaining the data directory
17726        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17727                res.removedInfo, true, pkg)) {
17728            // If the existing package wasn't successfully deleted
17729            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17730            deletedPkg = false;
17731        } else {
17732            // Successfully deleted the old package; proceed with replace.
17733
17734            // If deleted package lived in a container, give users a chance to
17735            // relinquish resources before killing.
17736            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17737                if (DEBUG_INSTALL) {
17738                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17739                }
17740                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17741                final ArrayList<String> pkgList = new ArrayList<String>(1);
17742                pkgList.add(deletedPackage.applicationInfo.packageName);
17743                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17744            }
17745
17746            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17747                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17748            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17749
17750            try {
17751                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17752                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17753                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17754                        installReason);
17755
17756                // Update the in-memory copy of the previous code paths.
17757                PackageSetting ps = mSettings.mPackages.get(pkgName);
17758                if (!killApp) {
17759                    if (ps.oldCodePaths == null) {
17760                        ps.oldCodePaths = new ArraySet<>();
17761                    }
17762                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17763                    if (deletedPackage.splitCodePaths != null) {
17764                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17765                    }
17766                } else {
17767                    ps.oldCodePaths = null;
17768                }
17769                if (ps.childPackageNames != null) {
17770                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17771                        final String childPkgName = ps.childPackageNames.get(i);
17772                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17773                        childPs.oldCodePaths = ps.oldCodePaths;
17774                    }
17775                }
17776                // set instant app status, but, only if it's explicitly specified
17777                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17778                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17779                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17780                prepareAppDataAfterInstallLIF(newPackage);
17781                addedPkg = true;
17782                mDexManager.notifyPackageUpdated(newPackage.packageName,
17783                        newPackage.baseCodePath, newPackage.splitCodePaths);
17784            } catch (PackageManagerException e) {
17785                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17786            }
17787        }
17788
17789        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17790            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17791
17792            // Revert all internal state mutations and added folders for the failed install
17793            if (addedPkg) {
17794                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17795                        res.removedInfo, true, null);
17796            }
17797
17798            // Restore the old package
17799            if (deletedPkg) {
17800                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17801                File restoreFile = new File(deletedPackage.codePath);
17802                // Parse old package
17803                boolean oldExternal = isExternal(deletedPackage);
17804                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17805                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17806                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17807                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17808                try {
17809                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17810                            null);
17811                } catch (PackageManagerException e) {
17812                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17813                            + e.getMessage());
17814                    return;
17815                }
17816
17817                synchronized (mPackages) {
17818                    // Ensure the installer package name up to date
17819                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17820
17821                    // Update permissions for restored package
17822                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17823
17824                    mSettings.writeLPr();
17825                }
17826
17827                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17828            }
17829        } else {
17830            synchronized (mPackages) {
17831                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17832                if (ps != null) {
17833                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17834                    if (res.removedInfo.removedChildPackages != null) {
17835                        final int childCount = res.removedInfo.removedChildPackages.size();
17836                        // Iterate in reverse as we may modify the collection
17837                        for (int i = childCount - 1; i >= 0; i--) {
17838                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17839                            if (res.addedChildPackages.containsKey(childPackageName)) {
17840                                res.removedInfo.removedChildPackages.removeAt(i);
17841                            } else {
17842                                PackageRemovedInfo childInfo = res.removedInfo
17843                                        .removedChildPackages.valueAt(i);
17844                                childInfo.removedForAllUsers = mPackages.get(
17845                                        childInfo.removedPackage) == null;
17846                            }
17847                        }
17848                    }
17849                }
17850            }
17851        }
17852    }
17853
17854    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17855            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17856            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17857            int installReason) {
17858        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17859                + ", old=" + deletedPackage);
17860
17861        final boolean disabledSystem;
17862
17863        // Remove existing system package
17864        removePackageLI(deletedPackage, true);
17865
17866        synchronized (mPackages) {
17867            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17868        }
17869        if (!disabledSystem) {
17870            // We didn't need to disable the .apk as a current system package,
17871            // which means we are replacing another update that is already
17872            // installed.  We need to make sure to delete the older one's .apk.
17873            res.removedInfo.args = createInstallArgsForExisting(0,
17874                    deletedPackage.applicationInfo.getCodePath(),
17875                    deletedPackage.applicationInfo.getResourcePath(),
17876                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17877        } else {
17878            res.removedInfo.args = null;
17879        }
17880
17881        // Successfully disabled the old package. Now proceed with re-installation
17882        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17883                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17884        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17885
17886        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17887        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17888                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17889
17890        PackageParser.Package newPackage = null;
17891        try {
17892            // Add the package to the internal data structures
17893            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17894
17895            // Set the update and install times
17896            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17897            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17898                    System.currentTimeMillis());
17899
17900            // Update the package dynamic state if succeeded
17901            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17902                // Now that the install succeeded make sure we remove data
17903                // directories for any child package the update removed.
17904                final int deletedChildCount = (deletedPackage.childPackages != null)
17905                        ? deletedPackage.childPackages.size() : 0;
17906                final int newChildCount = (newPackage.childPackages != null)
17907                        ? newPackage.childPackages.size() : 0;
17908                for (int i = 0; i < deletedChildCount; i++) {
17909                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17910                    boolean childPackageDeleted = true;
17911                    for (int j = 0; j < newChildCount; j++) {
17912                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17913                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17914                            childPackageDeleted = false;
17915                            break;
17916                        }
17917                    }
17918                    if (childPackageDeleted) {
17919                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17920                                deletedChildPkg.packageName);
17921                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17922                            PackageRemovedInfo removedChildRes = res.removedInfo
17923                                    .removedChildPackages.get(deletedChildPkg.packageName);
17924                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17925                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17926                        }
17927                    }
17928                }
17929
17930                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17931                        installReason);
17932                prepareAppDataAfterInstallLIF(newPackage);
17933
17934                mDexManager.notifyPackageUpdated(newPackage.packageName,
17935                            newPackage.baseCodePath, newPackage.splitCodePaths);
17936            }
17937        } catch (PackageManagerException e) {
17938            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17939            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17940        }
17941
17942        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17943            // Re installation failed. Restore old information
17944            // Remove new pkg information
17945            if (newPackage != null) {
17946                removeInstalledPackageLI(newPackage, true);
17947            }
17948            // Add back the old system package
17949            try {
17950                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17951            } catch (PackageManagerException e) {
17952                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17953            }
17954
17955            synchronized (mPackages) {
17956                if (disabledSystem) {
17957                    enableSystemPackageLPw(deletedPackage);
17958                }
17959
17960                // Ensure the installer package name up to date
17961                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17962
17963                // Update permissions for restored package
17964                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17965
17966                mSettings.writeLPr();
17967            }
17968
17969            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17970                    + " after failed upgrade");
17971        }
17972    }
17973
17974    /**
17975     * Checks whether the parent or any of the child packages have a change shared
17976     * user. For a package to be a valid update the shred users of the parent and
17977     * the children should match. We may later support changing child shared users.
17978     * @param oldPkg The updated package.
17979     * @param newPkg The update package.
17980     * @return The shared user that change between the versions.
17981     */
17982    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17983            PackageParser.Package newPkg) {
17984        // Check parent shared user
17985        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17986            return newPkg.packageName;
17987        }
17988        // Check child shared users
17989        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17990        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17991        for (int i = 0; i < newChildCount; i++) {
17992            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17993            // If this child was present, did it have the same shared user?
17994            for (int j = 0; j < oldChildCount; j++) {
17995                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17996                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17997                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17998                    return newChildPkg.packageName;
17999                }
18000            }
18001        }
18002        return null;
18003    }
18004
18005    private void removeNativeBinariesLI(PackageSetting ps) {
18006        // Remove the lib path for the parent package
18007        if (ps != null) {
18008            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
18009            // Remove the lib path for the child packages
18010            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18011            for (int i = 0; i < childCount; i++) {
18012                PackageSetting childPs = null;
18013                synchronized (mPackages) {
18014                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18015                }
18016                if (childPs != null) {
18017                    NativeLibraryHelper.removeNativeBinariesLI(childPs
18018                            .legacyNativeLibraryPathString);
18019                }
18020            }
18021        }
18022    }
18023
18024    private void enableSystemPackageLPw(PackageParser.Package pkg) {
18025        // Enable the parent package
18026        mSettings.enableSystemPackageLPw(pkg.packageName);
18027        // Enable the child packages
18028        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18029        for (int i = 0; i < childCount; i++) {
18030            PackageParser.Package childPkg = pkg.childPackages.get(i);
18031            mSettings.enableSystemPackageLPw(childPkg.packageName);
18032        }
18033    }
18034
18035    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18036            PackageParser.Package newPkg) {
18037        // Disable the parent package (parent always replaced)
18038        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18039        // Disable the child packages
18040        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18041        for (int i = 0; i < childCount; i++) {
18042            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18043            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18044            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18045        }
18046        return disabled;
18047    }
18048
18049    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18050            String installerPackageName) {
18051        // Enable the parent package
18052        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18053        // Enable the child packages
18054        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18055        for (int i = 0; i < childCount; i++) {
18056            PackageParser.Package childPkg = pkg.childPackages.get(i);
18057            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18058        }
18059    }
18060
18061    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18062        // Collect all used permissions in the UID
18063        ArraySet<String> usedPermissions = new ArraySet<>();
18064        final int packageCount = su.packages.size();
18065        for (int i = 0; i < packageCount; i++) {
18066            PackageSetting ps = su.packages.valueAt(i);
18067            if (ps.pkg == null) {
18068                continue;
18069            }
18070            final int requestedPermCount = ps.pkg.requestedPermissions.size();
18071            for (int j = 0; j < requestedPermCount; j++) {
18072                String permission = ps.pkg.requestedPermissions.get(j);
18073                BasePermission bp = mSettings.mPermissions.get(permission);
18074                if (bp != null) {
18075                    usedPermissions.add(permission);
18076                }
18077            }
18078        }
18079
18080        PermissionsState permissionsState = su.getPermissionsState();
18081        // Prune install permissions
18082        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18083        final int installPermCount = installPermStates.size();
18084        for (int i = installPermCount - 1; i >= 0;  i--) {
18085            PermissionState permissionState = installPermStates.get(i);
18086            if (!usedPermissions.contains(permissionState.getName())) {
18087                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18088                if (bp != null) {
18089                    permissionsState.revokeInstallPermission(bp);
18090                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18091                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18092                }
18093            }
18094        }
18095
18096        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18097
18098        // Prune runtime permissions
18099        for (int userId : allUserIds) {
18100            List<PermissionState> runtimePermStates = permissionsState
18101                    .getRuntimePermissionStates(userId);
18102            final int runtimePermCount = runtimePermStates.size();
18103            for (int i = runtimePermCount - 1; i >= 0; i--) {
18104                PermissionState permissionState = runtimePermStates.get(i);
18105                if (!usedPermissions.contains(permissionState.getName())) {
18106                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18107                    if (bp != null) {
18108                        permissionsState.revokeRuntimePermission(bp, userId);
18109                        permissionsState.updatePermissionFlags(bp, userId,
18110                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18111                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18112                                runtimePermissionChangedUserIds, userId);
18113                    }
18114                }
18115            }
18116        }
18117
18118        return runtimePermissionChangedUserIds;
18119    }
18120
18121    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18122            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18123        // Update the parent package setting
18124        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18125                res, user, installReason);
18126        // Update the child packages setting
18127        final int childCount = (newPackage.childPackages != null)
18128                ? newPackage.childPackages.size() : 0;
18129        for (int i = 0; i < childCount; i++) {
18130            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18131            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18132            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18133                    childRes.origUsers, childRes, user, installReason);
18134        }
18135    }
18136
18137    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18138            String installerPackageName, int[] allUsers, int[] installedForUsers,
18139            PackageInstalledInfo res, UserHandle user, int installReason) {
18140        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18141
18142        String pkgName = newPackage.packageName;
18143        synchronized (mPackages) {
18144            //write settings. the installStatus will be incomplete at this stage.
18145            //note that the new package setting would have already been
18146            //added to mPackages. It hasn't been persisted yet.
18147            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18148            // TODO: Remove this write? It's also written at the end of this method
18149            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18150            mSettings.writeLPr();
18151            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18152        }
18153
18154        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18155        synchronized (mPackages) {
18156            updatePermissionsLPw(newPackage.packageName, newPackage,
18157                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18158                            ? UPDATE_PERMISSIONS_ALL : 0));
18159            // For system-bundled packages, we assume that installing an upgraded version
18160            // of the package implies that the user actually wants to run that new code,
18161            // so we enable the package.
18162            PackageSetting ps = mSettings.mPackages.get(pkgName);
18163            final int userId = user.getIdentifier();
18164            if (ps != null) {
18165                if (isSystemApp(newPackage)) {
18166                    if (DEBUG_INSTALL) {
18167                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18168                    }
18169                    // Enable system package for requested users
18170                    if (res.origUsers != null) {
18171                        for (int origUserId : res.origUsers) {
18172                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18173                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18174                                        origUserId, installerPackageName);
18175                            }
18176                        }
18177                    }
18178                    // Also convey the prior install/uninstall state
18179                    if (allUsers != null && installedForUsers != null) {
18180                        for (int currentUserId : allUsers) {
18181                            final boolean installed = ArrayUtils.contains(
18182                                    installedForUsers, currentUserId);
18183                            if (DEBUG_INSTALL) {
18184                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18185                            }
18186                            ps.setInstalled(installed, currentUserId);
18187                        }
18188                        // these install state changes will be persisted in the
18189                        // upcoming call to mSettings.writeLPr().
18190                    }
18191                }
18192                // It's implied that when a user requests installation, they want the app to be
18193                // installed and enabled.
18194                if (userId != UserHandle.USER_ALL) {
18195                    ps.setInstalled(true, userId);
18196                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18197                }
18198
18199                // When replacing an existing package, preserve the original install reason for all
18200                // users that had the package installed before.
18201                final Set<Integer> previousUserIds = new ArraySet<>();
18202                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18203                    final int installReasonCount = res.removedInfo.installReasons.size();
18204                    for (int i = 0; i < installReasonCount; i++) {
18205                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18206                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18207                        ps.setInstallReason(previousInstallReason, previousUserId);
18208                        previousUserIds.add(previousUserId);
18209                    }
18210                }
18211
18212                // Set install reason for users that are having the package newly installed.
18213                if (userId == UserHandle.USER_ALL) {
18214                    for (int currentUserId : sUserManager.getUserIds()) {
18215                        if (!previousUserIds.contains(currentUserId)) {
18216                            ps.setInstallReason(installReason, currentUserId);
18217                        }
18218                    }
18219                } else if (!previousUserIds.contains(userId)) {
18220                    ps.setInstallReason(installReason, userId);
18221                }
18222                mSettings.writeKernelMappingLPr(ps);
18223            }
18224            res.name = pkgName;
18225            res.uid = newPackage.applicationInfo.uid;
18226            res.pkg = newPackage;
18227            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18228            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18229            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18230            //to update install status
18231            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18232            mSettings.writeLPr();
18233            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18234        }
18235
18236        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18237    }
18238
18239    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18240        try {
18241            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18242            installPackageLI(args, res);
18243        } finally {
18244            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18245        }
18246    }
18247
18248    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18249        final int installFlags = args.installFlags;
18250        final String installerPackageName = args.installerPackageName;
18251        final String volumeUuid = args.volumeUuid;
18252        final File tmpPackageFile = new File(args.getCodePath());
18253        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18254        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18255                || (args.volumeUuid != null));
18256        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18257        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18258        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18259        final boolean virtualPreload =
18260                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18261        boolean replace = false;
18262        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18263        if (args.move != null) {
18264            // moving a complete application; perform an initial scan on the new install location
18265            scanFlags |= SCAN_INITIAL;
18266        }
18267        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18268            scanFlags |= SCAN_DONT_KILL_APP;
18269        }
18270        if (instantApp) {
18271            scanFlags |= SCAN_AS_INSTANT_APP;
18272        }
18273        if (fullApp) {
18274            scanFlags |= SCAN_AS_FULL_APP;
18275        }
18276        if (virtualPreload) {
18277            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18278        }
18279
18280        // Result object to be returned
18281        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18282
18283        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18284
18285        // Sanity check
18286        if (instantApp && (forwardLocked || onExternal)) {
18287            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18288                    + " external=" + onExternal);
18289            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18290            return;
18291        }
18292
18293        // Retrieve PackageSettings and parse package
18294        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18295                | PackageParser.PARSE_ENFORCE_CODE
18296                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18297                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18298                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18299                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18300        PackageParser pp = new PackageParser();
18301        pp.setSeparateProcesses(mSeparateProcesses);
18302        pp.setDisplayMetrics(mMetrics);
18303        pp.setCallback(mPackageParserCallback);
18304
18305        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18306        final PackageParser.Package pkg;
18307        try {
18308            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18309        } catch (PackageParserException e) {
18310            res.setError("Failed parse during installPackageLI", e);
18311            return;
18312        } finally {
18313            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18314        }
18315
18316        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18317        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18318            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18319            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18320                    "Instant app package must target O");
18321            return;
18322        }
18323        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18324            Slog.w(TAG, "Instant app package " + pkg.packageName
18325                    + " does not target targetSandboxVersion 2");
18326            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18327                    "Instant app package must use targetSanboxVersion 2");
18328            return;
18329        }
18330
18331        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18332            // Static shared libraries have synthetic package names
18333            renameStaticSharedLibraryPackage(pkg);
18334
18335            // No static shared libs on external storage
18336            if (onExternal) {
18337                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18338                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18339                        "Packages declaring static-shared libs cannot be updated");
18340                return;
18341            }
18342        }
18343
18344        // If we are installing a clustered package add results for the children
18345        if (pkg.childPackages != null) {
18346            synchronized (mPackages) {
18347                final int childCount = pkg.childPackages.size();
18348                for (int i = 0; i < childCount; i++) {
18349                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18350                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18351                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18352                    childRes.pkg = childPkg;
18353                    childRes.name = childPkg.packageName;
18354                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18355                    if (childPs != null) {
18356                        childRes.origUsers = childPs.queryInstalledUsers(
18357                                sUserManager.getUserIds(), true);
18358                    }
18359                    if ((mPackages.containsKey(childPkg.packageName))) {
18360                        childRes.removedInfo = new PackageRemovedInfo(this);
18361                        childRes.removedInfo.removedPackage = childPkg.packageName;
18362                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18363                    }
18364                    if (res.addedChildPackages == null) {
18365                        res.addedChildPackages = new ArrayMap<>();
18366                    }
18367                    res.addedChildPackages.put(childPkg.packageName, childRes);
18368                }
18369            }
18370        }
18371
18372        // If package doesn't declare API override, mark that we have an install
18373        // time CPU ABI override.
18374        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18375            pkg.cpuAbiOverride = args.abiOverride;
18376        }
18377
18378        String pkgName = res.name = pkg.packageName;
18379        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18380            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18381                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18382                return;
18383            }
18384        }
18385
18386        try {
18387            // either use what we've been given or parse directly from the APK
18388            if (args.certificates != null) {
18389                try {
18390                    PackageParser.populateCertificates(pkg, args.certificates);
18391                } catch (PackageParserException e) {
18392                    // there was something wrong with the certificates we were given;
18393                    // try to pull them from the APK
18394                    PackageParser.collectCertificates(pkg, parseFlags);
18395                }
18396            } else {
18397                PackageParser.collectCertificates(pkg, parseFlags);
18398            }
18399        } catch (PackageParserException e) {
18400            res.setError("Failed collect during installPackageLI", e);
18401            return;
18402        }
18403
18404        // Get rid of all references to package scan path via parser.
18405        pp = null;
18406        String oldCodePath = null;
18407        boolean systemApp = false;
18408        synchronized (mPackages) {
18409            // Check if installing already existing package
18410            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18411                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18412                if (pkg.mOriginalPackages != null
18413                        && pkg.mOriginalPackages.contains(oldName)
18414                        && mPackages.containsKey(oldName)) {
18415                    // This package is derived from an original package,
18416                    // and this device has been updating from that original
18417                    // name.  We must continue using the original name, so
18418                    // rename the new package here.
18419                    pkg.setPackageName(oldName);
18420                    pkgName = pkg.packageName;
18421                    replace = true;
18422                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18423                            + oldName + " pkgName=" + pkgName);
18424                } else if (mPackages.containsKey(pkgName)) {
18425                    // This package, under its official name, already exists
18426                    // on the device; we should replace it.
18427                    replace = true;
18428                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18429                }
18430
18431                // Child packages are installed through the parent package
18432                if (pkg.parentPackage != null) {
18433                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18434                            "Package " + pkg.packageName + " is child of package "
18435                                    + pkg.parentPackage.parentPackage + ". Child packages "
18436                                    + "can be updated only through the parent package.");
18437                    return;
18438                }
18439
18440                if (replace) {
18441                    // Prevent apps opting out from runtime permissions
18442                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18443                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18444                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18445                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18446                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18447                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18448                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18449                                        + " doesn't support runtime permissions but the old"
18450                                        + " target SDK " + oldTargetSdk + " does.");
18451                        return;
18452                    }
18453                    // Prevent apps from downgrading their targetSandbox.
18454                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18455                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18456                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18457                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18458                                "Package " + pkg.packageName + " new target sandbox "
18459                                + newTargetSandbox + " is incompatible with the previous value of"
18460                                + oldTargetSandbox + ".");
18461                        return;
18462                    }
18463
18464                    // Prevent installing of child packages
18465                    if (oldPackage.parentPackage != null) {
18466                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18467                                "Package " + pkg.packageName + " is child of package "
18468                                        + oldPackage.parentPackage + ". Child packages "
18469                                        + "can be updated only through the parent package.");
18470                        return;
18471                    }
18472                }
18473            }
18474
18475            PackageSetting ps = mSettings.mPackages.get(pkgName);
18476            if (ps != null) {
18477                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18478
18479                // Static shared libs have same package with different versions where
18480                // we internally use a synthetic package name to allow multiple versions
18481                // of the same package, therefore we need to compare signatures against
18482                // the package setting for the latest library version.
18483                PackageSetting signatureCheckPs = ps;
18484                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18485                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18486                    if (libraryEntry != null) {
18487                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18488                    }
18489                }
18490
18491                // Quick sanity check that we're signed correctly if updating;
18492                // we'll check this again later when scanning, but we want to
18493                // bail early here before tripping over redefined permissions.
18494                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18495                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18496                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18497                                + pkg.packageName + " upgrade keys do not match the "
18498                                + "previously installed version");
18499                        return;
18500                    }
18501                } else {
18502                    try {
18503                        verifySignaturesLP(signatureCheckPs, pkg);
18504                    } catch (PackageManagerException e) {
18505                        res.setError(e.error, e.getMessage());
18506                        return;
18507                    }
18508                }
18509
18510                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18511                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18512                    systemApp = (ps.pkg.applicationInfo.flags &
18513                            ApplicationInfo.FLAG_SYSTEM) != 0;
18514                }
18515                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18516            }
18517
18518            int N = pkg.permissions.size();
18519            for (int i = N-1; i >= 0; i--) {
18520                PackageParser.Permission perm = pkg.permissions.get(i);
18521                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18522
18523                // Don't allow anyone but the system to define ephemeral permissions.
18524                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18525                        && !systemApp) {
18526                    Slog.w(TAG, "Non-System package " + pkg.packageName
18527                            + " attempting to delcare ephemeral permission "
18528                            + perm.info.name + "; Removing ephemeral.");
18529                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18530                }
18531                // Check whether the newly-scanned package wants to define an already-defined perm
18532                if (bp != null) {
18533                    // If the defining package is signed with our cert, it's okay.  This
18534                    // also includes the "updating the same package" case, of course.
18535                    // "updating same package" could also involve key-rotation.
18536                    final boolean sigsOk;
18537                    if (bp.sourcePackage.equals(pkg.packageName)
18538                            && (bp.packageSetting instanceof PackageSetting)
18539                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18540                                    scanFlags))) {
18541                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18542                    } else {
18543                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18544                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18545                    }
18546                    if (!sigsOk) {
18547                        // If the owning package is the system itself, we log but allow
18548                        // install to proceed; we fail the install on all other permission
18549                        // redefinitions.
18550                        if (!bp.sourcePackage.equals("android")) {
18551                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18552                                    + pkg.packageName + " attempting to redeclare permission "
18553                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18554                            res.origPermission = perm.info.name;
18555                            res.origPackage = bp.sourcePackage;
18556                            return;
18557                        } else {
18558                            Slog.w(TAG, "Package " + pkg.packageName
18559                                    + " attempting to redeclare system permission "
18560                                    + perm.info.name + "; ignoring new declaration");
18561                            pkg.permissions.remove(i);
18562                        }
18563                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18564                        // Prevent apps to change protection level to dangerous from any other
18565                        // type as this would allow a privilege escalation where an app adds a
18566                        // normal/signature permission in other app's group and later redefines
18567                        // it as dangerous leading to the group auto-grant.
18568                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18569                                == PermissionInfo.PROTECTION_DANGEROUS) {
18570                            if (bp != null && !bp.isRuntime()) {
18571                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18572                                        + "non-runtime permission " + perm.info.name
18573                                        + " to runtime; keeping old protection level");
18574                                perm.info.protectionLevel = bp.protectionLevel;
18575                            }
18576                        }
18577                    }
18578                }
18579            }
18580        }
18581
18582        if (systemApp) {
18583            if (onExternal) {
18584                // Abort update; system app can't be replaced with app on sdcard
18585                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18586                        "Cannot install updates to system apps on sdcard");
18587                return;
18588            } else if (instantApp) {
18589                // Abort update; system app can't be replaced with an instant app
18590                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18591                        "Cannot update a system app with an instant app");
18592                return;
18593            }
18594        }
18595
18596        if (args.move != null) {
18597            // We did an in-place move, so dex is ready to roll
18598            scanFlags |= SCAN_NO_DEX;
18599            scanFlags |= SCAN_MOVE;
18600
18601            synchronized (mPackages) {
18602                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18603                if (ps == null) {
18604                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18605                            "Missing settings for moved package " + pkgName);
18606                }
18607
18608                // We moved the entire application as-is, so bring over the
18609                // previously derived ABI information.
18610                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18611                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18612            }
18613
18614        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18615            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18616            scanFlags |= SCAN_NO_DEX;
18617
18618            try {
18619                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18620                    args.abiOverride : pkg.cpuAbiOverride);
18621                final boolean extractNativeLibs = !pkg.isLibrary();
18622                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18623                        extractNativeLibs, mAppLib32InstallDir);
18624            } catch (PackageManagerException pme) {
18625                Slog.e(TAG, "Error deriving application ABI", pme);
18626                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18627                return;
18628            }
18629
18630            // Shared libraries for the package need to be updated.
18631            synchronized (mPackages) {
18632                try {
18633                    updateSharedLibrariesLPr(pkg, null);
18634                } catch (PackageManagerException e) {
18635                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18636                }
18637            }
18638        }
18639
18640        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18641            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18642            return;
18643        }
18644
18645        // Verify if we need to dexopt the app.
18646        //
18647        // NOTE: it is *important* to call dexopt after doRename which will sync the
18648        // package data from PackageParser.Package and its corresponding ApplicationInfo.
18649        //
18650        // We only need to dexopt if the package meets ALL of the following conditions:
18651        //   1) it is not forward locked.
18652        //   2) it is not on on an external ASEC container.
18653        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18654        //
18655        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18656        // complete, so we skip this step during installation. Instead, we'll take extra time
18657        // the first time the instant app starts. It's preferred to do it this way to provide
18658        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18659        // middle of running an instant app. The default behaviour can be overridden
18660        // via gservices.
18661        final boolean performDexopt = !forwardLocked
18662            && !pkg.applicationInfo.isExternalAsec()
18663            && (!instantApp || Global.getInt(mContext.getContentResolver(),
18664                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18665
18666        if (performDexopt) {
18667            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18668            // Do not run PackageDexOptimizer through the local performDexOpt
18669            // method because `pkg` may not be in `mPackages` yet.
18670            //
18671            // Also, don't fail application installs if the dexopt step fails.
18672            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18673                REASON_INSTALL,
18674                DexoptOptions.DEXOPT_BOOT_COMPLETE);
18675            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18676                null /* instructionSets */,
18677                getOrCreateCompilerPackageStats(pkg),
18678                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18679                dexoptOptions);
18680            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18681        }
18682
18683        // Notify BackgroundDexOptService that the package has been changed.
18684        // If this is an update of a package which used to fail to compile,
18685        // BackgroundDexOptService will remove it from its blacklist.
18686        // TODO: Layering violation
18687        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18688
18689        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18690
18691        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18692                "installPackageLI")) {
18693            if (replace) {
18694                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18695                    // Static libs have a synthetic package name containing the version
18696                    // and cannot be updated as an update would get a new package name,
18697                    // unless this is the exact same version code which is useful for
18698                    // development.
18699                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18700                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18701                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18702                                + "static-shared libs cannot be updated");
18703                        return;
18704                    }
18705                }
18706                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18707                        installerPackageName, res, args.installReason);
18708            } else {
18709                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18710                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18711            }
18712        }
18713
18714        synchronized (mPackages) {
18715            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18716            if (ps != null) {
18717                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18718                ps.setUpdateAvailable(false /*updateAvailable*/);
18719            }
18720
18721            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18722            for (int i = 0; i < childCount; i++) {
18723                PackageParser.Package childPkg = pkg.childPackages.get(i);
18724                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18725                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18726                if (childPs != null) {
18727                    childRes.newUsers = childPs.queryInstalledUsers(
18728                            sUserManager.getUserIds(), true);
18729                }
18730            }
18731
18732            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18733                updateSequenceNumberLP(ps, res.newUsers);
18734                updateInstantAppInstallerLocked(pkgName);
18735            }
18736        }
18737    }
18738
18739    private void startIntentFilterVerifications(int userId, boolean replacing,
18740            PackageParser.Package pkg) {
18741        if (mIntentFilterVerifierComponent == null) {
18742            Slog.w(TAG, "No IntentFilter verification will not be done as "
18743                    + "there is no IntentFilterVerifier available!");
18744            return;
18745        }
18746
18747        final int verifierUid = getPackageUid(
18748                mIntentFilterVerifierComponent.getPackageName(),
18749                MATCH_DEBUG_TRIAGED_MISSING,
18750                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18751
18752        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18753        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18754        mHandler.sendMessage(msg);
18755
18756        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18757        for (int i = 0; i < childCount; i++) {
18758            PackageParser.Package childPkg = pkg.childPackages.get(i);
18759            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18760            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18761            mHandler.sendMessage(msg);
18762        }
18763    }
18764
18765    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18766            PackageParser.Package pkg) {
18767        int size = pkg.activities.size();
18768        if (size == 0) {
18769            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18770                    "No activity, so no need to verify any IntentFilter!");
18771            return;
18772        }
18773
18774        final boolean hasDomainURLs = hasDomainURLs(pkg);
18775        if (!hasDomainURLs) {
18776            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18777                    "No domain URLs, so no need to verify any IntentFilter!");
18778            return;
18779        }
18780
18781        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18782                + " if any IntentFilter from the " + size
18783                + " Activities needs verification ...");
18784
18785        int count = 0;
18786        final String packageName = pkg.packageName;
18787
18788        synchronized (mPackages) {
18789            // If this is a new install and we see that we've already run verification for this
18790            // package, we have nothing to do: it means the state was restored from backup.
18791            if (!replacing) {
18792                IntentFilterVerificationInfo ivi =
18793                        mSettings.getIntentFilterVerificationLPr(packageName);
18794                if (ivi != null) {
18795                    if (DEBUG_DOMAIN_VERIFICATION) {
18796                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18797                                + ivi.getStatusString());
18798                    }
18799                    return;
18800                }
18801            }
18802
18803            // If any filters need to be verified, then all need to be.
18804            boolean needToVerify = false;
18805            for (PackageParser.Activity a : pkg.activities) {
18806                for (ActivityIntentInfo filter : a.intents) {
18807                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18808                        if (DEBUG_DOMAIN_VERIFICATION) {
18809                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18810                        }
18811                        needToVerify = true;
18812                        break;
18813                    }
18814                }
18815            }
18816
18817            if (needToVerify) {
18818                final int verificationId = mIntentFilterVerificationToken++;
18819                for (PackageParser.Activity a : pkg.activities) {
18820                    for (ActivityIntentInfo filter : a.intents) {
18821                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18822                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18823                                    "Verification needed for IntentFilter:" + filter.toString());
18824                            mIntentFilterVerifier.addOneIntentFilterVerification(
18825                                    verifierUid, userId, verificationId, filter, packageName);
18826                            count++;
18827                        }
18828                    }
18829                }
18830            }
18831        }
18832
18833        if (count > 0) {
18834            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18835                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18836                    +  " for userId:" + userId);
18837            mIntentFilterVerifier.startVerifications(userId);
18838        } else {
18839            if (DEBUG_DOMAIN_VERIFICATION) {
18840                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18841            }
18842        }
18843    }
18844
18845    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18846        final ComponentName cn  = filter.activity.getComponentName();
18847        final String packageName = cn.getPackageName();
18848
18849        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18850                packageName);
18851        if (ivi == null) {
18852            return true;
18853        }
18854        int status = ivi.getStatus();
18855        switch (status) {
18856            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18857            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18858                return true;
18859
18860            default:
18861                // Nothing to do
18862                return false;
18863        }
18864    }
18865
18866    private static boolean isMultiArch(ApplicationInfo info) {
18867        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18868    }
18869
18870    private static boolean isExternal(PackageParser.Package pkg) {
18871        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18872    }
18873
18874    private static boolean isExternal(PackageSetting ps) {
18875        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18876    }
18877
18878    private static boolean isSystemApp(PackageParser.Package pkg) {
18879        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18880    }
18881
18882    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18883        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18884    }
18885
18886    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18887        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18888    }
18889
18890    private static boolean isSystemApp(PackageSetting ps) {
18891        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18892    }
18893
18894    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18895        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18896    }
18897
18898    private int packageFlagsToInstallFlags(PackageSetting ps) {
18899        int installFlags = 0;
18900        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18901            // This existing package was an external ASEC install when we have
18902            // the external flag without a UUID
18903            installFlags |= PackageManager.INSTALL_EXTERNAL;
18904        }
18905        if (ps.isForwardLocked()) {
18906            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18907        }
18908        return installFlags;
18909    }
18910
18911    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18912        if (isExternal(pkg)) {
18913            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18914                return StorageManager.UUID_PRIMARY_PHYSICAL;
18915            } else {
18916                return pkg.volumeUuid;
18917            }
18918        } else {
18919            return StorageManager.UUID_PRIVATE_INTERNAL;
18920        }
18921    }
18922
18923    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18924        if (isExternal(pkg)) {
18925            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18926                return mSettings.getExternalVersion();
18927            } else {
18928                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18929            }
18930        } else {
18931            return mSettings.getInternalVersion();
18932        }
18933    }
18934
18935    private void deleteTempPackageFiles() {
18936        final FilenameFilter filter = new FilenameFilter() {
18937            public boolean accept(File dir, String name) {
18938                return name.startsWith("vmdl") && name.endsWith(".tmp");
18939            }
18940        };
18941        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18942            file.delete();
18943        }
18944    }
18945
18946    @Override
18947    public void deletePackageAsUser(String packageName, int versionCode,
18948            IPackageDeleteObserver observer, int userId, int flags) {
18949        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18950                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18951    }
18952
18953    @Override
18954    public void deletePackageVersioned(VersionedPackage versionedPackage,
18955            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18956        final int callingUid = Binder.getCallingUid();
18957        mContext.enforceCallingOrSelfPermission(
18958                android.Manifest.permission.DELETE_PACKAGES, null);
18959        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18960        Preconditions.checkNotNull(versionedPackage);
18961        Preconditions.checkNotNull(observer);
18962        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18963                PackageManager.VERSION_CODE_HIGHEST,
18964                Integer.MAX_VALUE, "versionCode must be >= -1");
18965
18966        final String packageName = versionedPackage.getPackageName();
18967        final int versionCode = versionedPackage.getVersionCode();
18968        final String internalPackageName;
18969        synchronized (mPackages) {
18970            // Normalize package name to handle renamed packages and static libs
18971            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18972                    versionedPackage.getVersionCode());
18973        }
18974
18975        final int uid = Binder.getCallingUid();
18976        if (!isOrphaned(internalPackageName)
18977                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18978            try {
18979                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18980                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18981                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18982                observer.onUserActionRequired(intent);
18983            } catch (RemoteException re) {
18984            }
18985            return;
18986        }
18987        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18988        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18989        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18990            mContext.enforceCallingOrSelfPermission(
18991                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18992                    "deletePackage for user " + userId);
18993        }
18994
18995        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18996            try {
18997                observer.onPackageDeleted(packageName,
18998                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18999            } catch (RemoteException re) {
19000            }
19001            return;
19002        }
19003
19004        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
19005            try {
19006                observer.onPackageDeleted(packageName,
19007                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
19008            } catch (RemoteException re) {
19009            }
19010            return;
19011        }
19012
19013        if (DEBUG_REMOVE) {
19014            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
19015                    + " deleteAllUsers: " + deleteAllUsers + " version="
19016                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
19017                    ? "VERSION_CODE_HIGHEST" : versionCode));
19018        }
19019        // Queue up an async operation since the package deletion may take a little while.
19020        mHandler.post(new Runnable() {
19021            public void run() {
19022                mHandler.removeCallbacks(this);
19023                int returnCode;
19024                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
19025                boolean doDeletePackage = true;
19026                if (ps != null) {
19027                    final boolean targetIsInstantApp =
19028                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19029                    doDeletePackage = !targetIsInstantApp
19030                            || canViewInstantApps;
19031                }
19032                if (doDeletePackage) {
19033                    if (!deleteAllUsers) {
19034                        returnCode = deletePackageX(internalPackageName, versionCode,
19035                                userId, deleteFlags);
19036                    } else {
19037                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
19038                                internalPackageName, users);
19039                        // If nobody is blocking uninstall, proceed with delete for all users
19040                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19041                            returnCode = deletePackageX(internalPackageName, versionCode,
19042                                    userId, deleteFlags);
19043                        } else {
19044                            // Otherwise uninstall individually for users with blockUninstalls=false
19045                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19046                            for (int userId : users) {
19047                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19048                                    returnCode = deletePackageX(internalPackageName, versionCode,
19049                                            userId, userFlags);
19050                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19051                                        Slog.w(TAG, "Package delete failed for user " + userId
19052                                                + ", returnCode " + returnCode);
19053                                    }
19054                                }
19055                            }
19056                            // The app has only been marked uninstalled for certain users.
19057                            // We still need to report that delete was blocked
19058                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19059                        }
19060                    }
19061                } else {
19062                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19063                }
19064                try {
19065                    observer.onPackageDeleted(packageName, returnCode, null);
19066                } catch (RemoteException e) {
19067                    Log.i(TAG, "Observer no longer exists.");
19068                } //end catch
19069            } //end run
19070        });
19071    }
19072
19073    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19074        if (pkg.staticSharedLibName != null) {
19075            return pkg.manifestPackageName;
19076        }
19077        return pkg.packageName;
19078    }
19079
19080    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19081        // Handle renamed packages
19082        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19083        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19084
19085        // Is this a static library?
19086        SparseArray<SharedLibraryEntry> versionedLib =
19087                mStaticLibsByDeclaringPackage.get(packageName);
19088        if (versionedLib == null || versionedLib.size() <= 0) {
19089            return packageName;
19090        }
19091
19092        // Figure out which lib versions the caller can see
19093        SparseIntArray versionsCallerCanSee = null;
19094        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19095        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19096                && callingAppId != Process.ROOT_UID) {
19097            versionsCallerCanSee = new SparseIntArray();
19098            String libName = versionedLib.valueAt(0).info.getName();
19099            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19100            if (uidPackages != null) {
19101                for (String uidPackage : uidPackages) {
19102                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19103                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19104                    if (libIdx >= 0) {
19105                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19106                        versionsCallerCanSee.append(libVersion, libVersion);
19107                    }
19108                }
19109            }
19110        }
19111
19112        // Caller can see nothing - done
19113        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19114            return packageName;
19115        }
19116
19117        // Find the version the caller can see and the app version code
19118        SharedLibraryEntry highestVersion = null;
19119        final int versionCount = versionedLib.size();
19120        for (int i = 0; i < versionCount; i++) {
19121            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19122            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19123                    libEntry.info.getVersion()) < 0) {
19124                continue;
19125            }
19126            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19127            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19128                if (libVersionCode == versionCode) {
19129                    return libEntry.apk;
19130                }
19131            } else if (highestVersion == null) {
19132                highestVersion = libEntry;
19133            } else if (libVersionCode  > highestVersion.info
19134                    .getDeclaringPackage().getVersionCode()) {
19135                highestVersion = libEntry;
19136            }
19137        }
19138
19139        if (highestVersion != null) {
19140            return highestVersion.apk;
19141        }
19142
19143        return packageName;
19144    }
19145
19146    boolean isCallerVerifier(int callingUid) {
19147        final int callingUserId = UserHandle.getUserId(callingUid);
19148        return mRequiredVerifierPackage != null &&
19149                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19150    }
19151
19152    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19153        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19154              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19155            return true;
19156        }
19157        final int callingUserId = UserHandle.getUserId(callingUid);
19158        // If the caller installed the pkgName, then allow it to silently uninstall.
19159        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19160            return true;
19161        }
19162
19163        // Allow package verifier to silently uninstall.
19164        if (mRequiredVerifierPackage != null &&
19165                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19166            return true;
19167        }
19168
19169        // Allow package uninstaller to silently uninstall.
19170        if (mRequiredUninstallerPackage != null &&
19171                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19172            return true;
19173        }
19174
19175        // Allow storage manager to silently uninstall.
19176        if (mStorageManagerPackage != null &&
19177                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19178            return true;
19179        }
19180
19181        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19182        // uninstall for device owner provisioning.
19183        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19184                == PERMISSION_GRANTED) {
19185            return true;
19186        }
19187
19188        return false;
19189    }
19190
19191    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19192        int[] result = EMPTY_INT_ARRAY;
19193        for (int userId : userIds) {
19194            if (getBlockUninstallForUser(packageName, userId)) {
19195                result = ArrayUtils.appendInt(result, userId);
19196            }
19197        }
19198        return result;
19199    }
19200
19201    @Override
19202    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19203        final int callingUid = Binder.getCallingUid();
19204        if (getInstantAppPackageName(callingUid) != null
19205                && !isCallerSameApp(packageName, callingUid)) {
19206            return false;
19207        }
19208        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19209    }
19210
19211    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19212        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19213                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19214        try {
19215            if (dpm != null) {
19216                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19217                        /* callingUserOnly =*/ false);
19218                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19219                        : deviceOwnerComponentName.getPackageName();
19220                // Does the package contains the device owner?
19221                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19222                // this check is probably not needed, since DO should be registered as a device
19223                // admin on some user too. (Original bug for this: b/17657954)
19224                if (packageName.equals(deviceOwnerPackageName)) {
19225                    return true;
19226                }
19227                // Does it contain a device admin for any user?
19228                int[] users;
19229                if (userId == UserHandle.USER_ALL) {
19230                    users = sUserManager.getUserIds();
19231                } else {
19232                    users = new int[]{userId};
19233                }
19234                for (int i = 0; i < users.length; ++i) {
19235                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19236                        return true;
19237                    }
19238                }
19239            }
19240        } catch (RemoteException e) {
19241        }
19242        return false;
19243    }
19244
19245    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19246        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19247    }
19248
19249    /**
19250     *  This method is an internal method that could be get invoked either
19251     *  to delete an installed package or to clean up a failed installation.
19252     *  After deleting an installed package, a broadcast is sent to notify any
19253     *  listeners that the package has been removed. For cleaning up a failed
19254     *  installation, the broadcast is not necessary since the package's
19255     *  installation wouldn't have sent the initial broadcast either
19256     *  The key steps in deleting a package are
19257     *  deleting the package information in internal structures like mPackages,
19258     *  deleting the packages base directories through installd
19259     *  updating mSettings to reflect current status
19260     *  persisting settings for later use
19261     *  sending a broadcast if necessary
19262     */
19263    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19264        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19265        final boolean res;
19266
19267        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19268                ? UserHandle.USER_ALL : userId;
19269
19270        if (isPackageDeviceAdmin(packageName, removeUser)) {
19271            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19272            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19273        }
19274
19275        PackageSetting uninstalledPs = null;
19276        PackageParser.Package pkg = null;
19277
19278        // for the uninstall-updates case and restricted profiles, remember the per-
19279        // user handle installed state
19280        int[] allUsers;
19281        synchronized (mPackages) {
19282            uninstalledPs = mSettings.mPackages.get(packageName);
19283            if (uninstalledPs == null) {
19284                Slog.w(TAG, "Not removing non-existent package " + packageName);
19285                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19286            }
19287
19288            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19289                    && uninstalledPs.versionCode != versionCode) {
19290                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19291                        + uninstalledPs.versionCode + " != " + versionCode);
19292                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19293            }
19294
19295            // Static shared libs can be declared by any package, so let us not
19296            // allow removing a package if it provides a lib others depend on.
19297            pkg = mPackages.get(packageName);
19298
19299            allUsers = sUserManager.getUserIds();
19300
19301            if (pkg != null && pkg.staticSharedLibName != null) {
19302                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19303                        pkg.staticSharedLibVersion);
19304                if (libEntry != null) {
19305                    for (int currUserId : allUsers) {
19306                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19307                            continue;
19308                        }
19309                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19310                                libEntry.info, 0, currUserId);
19311                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19312                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19313                                    + " hosting lib " + libEntry.info.getName() + " version "
19314                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19315                                    + " for user " + currUserId);
19316                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19317                        }
19318                    }
19319                }
19320            }
19321
19322            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19323        }
19324
19325        final int freezeUser;
19326        if (isUpdatedSystemApp(uninstalledPs)
19327                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19328            // We're downgrading a system app, which will apply to all users, so
19329            // freeze them all during the downgrade
19330            freezeUser = UserHandle.USER_ALL;
19331        } else {
19332            freezeUser = removeUser;
19333        }
19334
19335        synchronized (mInstallLock) {
19336            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19337            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19338                    deleteFlags, "deletePackageX")) {
19339                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19340                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19341            }
19342            synchronized (mPackages) {
19343                if (res) {
19344                    if (pkg != null) {
19345                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19346                    }
19347                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19348                    updateInstantAppInstallerLocked(packageName);
19349                }
19350            }
19351        }
19352
19353        if (res) {
19354            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19355            info.sendPackageRemovedBroadcasts(killApp);
19356            info.sendSystemPackageUpdatedBroadcasts();
19357            info.sendSystemPackageAppearedBroadcasts();
19358        }
19359        // Force a gc here.
19360        Runtime.getRuntime().gc();
19361        // Delete the resources here after sending the broadcast to let
19362        // other processes clean up before deleting resources.
19363        if (info.args != null) {
19364            synchronized (mInstallLock) {
19365                info.args.doPostDeleteLI(true);
19366            }
19367        }
19368
19369        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19370    }
19371
19372    static class PackageRemovedInfo {
19373        final PackageSender packageSender;
19374        String removedPackage;
19375        String installerPackageName;
19376        int uid = -1;
19377        int removedAppId = -1;
19378        int[] origUsers;
19379        int[] removedUsers = null;
19380        int[] broadcastUsers = null;
19381        SparseArray<Integer> installReasons;
19382        boolean isRemovedPackageSystemUpdate = false;
19383        boolean isUpdate;
19384        boolean dataRemoved;
19385        boolean removedForAllUsers;
19386        boolean isStaticSharedLib;
19387        // Clean up resources deleted packages.
19388        InstallArgs args = null;
19389        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19390        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19391
19392        PackageRemovedInfo(PackageSender packageSender) {
19393            this.packageSender = packageSender;
19394        }
19395
19396        void sendPackageRemovedBroadcasts(boolean killApp) {
19397            sendPackageRemovedBroadcastInternal(killApp);
19398            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19399            for (int i = 0; i < childCount; i++) {
19400                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19401                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19402            }
19403        }
19404
19405        void sendSystemPackageUpdatedBroadcasts() {
19406            if (isRemovedPackageSystemUpdate) {
19407                sendSystemPackageUpdatedBroadcastsInternal();
19408                final int childCount = (removedChildPackages != null)
19409                        ? removedChildPackages.size() : 0;
19410                for (int i = 0; i < childCount; i++) {
19411                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19412                    if (childInfo.isRemovedPackageSystemUpdate) {
19413                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19414                    }
19415                }
19416            }
19417        }
19418
19419        void sendSystemPackageAppearedBroadcasts() {
19420            final int packageCount = (appearedChildPackages != null)
19421                    ? appearedChildPackages.size() : 0;
19422            for (int i = 0; i < packageCount; i++) {
19423                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19424                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19425                    true /*sendBootCompleted*/, false /*startReceiver*/,
19426                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19427            }
19428        }
19429
19430        private void sendSystemPackageUpdatedBroadcastsInternal() {
19431            Bundle extras = new Bundle(2);
19432            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19433            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19434            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19435                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19436            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19437                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19438            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19439                null, null, 0, removedPackage, null, null);
19440            if (installerPackageName != null) {
19441                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19442                        removedPackage, extras, 0 /*flags*/,
19443                        installerPackageName, null, null);
19444                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19445                        removedPackage, extras, 0 /*flags*/,
19446                        installerPackageName, null, null);
19447            }
19448        }
19449
19450        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19451            // Don't send static shared library removal broadcasts as these
19452            // libs are visible only the the apps that depend on them an one
19453            // cannot remove the library if it has a dependency.
19454            if (isStaticSharedLib) {
19455                return;
19456            }
19457            Bundle extras = new Bundle(2);
19458            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19459            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19460            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19461            if (isUpdate || isRemovedPackageSystemUpdate) {
19462                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19463            }
19464            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19465            if (removedPackage != null) {
19466                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19467                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19468                if (installerPackageName != null) {
19469                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19470                            removedPackage, extras, 0 /*flags*/,
19471                            installerPackageName, null, broadcastUsers);
19472                }
19473                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19474                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19475                        removedPackage, extras,
19476                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19477                        null, null, broadcastUsers);
19478                }
19479            }
19480            if (removedAppId >= 0) {
19481                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19482                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19483                    null, null, broadcastUsers);
19484            }
19485        }
19486
19487        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19488            removedUsers = userIds;
19489            if (removedUsers == null) {
19490                broadcastUsers = null;
19491                return;
19492            }
19493
19494            broadcastUsers = EMPTY_INT_ARRAY;
19495            for (int i = userIds.length - 1; i >= 0; --i) {
19496                final int userId = userIds[i];
19497                if (deletedPackageSetting.getInstantApp(userId)) {
19498                    continue;
19499                }
19500                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19501            }
19502        }
19503    }
19504
19505    /*
19506     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19507     * flag is not set, the data directory is removed as well.
19508     * make sure this flag is set for partially installed apps. If not its meaningless to
19509     * delete a partially installed application.
19510     */
19511    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19512            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19513        String packageName = ps.name;
19514        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19515        // Retrieve object to delete permissions for shared user later on
19516        final PackageParser.Package deletedPkg;
19517        final PackageSetting deletedPs;
19518        // reader
19519        synchronized (mPackages) {
19520            deletedPkg = mPackages.get(packageName);
19521            deletedPs = mSettings.mPackages.get(packageName);
19522            if (outInfo != null) {
19523                outInfo.removedPackage = packageName;
19524                outInfo.installerPackageName = ps.installerPackageName;
19525                outInfo.isStaticSharedLib = deletedPkg != null
19526                        && deletedPkg.staticSharedLibName != null;
19527                outInfo.populateUsers(deletedPs == null ? null
19528                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19529            }
19530        }
19531
19532        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19533
19534        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19535            final PackageParser.Package resolvedPkg;
19536            if (deletedPkg != null) {
19537                resolvedPkg = deletedPkg;
19538            } else {
19539                // We don't have a parsed package when it lives on an ejected
19540                // adopted storage device, so fake something together
19541                resolvedPkg = new PackageParser.Package(ps.name);
19542                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19543            }
19544            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19545                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19546            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19547            if (outInfo != null) {
19548                outInfo.dataRemoved = true;
19549            }
19550            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19551        }
19552
19553        int removedAppId = -1;
19554
19555        // writer
19556        synchronized (mPackages) {
19557            boolean installedStateChanged = false;
19558            if (deletedPs != null) {
19559                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19560                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19561                    clearDefaultBrowserIfNeeded(packageName);
19562                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19563                    removedAppId = mSettings.removePackageLPw(packageName);
19564                    if (outInfo != null) {
19565                        outInfo.removedAppId = removedAppId;
19566                    }
19567                    updatePermissionsLPw(deletedPs.name, null, 0);
19568                    if (deletedPs.sharedUser != null) {
19569                        // Remove permissions associated with package. Since runtime
19570                        // permissions are per user we have to kill the removed package
19571                        // or packages running under the shared user of the removed
19572                        // package if revoking the permissions requested only by the removed
19573                        // package is successful and this causes a change in gids.
19574                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19575                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19576                                    userId);
19577                            if (userIdToKill == UserHandle.USER_ALL
19578                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19579                                // If gids changed for this user, kill all affected packages.
19580                                mHandler.post(new Runnable() {
19581                                    @Override
19582                                    public void run() {
19583                                        // This has to happen with no lock held.
19584                                        killApplication(deletedPs.name, deletedPs.appId,
19585                                                KILL_APP_REASON_GIDS_CHANGED);
19586                                    }
19587                                });
19588                                break;
19589                            }
19590                        }
19591                    }
19592                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19593                }
19594                // make sure to preserve per-user disabled state if this removal was just
19595                // a downgrade of a system app to the factory package
19596                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19597                    if (DEBUG_REMOVE) {
19598                        Slog.d(TAG, "Propagating install state across downgrade");
19599                    }
19600                    for (int userId : allUserHandles) {
19601                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19602                        if (DEBUG_REMOVE) {
19603                            Slog.d(TAG, "    user " + userId + " => " + installed);
19604                        }
19605                        if (installed != ps.getInstalled(userId)) {
19606                            installedStateChanged = true;
19607                        }
19608                        ps.setInstalled(installed, userId);
19609                    }
19610                }
19611            }
19612            // can downgrade to reader
19613            if (writeSettings) {
19614                // Save settings now
19615                mSettings.writeLPr();
19616            }
19617            if (installedStateChanged) {
19618                mSettings.writeKernelMappingLPr(ps);
19619            }
19620        }
19621        if (removedAppId != -1) {
19622            // A user ID was deleted here. Go through all users and remove it
19623            // from KeyStore.
19624            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19625        }
19626    }
19627
19628    static boolean locationIsPrivileged(File path) {
19629        try {
19630            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19631                    .getCanonicalPath();
19632            return path.getCanonicalPath().startsWith(privilegedAppDir);
19633        } catch (IOException e) {
19634            Slog.e(TAG, "Unable to access code path " + path);
19635        }
19636        return false;
19637    }
19638
19639    /*
19640     * Tries to delete system package.
19641     */
19642    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19643            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19644            boolean writeSettings) {
19645        if (deletedPs.parentPackageName != null) {
19646            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19647            return false;
19648        }
19649
19650        final boolean applyUserRestrictions
19651                = (allUserHandles != null) && (outInfo.origUsers != null);
19652        final PackageSetting disabledPs;
19653        // Confirm if the system package has been updated
19654        // An updated system app can be deleted. This will also have to restore
19655        // the system pkg from system partition
19656        // reader
19657        synchronized (mPackages) {
19658            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19659        }
19660
19661        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19662                + " disabledPs=" + disabledPs);
19663
19664        if (disabledPs == null) {
19665            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19666            return false;
19667        } else if (DEBUG_REMOVE) {
19668            Slog.d(TAG, "Deleting system pkg from data partition");
19669        }
19670
19671        if (DEBUG_REMOVE) {
19672            if (applyUserRestrictions) {
19673                Slog.d(TAG, "Remembering install states:");
19674                for (int userId : allUserHandles) {
19675                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19676                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19677                }
19678            }
19679        }
19680
19681        // Delete the updated package
19682        outInfo.isRemovedPackageSystemUpdate = true;
19683        if (outInfo.removedChildPackages != null) {
19684            final int childCount = (deletedPs.childPackageNames != null)
19685                    ? deletedPs.childPackageNames.size() : 0;
19686            for (int i = 0; i < childCount; i++) {
19687                String childPackageName = deletedPs.childPackageNames.get(i);
19688                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19689                        .contains(childPackageName)) {
19690                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19691                            childPackageName);
19692                    if (childInfo != null) {
19693                        childInfo.isRemovedPackageSystemUpdate = true;
19694                    }
19695                }
19696            }
19697        }
19698
19699        if (disabledPs.versionCode < deletedPs.versionCode) {
19700            // Delete data for downgrades
19701            flags &= ~PackageManager.DELETE_KEEP_DATA;
19702        } else {
19703            // Preserve data by setting flag
19704            flags |= PackageManager.DELETE_KEEP_DATA;
19705        }
19706
19707        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19708                outInfo, writeSettings, disabledPs.pkg);
19709        if (!ret) {
19710            return false;
19711        }
19712
19713        // writer
19714        synchronized (mPackages) {
19715            // Reinstate the old system package
19716            enableSystemPackageLPw(disabledPs.pkg);
19717            // Remove any native libraries from the upgraded package.
19718            removeNativeBinariesLI(deletedPs);
19719        }
19720
19721        // Install the system package
19722        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19723        int parseFlags = mDefParseFlags
19724                | PackageParser.PARSE_MUST_BE_APK
19725                | PackageParser.PARSE_IS_SYSTEM
19726                | PackageParser.PARSE_IS_SYSTEM_DIR;
19727        if (locationIsPrivileged(disabledPs.codePath)) {
19728            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19729        }
19730
19731        final PackageParser.Package newPkg;
19732        try {
19733            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19734                0 /* currentTime */, null);
19735        } catch (PackageManagerException e) {
19736            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19737                    + e.getMessage());
19738            return false;
19739        }
19740
19741        try {
19742            // update shared libraries for the newly re-installed system package
19743            updateSharedLibrariesLPr(newPkg, null);
19744        } catch (PackageManagerException e) {
19745            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19746        }
19747
19748        prepareAppDataAfterInstallLIF(newPkg);
19749
19750        // writer
19751        synchronized (mPackages) {
19752            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19753
19754            // Propagate the permissions state as we do not want to drop on the floor
19755            // runtime permissions. The update permissions method below will take
19756            // care of removing obsolete permissions and grant install permissions.
19757            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19758            updatePermissionsLPw(newPkg.packageName, newPkg,
19759                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19760
19761            if (applyUserRestrictions) {
19762                boolean installedStateChanged = false;
19763                if (DEBUG_REMOVE) {
19764                    Slog.d(TAG, "Propagating install state across reinstall");
19765                }
19766                for (int userId : allUserHandles) {
19767                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19768                    if (DEBUG_REMOVE) {
19769                        Slog.d(TAG, "    user " + userId + " => " + installed);
19770                    }
19771                    if (installed != ps.getInstalled(userId)) {
19772                        installedStateChanged = true;
19773                    }
19774                    ps.setInstalled(installed, userId);
19775
19776                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19777                }
19778                // Regardless of writeSettings we need to ensure that this restriction
19779                // state propagation is persisted
19780                mSettings.writeAllUsersPackageRestrictionsLPr();
19781                if (installedStateChanged) {
19782                    mSettings.writeKernelMappingLPr(ps);
19783                }
19784            }
19785            // can downgrade to reader here
19786            if (writeSettings) {
19787                mSettings.writeLPr();
19788            }
19789        }
19790        return true;
19791    }
19792
19793    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19794            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19795            PackageRemovedInfo outInfo, boolean writeSettings,
19796            PackageParser.Package replacingPackage) {
19797        synchronized (mPackages) {
19798            if (outInfo != null) {
19799                outInfo.uid = ps.appId;
19800            }
19801
19802            if (outInfo != null && outInfo.removedChildPackages != null) {
19803                final int childCount = (ps.childPackageNames != null)
19804                        ? ps.childPackageNames.size() : 0;
19805                for (int i = 0; i < childCount; i++) {
19806                    String childPackageName = ps.childPackageNames.get(i);
19807                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19808                    if (childPs == null) {
19809                        return false;
19810                    }
19811                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19812                            childPackageName);
19813                    if (childInfo != null) {
19814                        childInfo.uid = childPs.appId;
19815                    }
19816                }
19817            }
19818        }
19819
19820        // Delete package data from internal structures and also remove data if flag is set
19821        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19822
19823        // Delete the child packages data
19824        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19825        for (int i = 0; i < childCount; i++) {
19826            PackageSetting childPs;
19827            synchronized (mPackages) {
19828                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19829            }
19830            if (childPs != null) {
19831                PackageRemovedInfo childOutInfo = (outInfo != null
19832                        && outInfo.removedChildPackages != null)
19833                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19834                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19835                        && (replacingPackage != null
19836                        && !replacingPackage.hasChildPackage(childPs.name))
19837                        ? flags & ~DELETE_KEEP_DATA : flags;
19838                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19839                        deleteFlags, writeSettings);
19840            }
19841        }
19842
19843        // Delete application code and resources only for parent packages
19844        if (ps.parentPackageName == null) {
19845            if (deleteCodeAndResources && (outInfo != null)) {
19846                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19847                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19848                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19849            }
19850        }
19851
19852        return true;
19853    }
19854
19855    @Override
19856    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19857            int userId) {
19858        mContext.enforceCallingOrSelfPermission(
19859                android.Manifest.permission.DELETE_PACKAGES, null);
19860        synchronized (mPackages) {
19861            // Cannot block uninstall of static shared libs as they are
19862            // considered a part of the using app (emulating static linking).
19863            // Also static libs are installed always on internal storage.
19864            PackageParser.Package pkg = mPackages.get(packageName);
19865            if (pkg != null && pkg.staticSharedLibName != null) {
19866                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19867                        + " providing static shared library: " + pkg.staticSharedLibName);
19868                return false;
19869            }
19870            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19871            mSettings.writePackageRestrictionsLPr(userId);
19872        }
19873        return true;
19874    }
19875
19876    @Override
19877    public boolean getBlockUninstallForUser(String packageName, int userId) {
19878        synchronized (mPackages) {
19879            final PackageSetting ps = mSettings.mPackages.get(packageName);
19880            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19881                return false;
19882            }
19883            return mSettings.getBlockUninstallLPr(userId, packageName);
19884        }
19885    }
19886
19887    @Override
19888    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19889        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19890        synchronized (mPackages) {
19891            PackageSetting ps = mSettings.mPackages.get(packageName);
19892            if (ps == null) {
19893                Log.w(TAG, "Package doesn't exist: " + packageName);
19894                return false;
19895            }
19896            if (systemUserApp) {
19897                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19898            } else {
19899                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19900            }
19901            mSettings.writeLPr();
19902        }
19903        return true;
19904    }
19905
19906    /*
19907     * This method handles package deletion in general
19908     */
19909    private boolean deletePackageLIF(String packageName, UserHandle user,
19910            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19911            PackageRemovedInfo outInfo, boolean writeSettings,
19912            PackageParser.Package replacingPackage) {
19913        if (packageName == null) {
19914            Slog.w(TAG, "Attempt to delete null packageName.");
19915            return false;
19916        }
19917
19918        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19919
19920        PackageSetting ps;
19921        synchronized (mPackages) {
19922            ps = mSettings.mPackages.get(packageName);
19923            if (ps == null) {
19924                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19925                return false;
19926            }
19927
19928            if (ps.parentPackageName != null && (!isSystemApp(ps)
19929                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19930                if (DEBUG_REMOVE) {
19931                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19932                            + ((user == null) ? UserHandle.USER_ALL : user));
19933                }
19934                final int removedUserId = (user != null) ? user.getIdentifier()
19935                        : UserHandle.USER_ALL;
19936                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19937                    return false;
19938                }
19939                markPackageUninstalledForUserLPw(ps, user);
19940                scheduleWritePackageRestrictionsLocked(user);
19941                return true;
19942            }
19943        }
19944
19945        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19946                && user.getIdentifier() != UserHandle.USER_ALL)) {
19947            // The caller is asking that the package only be deleted for a single
19948            // user.  To do this, we just mark its uninstalled state and delete
19949            // its data. If this is a system app, we only allow this to happen if
19950            // they have set the special DELETE_SYSTEM_APP which requests different
19951            // semantics than normal for uninstalling system apps.
19952            markPackageUninstalledForUserLPw(ps, user);
19953
19954            if (!isSystemApp(ps)) {
19955                // Do not uninstall the APK if an app should be cached
19956                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19957                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19958                    // Other user still have this package installed, so all
19959                    // we need to do is clear this user's data and save that
19960                    // it is uninstalled.
19961                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19962                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19963                        return false;
19964                    }
19965                    scheduleWritePackageRestrictionsLocked(user);
19966                    return true;
19967                } else {
19968                    // We need to set it back to 'installed' so the uninstall
19969                    // broadcasts will be sent correctly.
19970                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19971                    ps.setInstalled(true, user.getIdentifier());
19972                    mSettings.writeKernelMappingLPr(ps);
19973                }
19974            } else {
19975                // This is a system app, so we assume that the
19976                // other users still have this package installed, so all
19977                // we need to do is clear this user's data and save that
19978                // it is uninstalled.
19979                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19980                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19981                    return false;
19982                }
19983                scheduleWritePackageRestrictionsLocked(user);
19984                return true;
19985            }
19986        }
19987
19988        // If we are deleting a composite package for all users, keep track
19989        // of result for each child.
19990        if (ps.childPackageNames != null && outInfo != null) {
19991            synchronized (mPackages) {
19992                final int childCount = ps.childPackageNames.size();
19993                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19994                for (int i = 0; i < childCount; i++) {
19995                    String childPackageName = ps.childPackageNames.get(i);
19996                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19997                    childInfo.removedPackage = childPackageName;
19998                    childInfo.installerPackageName = ps.installerPackageName;
19999                    outInfo.removedChildPackages.put(childPackageName, childInfo);
20000                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20001                    if (childPs != null) {
20002                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
20003                    }
20004                }
20005            }
20006        }
20007
20008        boolean ret = false;
20009        if (isSystemApp(ps)) {
20010            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
20011            // When an updated system application is deleted we delete the existing resources
20012            // as well and fall back to existing code in system partition
20013            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
20014        } else {
20015            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
20016            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
20017                    outInfo, writeSettings, replacingPackage);
20018        }
20019
20020        // Take a note whether we deleted the package for all users
20021        if (outInfo != null) {
20022            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
20023            if (outInfo.removedChildPackages != null) {
20024                synchronized (mPackages) {
20025                    final int childCount = outInfo.removedChildPackages.size();
20026                    for (int i = 0; i < childCount; i++) {
20027                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
20028                        if (childInfo != null) {
20029                            childInfo.removedForAllUsers = mPackages.get(
20030                                    childInfo.removedPackage) == null;
20031                        }
20032                    }
20033                }
20034            }
20035            // If we uninstalled an update to a system app there may be some
20036            // child packages that appeared as they are declared in the system
20037            // app but were not declared in the update.
20038            if (isSystemApp(ps)) {
20039                synchronized (mPackages) {
20040                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20041                    final int childCount = (updatedPs.childPackageNames != null)
20042                            ? updatedPs.childPackageNames.size() : 0;
20043                    for (int i = 0; i < childCount; i++) {
20044                        String childPackageName = updatedPs.childPackageNames.get(i);
20045                        if (outInfo.removedChildPackages == null
20046                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20047                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20048                            if (childPs == null) {
20049                                continue;
20050                            }
20051                            PackageInstalledInfo installRes = new PackageInstalledInfo();
20052                            installRes.name = childPackageName;
20053                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20054                            installRes.pkg = mPackages.get(childPackageName);
20055                            installRes.uid = childPs.pkg.applicationInfo.uid;
20056                            if (outInfo.appearedChildPackages == null) {
20057                                outInfo.appearedChildPackages = new ArrayMap<>();
20058                            }
20059                            outInfo.appearedChildPackages.put(childPackageName, installRes);
20060                        }
20061                    }
20062                }
20063            }
20064        }
20065
20066        return ret;
20067    }
20068
20069    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20070        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20071                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20072        for (int nextUserId : userIds) {
20073            if (DEBUG_REMOVE) {
20074                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20075            }
20076            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20077                    false /*installed*/,
20078                    true /*stopped*/,
20079                    true /*notLaunched*/,
20080                    false /*hidden*/,
20081                    false /*suspended*/,
20082                    false /*instantApp*/,
20083                    false /*virtualPreload*/,
20084                    null /*lastDisableAppCaller*/,
20085                    null /*enabledComponents*/,
20086                    null /*disabledComponents*/,
20087                    ps.readUserState(nextUserId).domainVerificationStatus,
20088                    0, PackageManager.INSTALL_REASON_UNKNOWN);
20089        }
20090        mSettings.writeKernelMappingLPr(ps);
20091    }
20092
20093    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20094            PackageRemovedInfo outInfo) {
20095        final PackageParser.Package pkg;
20096        synchronized (mPackages) {
20097            pkg = mPackages.get(ps.name);
20098        }
20099
20100        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20101                : new int[] {userId};
20102        for (int nextUserId : userIds) {
20103            if (DEBUG_REMOVE) {
20104                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20105                        + nextUserId);
20106            }
20107
20108            destroyAppDataLIF(pkg, userId,
20109                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20110            destroyAppProfilesLIF(pkg, userId);
20111            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20112            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20113            schedulePackageCleaning(ps.name, nextUserId, false);
20114            synchronized (mPackages) {
20115                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20116                    scheduleWritePackageRestrictionsLocked(nextUserId);
20117                }
20118                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20119            }
20120        }
20121
20122        if (outInfo != null) {
20123            outInfo.removedPackage = ps.name;
20124            outInfo.installerPackageName = ps.installerPackageName;
20125            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20126            outInfo.removedAppId = ps.appId;
20127            outInfo.removedUsers = userIds;
20128            outInfo.broadcastUsers = userIds;
20129        }
20130
20131        return true;
20132    }
20133
20134    private final class ClearStorageConnection implements ServiceConnection {
20135        IMediaContainerService mContainerService;
20136
20137        @Override
20138        public void onServiceConnected(ComponentName name, IBinder service) {
20139            synchronized (this) {
20140                mContainerService = IMediaContainerService.Stub
20141                        .asInterface(Binder.allowBlocking(service));
20142                notifyAll();
20143            }
20144        }
20145
20146        @Override
20147        public void onServiceDisconnected(ComponentName name) {
20148        }
20149    }
20150
20151    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20152        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20153
20154        final boolean mounted;
20155        if (Environment.isExternalStorageEmulated()) {
20156            mounted = true;
20157        } else {
20158            final String status = Environment.getExternalStorageState();
20159
20160            mounted = status.equals(Environment.MEDIA_MOUNTED)
20161                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20162        }
20163
20164        if (!mounted) {
20165            return;
20166        }
20167
20168        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20169        int[] users;
20170        if (userId == UserHandle.USER_ALL) {
20171            users = sUserManager.getUserIds();
20172        } else {
20173            users = new int[] { userId };
20174        }
20175        final ClearStorageConnection conn = new ClearStorageConnection();
20176        if (mContext.bindServiceAsUser(
20177                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20178            try {
20179                for (int curUser : users) {
20180                    long timeout = SystemClock.uptimeMillis() + 5000;
20181                    synchronized (conn) {
20182                        long now;
20183                        while (conn.mContainerService == null &&
20184                                (now = SystemClock.uptimeMillis()) < timeout) {
20185                            try {
20186                                conn.wait(timeout - now);
20187                            } catch (InterruptedException e) {
20188                            }
20189                        }
20190                    }
20191                    if (conn.mContainerService == null) {
20192                        return;
20193                    }
20194
20195                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20196                    clearDirectory(conn.mContainerService,
20197                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20198                    if (allData) {
20199                        clearDirectory(conn.mContainerService,
20200                                userEnv.buildExternalStorageAppDataDirs(packageName));
20201                        clearDirectory(conn.mContainerService,
20202                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20203                    }
20204                }
20205            } finally {
20206                mContext.unbindService(conn);
20207            }
20208        }
20209    }
20210
20211    @Override
20212    public void clearApplicationProfileData(String packageName) {
20213        enforceSystemOrRoot("Only the system can clear all profile data");
20214
20215        final PackageParser.Package pkg;
20216        synchronized (mPackages) {
20217            pkg = mPackages.get(packageName);
20218        }
20219
20220        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20221            synchronized (mInstallLock) {
20222                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20223            }
20224        }
20225    }
20226
20227    @Override
20228    public void clearApplicationUserData(final String packageName,
20229            final IPackageDataObserver observer, final int userId) {
20230        mContext.enforceCallingOrSelfPermission(
20231                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20232
20233        final int callingUid = Binder.getCallingUid();
20234        enforceCrossUserPermission(callingUid, userId,
20235                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20236
20237        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20238        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
20239            return;
20240        }
20241        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20242            throw new SecurityException("Cannot clear data for a protected package: "
20243                    + packageName);
20244        }
20245        // Queue up an async operation since the package deletion may take a little while.
20246        mHandler.post(new Runnable() {
20247            public void run() {
20248                mHandler.removeCallbacks(this);
20249                final boolean succeeded;
20250                try (PackageFreezer freezer = freezePackage(packageName,
20251                        "clearApplicationUserData")) {
20252                    synchronized (mInstallLock) {
20253                        succeeded = clearApplicationUserDataLIF(packageName, userId);
20254                    }
20255                    clearExternalStorageDataSync(packageName, userId, true);
20256                    synchronized (mPackages) {
20257                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20258                                packageName, userId);
20259                    }
20260                }
20261                if (succeeded) {
20262                    // invoke DeviceStorageMonitor's update method to clear any notifications
20263                    DeviceStorageMonitorInternal dsm = LocalServices
20264                            .getService(DeviceStorageMonitorInternal.class);
20265                    if (dsm != null) {
20266                        dsm.checkMemory();
20267                    }
20268                }
20269                if(observer != null) {
20270                    try {
20271                        observer.onRemoveCompleted(packageName, succeeded);
20272                    } catch (RemoteException e) {
20273                        Log.i(TAG, "Observer no longer exists.");
20274                    }
20275                } //end if observer
20276            } //end run
20277        });
20278    }
20279
20280    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20281        if (packageName == null) {
20282            Slog.w(TAG, "Attempt to delete null packageName.");
20283            return false;
20284        }
20285
20286        // Try finding details about the requested package
20287        PackageParser.Package pkg;
20288        synchronized (mPackages) {
20289            pkg = mPackages.get(packageName);
20290            if (pkg == null) {
20291                final PackageSetting ps = mSettings.mPackages.get(packageName);
20292                if (ps != null) {
20293                    pkg = ps.pkg;
20294                }
20295            }
20296
20297            if (pkg == null) {
20298                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20299                return false;
20300            }
20301
20302            PackageSetting ps = (PackageSetting) pkg.mExtras;
20303            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20304        }
20305
20306        clearAppDataLIF(pkg, userId,
20307                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20308
20309        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20310        removeKeystoreDataIfNeeded(userId, appId);
20311
20312        UserManagerInternal umInternal = getUserManagerInternal();
20313        final int flags;
20314        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20315            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20316        } else if (umInternal.isUserRunning(userId)) {
20317            flags = StorageManager.FLAG_STORAGE_DE;
20318        } else {
20319            flags = 0;
20320        }
20321        prepareAppDataContentsLIF(pkg, userId, flags);
20322
20323        return true;
20324    }
20325
20326    /**
20327     * Reverts user permission state changes (permissions and flags) in
20328     * all packages for a given user.
20329     *
20330     * @param userId The device user for which to do a reset.
20331     */
20332    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20333        final int packageCount = mPackages.size();
20334        for (int i = 0; i < packageCount; i++) {
20335            PackageParser.Package pkg = mPackages.valueAt(i);
20336            PackageSetting ps = (PackageSetting) pkg.mExtras;
20337            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20338        }
20339    }
20340
20341    private void resetNetworkPolicies(int userId) {
20342        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20343    }
20344
20345    /**
20346     * Reverts user permission state changes (permissions and flags).
20347     *
20348     * @param ps The package for which to reset.
20349     * @param userId The device user for which to do a reset.
20350     */
20351    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20352            final PackageSetting ps, final int userId) {
20353        if (ps.pkg == null) {
20354            return;
20355        }
20356
20357        // These are flags that can change base on user actions.
20358        final int userSettableMask = FLAG_PERMISSION_USER_SET
20359                | FLAG_PERMISSION_USER_FIXED
20360                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20361                | FLAG_PERMISSION_REVIEW_REQUIRED;
20362
20363        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20364                | FLAG_PERMISSION_POLICY_FIXED;
20365
20366        boolean writeInstallPermissions = false;
20367        boolean writeRuntimePermissions = false;
20368
20369        final int permissionCount = ps.pkg.requestedPermissions.size();
20370        for (int i = 0; i < permissionCount; i++) {
20371            String permission = ps.pkg.requestedPermissions.get(i);
20372
20373            BasePermission bp = mSettings.mPermissions.get(permission);
20374            if (bp == null) {
20375                continue;
20376            }
20377
20378            // If shared user we just reset the state to which only this app contributed.
20379            if (ps.sharedUser != null) {
20380                boolean used = false;
20381                final int packageCount = ps.sharedUser.packages.size();
20382                for (int j = 0; j < packageCount; j++) {
20383                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20384                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20385                            && pkg.pkg.requestedPermissions.contains(permission)) {
20386                        used = true;
20387                        break;
20388                    }
20389                }
20390                if (used) {
20391                    continue;
20392                }
20393            }
20394
20395            PermissionsState permissionsState = ps.getPermissionsState();
20396
20397            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20398
20399            // Always clear the user settable flags.
20400            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20401                    bp.name) != null;
20402            // If permission review is enabled and this is a legacy app, mark the
20403            // permission as requiring a review as this is the initial state.
20404            int flags = 0;
20405            if (mPermissionReviewRequired
20406                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20407                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20408            }
20409            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20410                if (hasInstallState) {
20411                    writeInstallPermissions = true;
20412                } else {
20413                    writeRuntimePermissions = true;
20414                }
20415            }
20416
20417            // Below is only runtime permission handling.
20418            if (!bp.isRuntime()) {
20419                continue;
20420            }
20421
20422            // Never clobber system or policy.
20423            if ((oldFlags & policyOrSystemFlags) != 0) {
20424                continue;
20425            }
20426
20427            // If this permission was granted by default, make sure it is.
20428            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20429                if (permissionsState.grantRuntimePermission(bp, userId)
20430                        != PERMISSION_OPERATION_FAILURE) {
20431                    writeRuntimePermissions = true;
20432                }
20433            // If permission review is enabled the permissions for a legacy apps
20434            // are represented as constantly granted runtime ones, so don't revoke.
20435            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20436                // Otherwise, reset the permission.
20437                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20438                switch (revokeResult) {
20439                    case PERMISSION_OPERATION_SUCCESS:
20440                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20441                        writeRuntimePermissions = true;
20442                        final int appId = ps.appId;
20443                        mHandler.post(new Runnable() {
20444                            @Override
20445                            public void run() {
20446                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20447                            }
20448                        });
20449                    } break;
20450                }
20451            }
20452        }
20453
20454        // Synchronously write as we are taking permissions away.
20455        if (writeRuntimePermissions) {
20456            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20457        }
20458
20459        // Synchronously write as we are taking permissions away.
20460        if (writeInstallPermissions) {
20461            mSettings.writeLPr();
20462        }
20463    }
20464
20465    /**
20466     * Remove entries from the keystore daemon. Will only remove it if the
20467     * {@code appId} is valid.
20468     */
20469    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20470        if (appId < 0) {
20471            return;
20472        }
20473
20474        final KeyStore keyStore = KeyStore.getInstance();
20475        if (keyStore != null) {
20476            if (userId == UserHandle.USER_ALL) {
20477                for (final int individual : sUserManager.getUserIds()) {
20478                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20479                }
20480            } else {
20481                keyStore.clearUid(UserHandle.getUid(userId, appId));
20482            }
20483        } else {
20484            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20485        }
20486    }
20487
20488    @Override
20489    public void deleteApplicationCacheFiles(final String packageName,
20490            final IPackageDataObserver observer) {
20491        final int userId = UserHandle.getCallingUserId();
20492        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20493    }
20494
20495    @Override
20496    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20497            final IPackageDataObserver observer) {
20498        final int callingUid = Binder.getCallingUid();
20499        mContext.enforceCallingOrSelfPermission(
20500                android.Manifest.permission.DELETE_CACHE_FILES, null);
20501        enforceCrossUserPermission(callingUid, userId,
20502                /* requireFullPermission= */ true, /* checkShell= */ false,
20503                "delete application cache files");
20504        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20505                android.Manifest.permission.ACCESS_INSTANT_APPS);
20506
20507        final PackageParser.Package pkg;
20508        synchronized (mPackages) {
20509            pkg = mPackages.get(packageName);
20510        }
20511
20512        // Queue up an async operation since the package deletion may take a little while.
20513        mHandler.post(new Runnable() {
20514            public void run() {
20515                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20516                boolean doClearData = true;
20517                if (ps != null) {
20518                    final boolean targetIsInstantApp =
20519                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20520                    doClearData = !targetIsInstantApp
20521                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20522                }
20523                if (doClearData) {
20524                    synchronized (mInstallLock) {
20525                        final int flags = StorageManager.FLAG_STORAGE_DE
20526                                | StorageManager.FLAG_STORAGE_CE;
20527                        // We're only clearing cache files, so we don't care if the
20528                        // app is unfrozen and still able to run
20529                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20530                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20531                    }
20532                    clearExternalStorageDataSync(packageName, userId, false);
20533                }
20534                if (observer != null) {
20535                    try {
20536                        observer.onRemoveCompleted(packageName, true);
20537                    } catch (RemoteException e) {
20538                        Log.i(TAG, "Observer no longer exists.");
20539                    }
20540                }
20541            }
20542        });
20543    }
20544
20545    @Override
20546    public void getPackageSizeInfo(final String packageName, int userHandle,
20547            final IPackageStatsObserver observer) {
20548        throw new UnsupportedOperationException(
20549                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20550    }
20551
20552    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20553        final PackageSetting ps;
20554        synchronized (mPackages) {
20555            ps = mSettings.mPackages.get(packageName);
20556            if (ps == null) {
20557                Slog.w(TAG, "Failed to find settings for " + packageName);
20558                return false;
20559            }
20560        }
20561
20562        final String[] packageNames = { packageName };
20563        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20564        final String[] codePaths = { ps.codePathString };
20565
20566        try {
20567            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20568                    ps.appId, ceDataInodes, codePaths, stats);
20569
20570            // For now, ignore code size of packages on system partition
20571            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20572                stats.codeSize = 0;
20573            }
20574
20575            // External clients expect these to be tracked separately
20576            stats.dataSize -= stats.cacheSize;
20577
20578        } catch (InstallerException e) {
20579            Slog.w(TAG, String.valueOf(e));
20580            return false;
20581        }
20582
20583        return true;
20584    }
20585
20586    private int getUidTargetSdkVersionLockedLPr(int uid) {
20587        Object obj = mSettings.getUserIdLPr(uid);
20588        if (obj instanceof SharedUserSetting) {
20589            final SharedUserSetting sus = (SharedUserSetting) obj;
20590            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20591            final Iterator<PackageSetting> it = sus.packages.iterator();
20592            while (it.hasNext()) {
20593                final PackageSetting ps = it.next();
20594                if (ps.pkg != null) {
20595                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20596                    if (v < vers) vers = v;
20597                }
20598            }
20599            return vers;
20600        } else if (obj instanceof PackageSetting) {
20601            final PackageSetting ps = (PackageSetting) obj;
20602            if (ps.pkg != null) {
20603                return ps.pkg.applicationInfo.targetSdkVersion;
20604            }
20605        }
20606        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20607    }
20608
20609    @Override
20610    public void addPreferredActivity(IntentFilter filter, int match,
20611            ComponentName[] set, ComponentName activity, int userId) {
20612        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20613                "Adding preferred");
20614    }
20615
20616    private void addPreferredActivityInternal(IntentFilter filter, int match,
20617            ComponentName[] set, ComponentName activity, boolean always, int userId,
20618            String opname) {
20619        // writer
20620        int callingUid = Binder.getCallingUid();
20621        enforceCrossUserPermission(callingUid, userId,
20622                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20623        if (filter.countActions() == 0) {
20624            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20625            return;
20626        }
20627        synchronized (mPackages) {
20628            if (mContext.checkCallingOrSelfPermission(
20629                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20630                    != PackageManager.PERMISSION_GRANTED) {
20631                if (getUidTargetSdkVersionLockedLPr(callingUid)
20632                        < Build.VERSION_CODES.FROYO) {
20633                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20634                            + callingUid);
20635                    return;
20636                }
20637                mContext.enforceCallingOrSelfPermission(
20638                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20639            }
20640
20641            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20642            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20643                    + userId + ":");
20644            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20645            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20646            scheduleWritePackageRestrictionsLocked(userId);
20647            postPreferredActivityChangedBroadcast(userId);
20648        }
20649    }
20650
20651    private void postPreferredActivityChangedBroadcast(int userId) {
20652        mHandler.post(() -> {
20653            final IActivityManager am = ActivityManager.getService();
20654            if (am == null) {
20655                return;
20656            }
20657
20658            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20659            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20660            try {
20661                am.broadcastIntent(null, intent, null, null,
20662                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20663                        null, false, false, userId);
20664            } catch (RemoteException e) {
20665            }
20666        });
20667    }
20668
20669    @Override
20670    public void replacePreferredActivity(IntentFilter filter, int match,
20671            ComponentName[] set, ComponentName activity, int userId) {
20672        if (filter.countActions() != 1) {
20673            throw new IllegalArgumentException(
20674                    "replacePreferredActivity expects filter to have only 1 action.");
20675        }
20676        if (filter.countDataAuthorities() != 0
20677                || filter.countDataPaths() != 0
20678                || filter.countDataSchemes() > 1
20679                || filter.countDataTypes() != 0) {
20680            throw new IllegalArgumentException(
20681                    "replacePreferredActivity expects filter to have no data authorities, " +
20682                    "paths, or types; and at most one scheme.");
20683        }
20684
20685        final int callingUid = Binder.getCallingUid();
20686        enforceCrossUserPermission(callingUid, userId,
20687                true /* requireFullPermission */, false /* checkShell */,
20688                "replace preferred activity");
20689        synchronized (mPackages) {
20690            if (mContext.checkCallingOrSelfPermission(
20691                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20692                    != PackageManager.PERMISSION_GRANTED) {
20693                if (getUidTargetSdkVersionLockedLPr(callingUid)
20694                        < Build.VERSION_CODES.FROYO) {
20695                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20696                            + Binder.getCallingUid());
20697                    return;
20698                }
20699                mContext.enforceCallingOrSelfPermission(
20700                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20701            }
20702
20703            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20704            if (pir != null) {
20705                // Get all of the existing entries that exactly match this filter.
20706                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20707                if (existing != null && existing.size() == 1) {
20708                    PreferredActivity cur = existing.get(0);
20709                    if (DEBUG_PREFERRED) {
20710                        Slog.i(TAG, "Checking replace of preferred:");
20711                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20712                        if (!cur.mPref.mAlways) {
20713                            Slog.i(TAG, "  -- CUR; not mAlways!");
20714                        } else {
20715                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20716                            Slog.i(TAG, "  -- CUR: mSet="
20717                                    + Arrays.toString(cur.mPref.mSetComponents));
20718                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20719                            Slog.i(TAG, "  -- NEW: mMatch="
20720                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20721                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20722                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20723                        }
20724                    }
20725                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20726                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20727                            && cur.mPref.sameSet(set)) {
20728                        // Setting the preferred activity to what it happens to be already
20729                        if (DEBUG_PREFERRED) {
20730                            Slog.i(TAG, "Replacing with same preferred activity "
20731                                    + cur.mPref.mShortComponent + " for user "
20732                                    + userId + ":");
20733                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20734                        }
20735                        return;
20736                    }
20737                }
20738
20739                if (existing != null) {
20740                    if (DEBUG_PREFERRED) {
20741                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20742                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20743                    }
20744                    for (int i = 0; i < existing.size(); i++) {
20745                        PreferredActivity pa = existing.get(i);
20746                        if (DEBUG_PREFERRED) {
20747                            Slog.i(TAG, "Removing existing preferred activity "
20748                                    + pa.mPref.mComponent + ":");
20749                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20750                        }
20751                        pir.removeFilter(pa);
20752                    }
20753                }
20754            }
20755            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20756                    "Replacing preferred");
20757        }
20758    }
20759
20760    @Override
20761    public void clearPackagePreferredActivities(String packageName) {
20762        final int callingUid = Binder.getCallingUid();
20763        if (getInstantAppPackageName(callingUid) != null) {
20764            return;
20765        }
20766        // writer
20767        synchronized (mPackages) {
20768            PackageParser.Package pkg = mPackages.get(packageName);
20769            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20770                if (mContext.checkCallingOrSelfPermission(
20771                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20772                        != PackageManager.PERMISSION_GRANTED) {
20773                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20774                            < Build.VERSION_CODES.FROYO) {
20775                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20776                                + callingUid);
20777                        return;
20778                    }
20779                    mContext.enforceCallingOrSelfPermission(
20780                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20781                }
20782            }
20783            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20784            if (ps != null
20785                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20786                return;
20787            }
20788            int user = UserHandle.getCallingUserId();
20789            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20790                scheduleWritePackageRestrictionsLocked(user);
20791            }
20792        }
20793    }
20794
20795    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20796    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20797        ArrayList<PreferredActivity> removed = null;
20798        boolean changed = false;
20799        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20800            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20801            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20802            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20803                continue;
20804            }
20805            Iterator<PreferredActivity> it = pir.filterIterator();
20806            while (it.hasNext()) {
20807                PreferredActivity pa = it.next();
20808                // Mark entry for removal only if it matches the package name
20809                // and the entry is of type "always".
20810                if (packageName == null ||
20811                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20812                                && pa.mPref.mAlways)) {
20813                    if (removed == null) {
20814                        removed = new ArrayList<PreferredActivity>();
20815                    }
20816                    removed.add(pa);
20817                }
20818            }
20819            if (removed != null) {
20820                for (int j=0; j<removed.size(); j++) {
20821                    PreferredActivity pa = removed.get(j);
20822                    pir.removeFilter(pa);
20823                }
20824                changed = true;
20825            }
20826        }
20827        if (changed) {
20828            postPreferredActivityChangedBroadcast(userId);
20829        }
20830        return changed;
20831    }
20832
20833    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20834    private void clearIntentFilterVerificationsLPw(int userId) {
20835        final int packageCount = mPackages.size();
20836        for (int i = 0; i < packageCount; i++) {
20837            PackageParser.Package pkg = mPackages.valueAt(i);
20838            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20839        }
20840    }
20841
20842    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20843    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20844        if (userId == UserHandle.USER_ALL) {
20845            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20846                    sUserManager.getUserIds())) {
20847                for (int oneUserId : sUserManager.getUserIds()) {
20848                    scheduleWritePackageRestrictionsLocked(oneUserId);
20849                }
20850            }
20851        } else {
20852            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20853                scheduleWritePackageRestrictionsLocked(userId);
20854            }
20855        }
20856    }
20857
20858    /** Clears state for all users, and touches intent filter verification policy */
20859    void clearDefaultBrowserIfNeeded(String packageName) {
20860        for (int oneUserId : sUserManager.getUserIds()) {
20861            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20862        }
20863    }
20864
20865    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20866        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20867        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20868            if (packageName.equals(defaultBrowserPackageName)) {
20869                setDefaultBrowserPackageName(null, userId);
20870            }
20871        }
20872    }
20873
20874    @Override
20875    public void resetApplicationPreferences(int userId) {
20876        mContext.enforceCallingOrSelfPermission(
20877                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20878        final long identity = Binder.clearCallingIdentity();
20879        // writer
20880        try {
20881            synchronized (mPackages) {
20882                clearPackagePreferredActivitiesLPw(null, userId);
20883                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20884                // TODO: We have to reset the default SMS and Phone. This requires
20885                // significant refactoring to keep all default apps in the package
20886                // manager (cleaner but more work) or have the services provide
20887                // callbacks to the package manager to request a default app reset.
20888                applyFactoryDefaultBrowserLPw(userId);
20889                clearIntentFilterVerificationsLPw(userId);
20890                primeDomainVerificationsLPw(userId);
20891                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20892                scheduleWritePackageRestrictionsLocked(userId);
20893            }
20894            resetNetworkPolicies(userId);
20895        } finally {
20896            Binder.restoreCallingIdentity(identity);
20897        }
20898    }
20899
20900    @Override
20901    public int getPreferredActivities(List<IntentFilter> outFilters,
20902            List<ComponentName> outActivities, String packageName) {
20903        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20904            return 0;
20905        }
20906        int num = 0;
20907        final int userId = UserHandle.getCallingUserId();
20908        // reader
20909        synchronized (mPackages) {
20910            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20911            if (pir != null) {
20912                final Iterator<PreferredActivity> it = pir.filterIterator();
20913                while (it.hasNext()) {
20914                    final PreferredActivity pa = it.next();
20915                    if (packageName == null
20916                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20917                                    && pa.mPref.mAlways)) {
20918                        if (outFilters != null) {
20919                            outFilters.add(new IntentFilter(pa));
20920                        }
20921                        if (outActivities != null) {
20922                            outActivities.add(pa.mPref.mComponent);
20923                        }
20924                    }
20925                }
20926            }
20927        }
20928
20929        return num;
20930    }
20931
20932    @Override
20933    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20934            int userId) {
20935        int callingUid = Binder.getCallingUid();
20936        if (callingUid != Process.SYSTEM_UID) {
20937            throw new SecurityException(
20938                    "addPersistentPreferredActivity can only be run by the system");
20939        }
20940        if (filter.countActions() == 0) {
20941            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20942            return;
20943        }
20944        synchronized (mPackages) {
20945            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20946                    ":");
20947            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20948            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20949                    new PersistentPreferredActivity(filter, activity));
20950            scheduleWritePackageRestrictionsLocked(userId);
20951            postPreferredActivityChangedBroadcast(userId);
20952        }
20953    }
20954
20955    @Override
20956    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20957        int callingUid = Binder.getCallingUid();
20958        if (callingUid != Process.SYSTEM_UID) {
20959            throw new SecurityException(
20960                    "clearPackagePersistentPreferredActivities can only be run by the system");
20961        }
20962        ArrayList<PersistentPreferredActivity> removed = null;
20963        boolean changed = false;
20964        synchronized (mPackages) {
20965            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20966                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20967                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20968                        .valueAt(i);
20969                if (userId != thisUserId) {
20970                    continue;
20971                }
20972                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20973                while (it.hasNext()) {
20974                    PersistentPreferredActivity ppa = it.next();
20975                    // Mark entry for removal only if it matches the package name.
20976                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20977                        if (removed == null) {
20978                            removed = new ArrayList<PersistentPreferredActivity>();
20979                        }
20980                        removed.add(ppa);
20981                    }
20982                }
20983                if (removed != null) {
20984                    for (int j=0; j<removed.size(); j++) {
20985                        PersistentPreferredActivity ppa = removed.get(j);
20986                        ppir.removeFilter(ppa);
20987                    }
20988                    changed = true;
20989                }
20990            }
20991
20992            if (changed) {
20993                scheduleWritePackageRestrictionsLocked(userId);
20994                postPreferredActivityChangedBroadcast(userId);
20995            }
20996        }
20997    }
20998
20999    /**
21000     * Common machinery for picking apart a restored XML blob and passing
21001     * it to a caller-supplied functor to be applied to the running system.
21002     */
21003    private void restoreFromXml(XmlPullParser parser, int userId,
21004            String expectedStartTag, BlobXmlRestorer functor)
21005            throws IOException, XmlPullParserException {
21006        int type;
21007        while ((type = parser.next()) != XmlPullParser.START_TAG
21008                && type != XmlPullParser.END_DOCUMENT) {
21009        }
21010        if (type != XmlPullParser.START_TAG) {
21011            // oops didn't find a start tag?!
21012            if (DEBUG_BACKUP) {
21013                Slog.e(TAG, "Didn't find start tag during restore");
21014            }
21015            return;
21016        }
21017Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
21018        // this is supposed to be TAG_PREFERRED_BACKUP
21019        if (!expectedStartTag.equals(parser.getName())) {
21020            if (DEBUG_BACKUP) {
21021                Slog.e(TAG, "Found unexpected tag " + parser.getName());
21022            }
21023            return;
21024        }
21025
21026        // skip interfering stuff, then we're aligned with the backing implementation
21027        while ((type = parser.next()) == XmlPullParser.TEXT) { }
21028Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
21029        functor.apply(parser, userId);
21030    }
21031
21032    private interface BlobXmlRestorer {
21033        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
21034    }
21035
21036    /**
21037     * Non-Binder method, support for the backup/restore mechanism: write the
21038     * full set of preferred activities in its canonical XML format.  Returns the
21039     * XML output as a byte array, or null if there is none.
21040     */
21041    @Override
21042    public byte[] getPreferredActivityBackup(int userId) {
21043        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21044            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21045        }
21046
21047        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21048        try {
21049            final XmlSerializer serializer = new FastXmlSerializer();
21050            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21051            serializer.startDocument(null, true);
21052            serializer.startTag(null, TAG_PREFERRED_BACKUP);
21053
21054            synchronized (mPackages) {
21055                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21056            }
21057
21058            serializer.endTag(null, TAG_PREFERRED_BACKUP);
21059            serializer.endDocument();
21060            serializer.flush();
21061        } catch (Exception e) {
21062            if (DEBUG_BACKUP) {
21063                Slog.e(TAG, "Unable to write preferred activities for backup", e);
21064            }
21065            return null;
21066        }
21067
21068        return dataStream.toByteArray();
21069    }
21070
21071    @Override
21072    public void restorePreferredActivities(byte[] backup, int userId) {
21073        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21074            throw new SecurityException("Only the system may call restorePreferredActivities()");
21075        }
21076
21077        try {
21078            final XmlPullParser parser = Xml.newPullParser();
21079            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21080            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21081                    new BlobXmlRestorer() {
21082                        @Override
21083                        public void apply(XmlPullParser parser, int userId)
21084                                throws XmlPullParserException, IOException {
21085                            synchronized (mPackages) {
21086                                mSettings.readPreferredActivitiesLPw(parser, userId);
21087                            }
21088                        }
21089                    } );
21090        } catch (Exception e) {
21091            if (DEBUG_BACKUP) {
21092                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21093            }
21094        }
21095    }
21096
21097    /**
21098     * Non-Binder method, support for the backup/restore mechanism: write the
21099     * default browser (etc) settings in its canonical XML format.  Returns the default
21100     * browser XML representation as a byte array, or null if there is none.
21101     */
21102    @Override
21103    public byte[] getDefaultAppsBackup(int userId) {
21104        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21105            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21106        }
21107
21108        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21109        try {
21110            final XmlSerializer serializer = new FastXmlSerializer();
21111            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21112            serializer.startDocument(null, true);
21113            serializer.startTag(null, TAG_DEFAULT_APPS);
21114
21115            synchronized (mPackages) {
21116                mSettings.writeDefaultAppsLPr(serializer, userId);
21117            }
21118
21119            serializer.endTag(null, TAG_DEFAULT_APPS);
21120            serializer.endDocument();
21121            serializer.flush();
21122        } catch (Exception e) {
21123            if (DEBUG_BACKUP) {
21124                Slog.e(TAG, "Unable to write default apps for backup", e);
21125            }
21126            return null;
21127        }
21128
21129        return dataStream.toByteArray();
21130    }
21131
21132    @Override
21133    public void restoreDefaultApps(byte[] backup, int userId) {
21134        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21135            throw new SecurityException("Only the system may call restoreDefaultApps()");
21136        }
21137
21138        try {
21139            final XmlPullParser parser = Xml.newPullParser();
21140            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21141            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21142                    new BlobXmlRestorer() {
21143                        @Override
21144                        public void apply(XmlPullParser parser, int userId)
21145                                throws XmlPullParserException, IOException {
21146                            synchronized (mPackages) {
21147                                mSettings.readDefaultAppsLPw(parser, userId);
21148                            }
21149                        }
21150                    } );
21151        } catch (Exception e) {
21152            if (DEBUG_BACKUP) {
21153                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21154            }
21155        }
21156    }
21157
21158    @Override
21159    public byte[] getIntentFilterVerificationBackup(int userId) {
21160        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21161            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21162        }
21163
21164        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21165        try {
21166            final XmlSerializer serializer = new FastXmlSerializer();
21167            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21168            serializer.startDocument(null, true);
21169            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21170
21171            synchronized (mPackages) {
21172                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21173            }
21174
21175            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21176            serializer.endDocument();
21177            serializer.flush();
21178        } catch (Exception e) {
21179            if (DEBUG_BACKUP) {
21180                Slog.e(TAG, "Unable to write default apps for backup", e);
21181            }
21182            return null;
21183        }
21184
21185        return dataStream.toByteArray();
21186    }
21187
21188    @Override
21189    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21190        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21191            throw new SecurityException("Only the system may call restorePreferredActivities()");
21192        }
21193
21194        try {
21195            final XmlPullParser parser = Xml.newPullParser();
21196            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21197            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21198                    new BlobXmlRestorer() {
21199                        @Override
21200                        public void apply(XmlPullParser parser, int userId)
21201                                throws XmlPullParserException, IOException {
21202                            synchronized (mPackages) {
21203                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21204                                mSettings.writeLPr();
21205                            }
21206                        }
21207                    } );
21208        } catch (Exception e) {
21209            if (DEBUG_BACKUP) {
21210                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21211            }
21212        }
21213    }
21214
21215    @Override
21216    public byte[] getPermissionGrantBackup(int userId) {
21217        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21218            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21219        }
21220
21221        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21222        try {
21223            final XmlSerializer serializer = new FastXmlSerializer();
21224            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21225            serializer.startDocument(null, true);
21226            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21227
21228            synchronized (mPackages) {
21229                serializeRuntimePermissionGrantsLPr(serializer, userId);
21230            }
21231
21232            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21233            serializer.endDocument();
21234            serializer.flush();
21235        } catch (Exception e) {
21236            if (DEBUG_BACKUP) {
21237                Slog.e(TAG, "Unable to write default apps for backup", e);
21238            }
21239            return null;
21240        }
21241
21242        return dataStream.toByteArray();
21243    }
21244
21245    @Override
21246    public void restorePermissionGrants(byte[] backup, int userId) {
21247        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21248            throw new SecurityException("Only the system may call restorePermissionGrants()");
21249        }
21250
21251        try {
21252            final XmlPullParser parser = Xml.newPullParser();
21253            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21254            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21255                    new BlobXmlRestorer() {
21256                        @Override
21257                        public void apply(XmlPullParser parser, int userId)
21258                                throws XmlPullParserException, IOException {
21259                            synchronized (mPackages) {
21260                                processRestoredPermissionGrantsLPr(parser, userId);
21261                            }
21262                        }
21263                    } );
21264        } catch (Exception e) {
21265            if (DEBUG_BACKUP) {
21266                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21267            }
21268        }
21269    }
21270
21271    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21272            throws IOException {
21273        serializer.startTag(null, TAG_ALL_GRANTS);
21274
21275        final int N = mSettings.mPackages.size();
21276        for (int i = 0; i < N; i++) {
21277            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21278            boolean pkgGrantsKnown = false;
21279
21280            PermissionsState packagePerms = ps.getPermissionsState();
21281
21282            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21283                final int grantFlags = state.getFlags();
21284                // only look at grants that are not system/policy fixed
21285                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21286                    final boolean isGranted = state.isGranted();
21287                    // And only back up the user-twiddled state bits
21288                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21289                        final String packageName = mSettings.mPackages.keyAt(i);
21290                        if (!pkgGrantsKnown) {
21291                            serializer.startTag(null, TAG_GRANT);
21292                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21293                            pkgGrantsKnown = true;
21294                        }
21295
21296                        final boolean userSet =
21297                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21298                        final boolean userFixed =
21299                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21300                        final boolean revoke =
21301                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21302
21303                        serializer.startTag(null, TAG_PERMISSION);
21304                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21305                        if (isGranted) {
21306                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21307                        }
21308                        if (userSet) {
21309                            serializer.attribute(null, ATTR_USER_SET, "true");
21310                        }
21311                        if (userFixed) {
21312                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21313                        }
21314                        if (revoke) {
21315                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21316                        }
21317                        serializer.endTag(null, TAG_PERMISSION);
21318                    }
21319                }
21320            }
21321
21322            if (pkgGrantsKnown) {
21323                serializer.endTag(null, TAG_GRANT);
21324            }
21325        }
21326
21327        serializer.endTag(null, TAG_ALL_GRANTS);
21328    }
21329
21330    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21331            throws XmlPullParserException, IOException {
21332        String pkgName = null;
21333        int outerDepth = parser.getDepth();
21334        int type;
21335        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21336                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21337            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21338                continue;
21339            }
21340
21341            final String tagName = parser.getName();
21342            if (tagName.equals(TAG_GRANT)) {
21343                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21344                if (DEBUG_BACKUP) {
21345                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21346                }
21347            } else if (tagName.equals(TAG_PERMISSION)) {
21348
21349                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21350                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21351
21352                int newFlagSet = 0;
21353                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21354                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21355                }
21356                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21357                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21358                }
21359                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21360                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21361                }
21362                if (DEBUG_BACKUP) {
21363                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21364                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21365                }
21366                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21367                if (ps != null) {
21368                    // Already installed so we apply the grant immediately
21369                    if (DEBUG_BACKUP) {
21370                        Slog.v(TAG, "        + already installed; applying");
21371                    }
21372                    PermissionsState perms = ps.getPermissionsState();
21373                    BasePermission bp = mSettings.mPermissions.get(permName);
21374                    if (bp != null) {
21375                        if (isGranted) {
21376                            perms.grantRuntimePermission(bp, userId);
21377                        }
21378                        if (newFlagSet != 0) {
21379                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21380                        }
21381                    }
21382                } else {
21383                    // Need to wait for post-restore install to apply the grant
21384                    if (DEBUG_BACKUP) {
21385                        Slog.v(TAG, "        - not yet installed; saving for later");
21386                    }
21387                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21388                            isGranted, newFlagSet, userId);
21389                }
21390            } else {
21391                PackageManagerService.reportSettingsProblem(Log.WARN,
21392                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21393                XmlUtils.skipCurrentTag(parser);
21394            }
21395        }
21396
21397        scheduleWriteSettingsLocked();
21398        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21399    }
21400
21401    @Override
21402    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21403            int sourceUserId, int targetUserId, int flags) {
21404        mContext.enforceCallingOrSelfPermission(
21405                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21406        int callingUid = Binder.getCallingUid();
21407        enforceOwnerRights(ownerPackage, callingUid);
21408        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21409        if (intentFilter.countActions() == 0) {
21410            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21411            return;
21412        }
21413        synchronized (mPackages) {
21414            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21415                    ownerPackage, targetUserId, flags);
21416            CrossProfileIntentResolver resolver =
21417                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21418            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21419            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21420            if (existing != null) {
21421                int size = existing.size();
21422                for (int i = 0; i < size; i++) {
21423                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21424                        return;
21425                    }
21426                }
21427            }
21428            resolver.addFilter(newFilter);
21429            scheduleWritePackageRestrictionsLocked(sourceUserId);
21430        }
21431    }
21432
21433    @Override
21434    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21435        mContext.enforceCallingOrSelfPermission(
21436                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21437        final int callingUid = Binder.getCallingUid();
21438        enforceOwnerRights(ownerPackage, callingUid);
21439        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21440        synchronized (mPackages) {
21441            CrossProfileIntentResolver resolver =
21442                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21443            ArraySet<CrossProfileIntentFilter> set =
21444                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21445            for (CrossProfileIntentFilter filter : set) {
21446                if (filter.getOwnerPackage().equals(ownerPackage)) {
21447                    resolver.removeFilter(filter);
21448                }
21449            }
21450            scheduleWritePackageRestrictionsLocked(sourceUserId);
21451        }
21452    }
21453
21454    // Enforcing that callingUid is owning pkg on userId
21455    private void enforceOwnerRights(String pkg, int callingUid) {
21456        // The system owns everything.
21457        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21458            return;
21459        }
21460        final int callingUserId = UserHandle.getUserId(callingUid);
21461        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21462        if (pi == null) {
21463            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21464                    + callingUserId);
21465        }
21466        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21467            throw new SecurityException("Calling uid " + callingUid
21468                    + " does not own package " + pkg);
21469        }
21470    }
21471
21472    @Override
21473    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21474        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21475            return null;
21476        }
21477        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21478    }
21479
21480    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21481        UserManagerService ums = UserManagerService.getInstance();
21482        if (ums != null) {
21483            final UserInfo parent = ums.getProfileParent(userId);
21484            final int launcherUid = (parent != null) ? parent.id : userId;
21485            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21486            if (launcherComponent != null) {
21487                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21488                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21489                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21490                        .setPackage(launcherComponent.getPackageName());
21491                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21492            }
21493        }
21494    }
21495
21496    /**
21497     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21498     * then reports the most likely home activity or null if there are more than one.
21499     */
21500    private ComponentName getDefaultHomeActivity(int userId) {
21501        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21502        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21503        if (cn != null) {
21504            return cn;
21505        }
21506
21507        // Find the launcher with the highest priority and return that component if there are no
21508        // other home activity with the same priority.
21509        int lastPriority = Integer.MIN_VALUE;
21510        ComponentName lastComponent = null;
21511        final int size = allHomeCandidates.size();
21512        for (int i = 0; i < size; i++) {
21513            final ResolveInfo ri = allHomeCandidates.get(i);
21514            if (ri.priority > lastPriority) {
21515                lastComponent = ri.activityInfo.getComponentName();
21516                lastPriority = ri.priority;
21517            } else if (ri.priority == lastPriority) {
21518                // Two components found with same priority.
21519                lastComponent = null;
21520            }
21521        }
21522        return lastComponent;
21523    }
21524
21525    private Intent getHomeIntent() {
21526        Intent intent = new Intent(Intent.ACTION_MAIN);
21527        intent.addCategory(Intent.CATEGORY_HOME);
21528        intent.addCategory(Intent.CATEGORY_DEFAULT);
21529        return intent;
21530    }
21531
21532    private IntentFilter getHomeFilter() {
21533        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21534        filter.addCategory(Intent.CATEGORY_HOME);
21535        filter.addCategory(Intent.CATEGORY_DEFAULT);
21536        return filter;
21537    }
21538
21539    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21540            int userId) {
21541        Intent intent  = getHomeIntent();
21542        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21543                PackageManager.GET_META_DATA, userId);
21544        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21545                true, false, false, userId);
21546
21547        allHomeCandidates.clear();
21548        if (list != null) {
21549            for (ResolveInfo ri : list) {
21550                allHomeCandidates.add(ri);
21551            }
21552        }
21553        return (preferred == null || preferred.activityInfo == null)
21554                ? null
21555                : new ComponentName(preferred.activityInfo.packageName,
21556                        preferred.activityInfo.name);
21557    }
21558
21559    @Override
21560    public void setHomeActivity(ComponentName comp, int userId) {
21561        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21562            return;
21563        }
21564        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21565        getHomeActivitiesAsUser(homeActivities, userId);
21566
21567        boolean found = false;
21568
21569        final int size = homeActivities.size();
21570        final ComponentName[] set = new ComponentName[size];
21571        for (int i = 0; i < size; i++) {
21572            final ResolveInfo candidate = homeActivities.get(i);
21573            final ActivityInfo info = candidate.activityInfo;
21574            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21575            set[i] = activityName;
21576            if (!found && activityName.equals(comp)) {
21577                found = true;
21578            }
21579        }
21580        if (!found) {
21581            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21582                    + userId);
21583        }
21584        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21585                set, comp, userId);
21586    }
21587
21588    private @Nullable String getSetupWizardPackageName() {
21589        final Intent intent = new Intent(Intent.ACTION_MAIN);
21590        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21591
21592        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21593                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21594                        | MATCH_DISABLED_COMPONENTS,
21595                UserHandle.myUserId());
21596        if (matches.size() == 1) {
21597            return matches.get(0).getComponentInfo().packageName;
21598        } else {
21599            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21600                    + ": matches=" + matches);
21601            return null;
21602        }
21603    }
21604
21605    private @Nullable String getStorageManagerPackageName() {
21606        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21607
21608        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21609                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21610                        | MATCH_DISABLED_COMPONENTS,
21611                UserHandle.myUserId());
21612        if (matches.size() == 1) {
21613            return matches.get(0).getComponentInfo().packageName;
21614        } else {
21615            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21616                    + matches.size() + ": matches=" + matches);
21617            return null;
21618        }
21619    }
21620
21621    @Override
21622    public void setApplicationEnabledSetting(String appPackageName,
21623            int newState, int flags, int userId, String callingPackage) {
21624        if (!sUserManager.exists(userId)) return;
21625        if (callingPackage == null) {
21626            callingPackage = Integer.toString(Binder.getCallingUid());
21627        }
21628        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21629    }
21630
21631    @Override
21632    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21633        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21634        synchronized (mPackages) {
21635            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21636            if (pkgSetting != null) {
21637                pkgSetting.setUpdateAvailable(updateAvailable);
21638            }
21639        }
21640    }
21641
21642    @Override
21643    public void setComponentEnabledSetting(ComponentName componentName,
21644            int newState, int flags, int userId) {
21645        if (!sUserManager.exists(userId)) return;
21646        setEnabledSetting(componentName.getPackageName(),
21647                componentName.getClassName(), newState, flags, userId, null);
21648    }
21649
21650    private void setEnabledSetting(final String packageName, String className, int newState,
21651            final int flags, int userId, String callingPackage) {
21652        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21653              || newState == COMPONENT_ENABLED_STATE_ENABLED
21654              || newState == COMPONENT_ENABLED_STATE_DISABLED
21655              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21656              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21657            throw new IllegalArgumentException("Invalid new component state: "
21658                    + newState);
21659        }
21660        PackageSetting pkgSetting;
21661        final int callingUid = Binder.getCallingUid();
21662        final int permission;
21663        if (callingUid == Process.SYSTEM_UID) {
21664            permission = PackageManager.PERMISSION_GRANTED;
21665        } else {
21666            permission = mContext.checkCallingOrSelfPermission(
21667                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21668        }
21669        enforceCrossUserPermission(callingUid, userId,
21670                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21671        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21672        boolean sendNow = false;
21673        boolean isApp = (className == null);
21674        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21675        String componentName = isApp ? packageName : className;
21676        int packageUid = -1;
21677        ArrayList<String> components;
21678
21679        // reader
21680        synchronized (mPackages) {
21681            pkgSetting = mSettings.mPackages.get(packageName);
21682            if (pkgSetting == null) {
21683                if (!isCallerInstantApp) {
21684                    if (className == null) {
21685                        throw new IllegalArgumentException("Unknown package: " + packageName);
21686                    }
21687                    throw new IllegalArgumentException(
21688                            "Unknown component: " + packageName + "/" + className);
21689                } else {
21690                    // throw SecurityException to prevent leaking package information
21691                    throw new SecurityException(
21692                            "Attempt to change component state; "
21693                            + "pid=" + Binder.getCallingPid()
21694                            + ", uid=" + callingUid
21695                            + (className == null
21696                                    ? ", package=" + packageName
21697                                    : ", component=" + packageName + "/" + className));
21698                }
21699            }
21700        }
21701
21702        // Limit who can change which apps
21703        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21704            // Don't allow apps that don't have permission to modify other apps
21705            if (!allowedByPermission
21706                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21707                throw new SecurityException(
21708                        "Attempt to change component state; "
21709                        + "pid=" + Binder.getCallingPid()
21710                        + ", uid=" + callingUid
21711                        + (className == null
21712                                ? ", package=" + packageName
21713                                : ", component=" + packageName + "/" + className));
21714            }
21715            // Don't allow changing protected packages.
21716            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21717                throw new SecurityException("Cannot disable a protected package: " + packageName);
21718            }
21719        }
21720
21721        synchronized (mPackages) {
21722            if (callingUid == Process.SHELL_UID
21723                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21724                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21725                // unless it is a test package.
21726                int oldState = pkgSetting.getEnabled(userId);
21727                if (className == null
21728                    &&
21729                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21730                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21731                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21732                    &&
21733                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21734                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21735                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21736                    // ok
21737                } else {
21738                    throw new SecurityException(
21739                            "Shell cannot change component state for " + packageName + "/"
21740                            + className + " to " + newState);
21741                }
21742            }
21743            if (className == null) {
21744                // We're dealing with an application/package level state change
21745                if (pkgSetting.getEnabled(userId) == newState) {
21746                    // Nothing to do
21747                    return;
21748                }
21749                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21750                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21751                    // Don't care about who enables an app.
21752                    callingPackage = null;
21753                }
21754                pkgSetting.setEnabled(newState, userId, callingPackage);
21755                // pkgSetting.pkg.mSetEnabled = newState;
21756            } else {
21757                // We're dealing with a component level state change
21758                // First, verify that this is a valid class name.
21759                PackageParser.Package pkg = pkgSetting.pkg;
21760                if (pkg == null || !pkg.hasComponentClassName(className)) {
21761                    if (pkg != null &&
21762                            pkg.applicationInfo.targetSdkVersion >=
21763                                    Build.VERSION_CODES.JELLY_BEAN) {
21764                        throw new IllegalArgumentException("Component class " + className
21765                                + " does not exist in " + packageName);
21766                    } else {
21767                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21768                                + className + " does not exist in " + packageName);
21769                    }
21770                }
21771                switch (newState) {
21772                case COMPONENT_ENABLED_STATE_ENABLED:
21773                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21774                        return;
21775                    }
21776                    break;
21777                case COMPONENT_ENABLED_STATE_DISABLED:
21778                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21779                        return;
21780                    }
21781                    break;
21782                case COMPONENT_ENABLED_STATE_DEFAULT:
21783                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21784                        return;
21785                    }
21786                    break;
21787                default:
21788                    Slog.e(TAG, "Invalid new component state: " + newState);
21789                    return;
21790                }
21791            }
21792            scheduleWritePackageRestrictionsLocked(userId);
21793            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21794            final long callingId = Binder.clearCallingIdentity();
21795            try {
21796                updateInstantAppInstallerLocked(packageName);
21797            } finally {
21798                Binder.restoreCallingIdentity(callingId);
21799            }
21800            components = mPendingBroadcasts.get(userId, packageName);
21801            final boolean newPackage = components == null;
21802            if (newPackage) {
21803                components = new ArrayList<String>();
21804            }
21805            if (!components.contains(componentName)) {
21806                components.add(componentName);
21807            }
21808            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21809                sendNow = true;
21810                // Purge entry from pending broadcast list if another one exists already
21811                // since we are sending one right away.
21812                mPendingBroadcasts.remove(userId, packageName);
21813            } else {
21814                if (newPackage) {
21815                    mPendingBroadcasts.put(userId, packageName, components);
21816                }
21817                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21818                    // Schedule a message
21819                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21820                }
21821            }
21822        }
21823
21824        long callingId = Binder.clearCallingIdentity();
21825        try {
21826            if (sendNow) {
21827                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21828                sendPackageChangedBroadcast(packageName,
21829                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21830            }
21831        } finally {
21832            Binder.restoreCallingIdentity(callingId);
21833        }
21834    }
21835
21836    @Override
21837    public void flushPackageRestrictionsAsUser(int userId) {
21838        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21839            return;
21840        }
21841        if (!sUserManager.exists(userId)) {
21842            return;
21843        }
21844        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21845                false /* checkShell */, "flushPackageRestrictions");
21846        synchronized (mPackages) {
21847            mSettings.writePackageRestrictionsLPr(userId);
21848            mDirtyUsers.remove(userId);
21849            if (mDirtyUsers.isEmpty()) {
21850                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21851            }
21852        }
21853    }
21854
21855    private void sendPackageChangedBroadcast(String packageName,
21856            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21857        if (DEBUG_INSTALL)
21858            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21859                    + componentNames);
21860        Bundle extras = new Bundle(4);
21861        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21862        String nameList[] = new String[componentNames.size()];
21863        componentNames.toArray(nameList);
21864        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21865        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21866        extras.putInt(Intent.EXTRA_UID, packageUid);
21867        // If this is not reporting a change of the overall package, then only send it
21868        // to registered receivers.  We don't want to launch a swath of apps for every
21869        // little component state change.
21870        final int flags = !componentNames.contains(packageName)
21871                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21872        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21873                new int[] {UserHandle.getUserId(packageUid)});
21874    }
21875
21876    @Override
21877    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21878        if (!sUserManager.exists(userId)) return;
21879        final int callingUid = Binder.getCallingUid();
21880        if (getInstantAppPackageName(callingUid) != null) {
21881            return;
21882        }
21883        final int permission = mContext.checkCallingOrSelfPermission(
21884                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21885        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21886        enforceCrossUserPermission(callingUid, userId,
21887                true /* requireFullPermission */, true /* checkShell */, "stop package");
21888        // writer
21889        synchronized (mPackages) {
21890            final PackageSetting ps = mSettings.mPackages.get(packageName);
21891            if (!filterAppAccessLPr(ps, callingUid, userId)
21892                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21893                            allowedByPermission, callingUid, userId)) {
21894                scheduleWritePackageRestrictionsLocked(userId);
21895            }
21896        }
21897    }
21898
21899    @Override
21900    public String getInstallerPackageName(String packageName) {
21901        final int callingUid = Binder.getCallingUid();
21902        if (getInstantAppPackageName(callingUid) != null) {
21903            return null;
21904        }
21905        // reader
21906        synchronized (mPackages) {
21907            final PackageSetting ps = mSettings.mPackages.get(packageName);
21908            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21909                return null;
21910            }
21911            return mSettings.getInstallerPackageNameLPr(packageName);
21912        }
21913    }
21914
21915    public boolean isOrphaned(String packageName) {
21916        // reader
21917        synchronized (mPackages) {
21918            return mSettings.isOrphaned(packageName);
21919        }
21920    }
21921
21922    @Override
21923    public int getApplicationEnabledSetting(String packageName, int userId) {
21924        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21925        int callingUid = Binder.getCallingUid();
21926        enforceCrossUserPermission(callingUid, userId,
21927                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21928        // reader
21929        synchronized (mPackages) {
21930            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21931                return COMPONENT_ENABLED_STATE_DISABLED;
21932            }
21933            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21934        }
21935    }
21936
21937    @Override
21938    public int getComponentEnabledSetting(ComponentName component, int userId) {
21939        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21940        int callingUid = Binder.getCallingUid();
21941        enforceCrossUserPermission(callingUid, userId,
21942                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21943        synchronized (mPackages) {
21944            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21945                    component, TYPE_UNKNOWN, userId)) {
21946                return COMPONENT_ENABLED_STATE_DISABLED;
21947            }
21948            return mSettings.getComponentEnabledSettingLPr(component, userId);
21949        }
21950    }
21951
21952    @Override
21953    public void enterSafeMode() {
21954        enforceSystemOrRoot("Only the system can request entering safe mode");
21955
21956        if (!mSystemReady) {
21957            mSafeMode = true;
21958        }
21959    }
21960
21961    @Override
21962    public void systemReady() {
21963        enforceSystemOrRoot("Only the system can claim the system is ready");
21964
21965        mSystemReady = true;
21966        final ContentResolver resolver = mContext.getContentResolver();
21967        ContentObserver co = new ContentObserver(mHandler) {
21968            @Override
21969            public void onChange(boolean selfChange) {
21970                mEphemeralAppsDisabled =
21971                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21972                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21973            }
21974        };
21975        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21976                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21977                false, co, UserHandle.USER_SYSTEM);
21978        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21979                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21980        co.onChange(true);
21981
21982        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21983        // disabled after already being started.
21984        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21985                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21986
21987        // Read the compatibilty setting when the system is ready.
21988        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21989                mContext.getContentResolver(),
21990                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21991        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21992        if (DEBUG_SETTINGS) {
21993            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21994        }
21995
21996        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21997
21998        synchronized (mPackages) {
21999            // Verify that all of the preferred activity components actually
22000            // exist.  It is possible for applications to be updated and at
22001            // that point remove a previously declared activity component that
22002            // had been set as a preferred activity.  We try to clean this up
22003            // the next time we encounter that preferred activity, but it is
22004            // possible for the user flow to never be able to return to that
22005            // situation so here we do a sanity check to make sure we haven't
22006            // left any junk around.
22007            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
22008            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22009                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22010                removed.clear();
22011                for (PreferredActivity pa : pir.filterSet()) {
22012                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
22013                        removed.add(pa);
22014                    }
22015                }
22016                if (removed.size() > 0) {
22017                    for (int r=0; r<removed.size(); r++) {
22018                        PreferredActivity pa = removed.get(r);
22019                        Slog.w(TAG, "Removing dangling preferred activity: "
22020                                + pa.mPref.mComponent);
22021                        pir.removeFilter(pa);
22022                    }
22023                    mSettings.writePackageRestrictionsLPr(
22024                            mSettings.mPreferredActivities.keyAt(i));
22025                }
22026            }
22027
22028            for (int userId : UserManagerService.getInstance().getUserIds()) {
22029                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
22030                    grantPermissionsUserIds = ArrayUtils.appendInt(
22031                            grantPermissionsUserIds, userId);
22032                }
22033            }
22034        }
22035        sUserManager.systemReady();
22036
22037        // If we upgraded grant all default permissions before kicking off.
22038        for (int userId : grantPermissionsUserIds) {
22039            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22040        }
22041
22042        // If we did not grant default permissions, we preload from this the
22043        // default permission exceptions lazily to ensure we don't hit the
22044        // disk on a new user creation.
22045        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22046            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22047        }
22048
22049        // Kick off any messages waiting for system ready
22050        if (mPostSystemReadyMessages != null) {
22051            for (Message msg : mPostSystemReadyMessages) {
22052                msg.sendToTarget();
22053            }
22054            mPostSystemReadyMessages = null;
22055        }
22056
22057        // Watch for external volumes that come and go over time
22058        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22059        storage.registerListener(mStorageListener);
22060
22061        mInstallerService.systemReady();
22062        mPackageDexOptimizer.systemReady();
22063
22064        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22065                StorageManagerInternal.class);
22066        StorageManagerInternal.addExternalStoragePolicy(
22067                new StorageManagerInternal.ExternalStorageMountPolicy() {
22068            @Override
22069            public int getMountMode(int uid, String packageName) {
22070                if (Process.isIsolated(uid)) {
22071                    return Zygote.MOUNT_EXTERNAL_NONE;
22072                }
22073                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22074                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22075                }
22076                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22077                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22078                }
22079                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22080                    return Zygote.MOUNT_EXTERNAL_READ;
22081                }
22082                return Zygote.MOUNT_EXTERNAL_WRITE;
22083            }
22084
22085            @Override
22086            public boolean hasExternalStorage(int uid, String packageName) {
22087                return true;
22088            }
22089        });
22090
22091        // Now that we're mostly running, clean up stale users and apps
22092        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22093        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22094
22095        if (mPrivappPermissionsViolations != null) {
22096            Slog.wtf(TAG,"Signature|privileged permissions not in "
22097                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22098            mPrivappPermissionsViolations = null;
22099        }
22100    }
22101
22102    public void waitForAppDataPrepared() {
22103        if (mPrepareAppDataFuture == null) {
22104            return;
22105        }
22106        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22107        mPrepareAppDataFuture = null;
22108    }
22109
22110    @Override
22111    public boolean isSafeMode() {
22112        // allow instant applications
22113        return mSafeMode;
22114    }
22115
22116    @Override
22117    public boolean hasSystemUidErrors() {
22118        // allow instant applications
22119        return mHasSystemUidErrors;
22120    }
22121
22122    static String arrayToString(int[] array) {
22123        StringBuffer buf = new StringBuffer(128);
22124        buf.append('[');
22125        if (array != null) {
22126            for (int i=0; i<array.length; i++) {
22127                if (i > 0) buf.append(", ");
22128                buf.append(array[i]);
22129            }
22130        }
22131        buf.append(']');
22132        return buf.toString();
22133    }
22134
22135    static class DumpState {
22136        public static final int DUMP_LIBS = 1 << 0;
22137        public static final int DUMP_FEATURES = 1 << 1;
22138        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22139        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22140        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22141        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22142        public static final int DUMP_PERMISSIONS = 1 << 6;
22143        public static final int DUMP_PACKAGES = 1 << 7;
22144        public static final int DUMP_SHARED_USERS = 1 << 8;
22145        public static final int DUMP_MESSAGES = 1 << 9;
22146        public static final int DUMP_PROVIDERS = 1 << 10;
22147        public static final int DUMP_VERIFIERS = 1 << 11;
22148        public static final int DUMP_PREFERRED = 1 << 12;
22149        public static final int DUMP_PREFERRED_XML = 1 << 13;
22150        public static final int DUMP_KEYSETS = 1 << 14;
22151        public static final int DUMP_VERSION = 1 << 15;
22152        public static final int DUMP_INSTALLS = 1 << 16;
22153        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22154        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22155        public static final int DUMP_FROZEN = 1 << 19;
22156        public static final int DUMP_DEXOPT = 1 << 20;
22157        public static final int DUMP_COMPILER_STATS = 1 << 21;
22158        public static final int DUMP_CHANGES = 1 << 22;
22159        public static final int DUMP_VOLUMES = 1 << 23;
22160
22161        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22162
22163        private int mTypes;
22164
22165        private int mOptions;
22166
22167        private boolean mTitlePrinted;
22168
22169        private SharedUserSetting mSharedUser;
22170
22171        public boolean isDumping(int type) {
22172            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22173                return true;
22174            }
22175
22176            return (mTypes & type) != 0;
22177        }
22178
22179        public void setDump(int type) {
22180            mTypes |= type;
22181        }
22182
22183        public boolean isOptionEnabled(int option) {
22184            return (mOptions & option) != 0;
22185        }
22186
22187        public void setOptionEnabled(int option) {
22188            mOptions |= option;
22189        }
22190
22191        public boolean onTitlePrinted() {
22192            final boolean printed = mTitlePrinted;
22193            mTitlePrinted = true;
22194            return printed;
22195        }
22196
22197        public boolean getTitlePrinted() {
22198            return mTitlePrinted;
22199        }
22200
22201        public void setTitlePrinted(boolean enabled) {
22202            mTitlePrinted = enabled;
22203        }
22204
22205        public SharedUserSetting getSharedUser() {
22206            return mSharedUser;
22207        }
22208
22209        public void setSharedUser(SharedUserSetting user) {
22210            mSharedUser = user;
22211        }
22212    }
22213
22214    @Override
22215    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22216            FileDescriptor err, String[] args, ShellCallback callback,
22217            ResultReceiver resultReceiver) {
22218        (new PackageManagerShellCommand(this)).exec(
22219                this, in, out, err, args, callback, resultReceiver);
22220    }
22221
22222    @Override
22223    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22224        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22225
22226        DumpState dumpState = new DumpState();
22227        boolean fullPreferred = false;
22228        boolean checkin = false;
22229
22230        String packageName = null;
22231        ArraySet<String> permissionNames = null;
22232
22233        int opti = 0;
22234        while (opti < args.length) {
22235            String opt = args[opti];
22236            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22237                break;
22238            }
22239            opti++;
22240
22241            if ("-a".equals(opt)) {
22242                // Right now we only know how to print all.
22243            } else if ("-h".equals(opt)) {
22244                pw.println("Package manager dump options:");
22245                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22246                pw.println("    --checkin: dump for a checkin");
22247                pw.println("    -f: print details of intent filters");
22248                pw.println("    -h: print this help");
22249                pw.println("  cmd may be one of:");
22250                pw.println("    l[ibraries]: list known shared libraries");
22251                pw.println("    f[eatures]: list device features");
22252                pw.println("    k[eysets]: print known keysets");
22253                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22254                pw.println("    perm[issions]: dump permissions");
22255                pw.println("    permission [name ...]: dump declaration and use of given permission");
22256                pw.println("    pref[erred]: print preferred package settings");
22257                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22258                pw.println("    prov[iders]: dump content providers");
22259                pw.println("    p[ackages]: dump installed packages");
22260                pw.println("    s[hared-users]: dump shared user IDs");
22261                pw.println("    m[essages]: print collected runtime messages");
22262                pw.println("    v[erifiers]: print package verifier info");
22263                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22264                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22265                pw.println("    version: print database version info");
22266                pw.println("    write: write current settings now");
22267                pw.println("    installs: details about install sessions");
22268                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22269                pw.println("    dexopt: dump dexopt state");
22270                pw.println("    compiler-stats: dump compiler statistics");
22271                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22272                pw.println("    <package.name>: info about given package");
22273                return;
22274            } else if ("--checkin".equals(opt)) {
22275                checkin = true;
22276            } else if ("-f".equals(opt)) {
22277                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22278            } else if ("--proto".equals(opt)) {
22279                dumpProto(fd);
22280                return;
22281            } else {
22282                pw.println("Unknown argument: " + opt + "; use -h for help");
22283            }
22284        }
22285
22286        // Is the caller requesting to dump a particular piece of data?
22287        if (opti < args.length) {
22288            String cmd = args[opti];
22289            opti++;
22290            // Is this a package name?
22291            if ("android".equals(cmd) || cmd.contains(".")) {
22292                packageName = cmd;
22293                // When dumping a single package, we always dump all of its
22294                // filter information since the amount of data will be reasonable.
22295                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22296            } else if ("check-permission".equals(cmd)) {
22297                if (opti >= args.length) {
22298                    pw.println("Error: check-permission missing permission argument");
22299                    return;
22300                }
22301                String perm = args[opti];
22302                opti++;
22303                if (opti >= args.length) {
22304                    pw.println("Error: check-permission missing package argument");
22305                    return;
22306                }
22307
22308                String pkg = args[opti];
22309                opti++;
22310                int user = UserHandle.getUserId(Binder.getCallingUid());
22311                if (opti < args.length) {
22312                    try {
22313                        user = Integer.parseInt(args[opti]);
22314                    } catch (NumberFormatException e) {
22315                        pw.println("Error: check-permission user argument is not a number: "
22316                                + args[opti]);
22317                        return;
22318                    }
22319                }
22320
22321                // Normalize package name to handle renamed packages and static libs
22322                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22323
22324                pw.println(checkPermission(perm, pkg, user));
22325                return;
22326            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22327                dumpState.setDump(DumpState.DUMP_LIBS);
22328            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22329                dumpState.setDump(DumpState.DUMP_FEATURES);
22330            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22331                if (opti >= args.length) {
22332                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22333                            | DumpState.DUMP_SERVICE_RESOLVERS
22334                            | DumpState.DUMP_RECEIVER_RESOLVERS
22335                            | DumpState.DUMP_CONTENT_RESOLVERS);
22336                } else {
22337                    while (opti < args.length) {
22338                        String name = args[opti];
22339                        if ("a".equals(name) || "activity".equals(name)) {
22340                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22341                        } else if ("s".equals(name) || "service".equals(name)) {
22342                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22343                        } else if ("r".equals(name) || "receiver".equals(name)) {
22344                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22345                        } else if ("c".equals(name) || "content".equals(name)) {
22346                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22347                        } else {
22348                            pw.println("Error: unknown resolver table type: " + name);
22349                            return;
22350                        }
22351                        opti++;
22352                    }
22353                }
22354            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22355                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22356            } else if ("permission".equals(cmd)) {
22357                if (opti >= args.length) {
22358                    pw.println("Error: permission requires permission name");
22359                    return;
22360                }
22361                permissionNames = new ArraySet<>();
22362                while (opti < args.length) {
22363                    permissionNames.add(args[opti]);
22364                    opti++;
22365                }
22366                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22367                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22368            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22369                dumpState.setDump(DumpState.DUMP_PREFERRED);
22370            } else if ("preferred-xml".equals(cmd)) {
22371                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22372                if (opti < args.length && "--full".equals(args[opti])) {
22373                    fullPreferred = true;
22374                    opti++;
22375                }
22376            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22377                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22378            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22379                dumpState.setDump(DumpState.DUMP_PACKAGES);
22380            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22381                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22382            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22383                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22384            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22385                dumpState.setDump(DumpState.DUMP_MESSAGES);
22386            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22387                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22388            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22389                    || "intent-filter-verifiers".equals(cmd)) {
22390                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22391            } else if ("version".equals(cmd)) {
22392                dumpState.setDump(DumpState.DUMP_VERSION);
22393            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22394                dumpState.setDump(DumpState.DUMP_KEYSETS);
22395            } else if ("installs".equals(cmd)) {
22396                dumpState.setDump(DumpState.DUMP_INSTALLS);
22397            } else if ("frozen".equals(cmd)) {
22398                dumpState.setDump(DumpState.DUMP_FROZEN);
22399            } else if ("volumes".equals(cmd)) {
22400                dumpState.setDump(DumpState.DUMP_VOLUMES);
22401            } else if ("dexopt".equals(cmd)) {
22402                dumpState.setDump(DumpState.DUMP_DEXOPT);
22403            } else if ("compiler-stats".equals(cmd)) {
22404                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22405            } else if ("changes".equals(cmd)) {
22406                dumpState.setDump(DumpState.DUMP_CHANGES);
22407            } else if ("write".equals(cmd)) {
22408                synchronized (mPackages) {
22409                    mSettings.writeLPr();
22410                    pw.println("Settings written.");
22411                    return;
22412                }
22413            }
22414        }
22415
22416        if (checkin) {
22417            pw.println("vers,1");
22418        }
22419
22420        // reader
22421        synchronized (mPackages) {
22422            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22423                if (!checkin) {
22424                    if (dumpState.onTitlePrinted())
22425                        pw.println();
22426                    pw.println("Database versions:");
22427                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22428                }
22429            }
22430
22431            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22432                if (!checkin) {
22433                    if (dumpState.onTitlePrinted())
22434                        pw.println();
22435                    pw.println("Verifiers:");
22436                    pw.print("  Required: ");
22437                    pw.print(mRequiredVerifierPackage);
22438                    pw.print(" (uid=");
22439                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22440                            UserHandle.USER_SYSTEM));
22441                    pw.println(")");
22442                } else if (mRequiredVerifierPackage != null) {
22443                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22444                    pw.print(",");
22445                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22446                            UserHandle.USER_SYSTEM));
22447                }
22448            }
22449
22450            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22451                    packageName == null) {
22452                if (mIntentFilterVerifierComponent != null) {
22453                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22454                    if (!checkin) {
22455                        if (dumpState.onTitlePrinted())
22456                            pw.println();
22457                        pw.println("Intent Filter Verifier:");
22458                        pw.print("  Using: ");
22459                        pw.print(verifierPackageName);
22460                        pw.print(" (uid=");
22461                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22462                                UserHandle.USER_SYSTEM));
22463                        pw.println(")");
22464                    } else if (verifierPackageName != null) {
22465                        pw.print("ifv,"); pw.print(verifierPackageName);
22466                        pw.print(",");
22467                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22468                                UserHandle.USER_SYSTEM));
22469                    }
22470                } else {
22471                    pw.println();
22472                    pw.println("No Intent Filter Verifier available!");
22473                }
22474            }
22475
22476            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22477                boolean printedHeader = false;
22478                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22479                while (it.hasNext()) {
22480                    String libName = it.next();
22481                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22482                    if (versionedLib == null) {
22483                        continue;
22484                    }
22485                    final int versionCount = versionedLib.size();
22486                    for (int i = 0; i < versionCount; i++) {
22487                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22488                        if (!checkin) {
22489                            if (!printedHeader) {
22490                                if (dumpState.onTitlePrinted())
22491                                    pw.println();
22492                                pw.println("Libraries:");
22493                                printedHeader = true;
22494                            }
22495                            pw.print("  ");
22496                        } else {
22497                            pw.print("lib,");
22498                        }
22499                        pw.print(libEntry.info.getName());
22500                        if (libEntry.info.isStatic()) {
22501                            pw.print(" version=" + libEntry.info.getVersion());
22502                        }
22503                        if (!checkin) {
22504                            pw.print(" -> ");
22505                        }
22506                        if (libEntry.path != null) {
22507                            pw.print(" (jar) ");
22508                            pw.print(libEntry.path);
22509                        } else {
22510                            pw.print(" (apk) ");
22511                            pw.print(libEntry.apk);
22512                        }
22513                        pw.println();
22514                    }
22515                }
22516            }
22517
22518            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22519                if (dumpState.onTitlePrinted())
22520                    pw.println();
22521                if (!checkin) {
22522                    pw.println("Features:");
22523                }
22524
22525                synchronized (mAvailableFeatures) {
22526                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22527                        if (checkin) {
22528                            pw.print("feat,");
22529                            pw.print(feat.name);
22530                            pw.print(",");
22531                            pw.println(feat.version);
22532                        } else {
22533                            pw.print("  ");
22534                            pw.print(feat.name);
22535                            if (feat.version > 0) {
22536                                pw.print(" version=");
22537                                pw.print(feat.version);
22538                            }
22539                            pw.println();
22540                        }
22541                    }
22542                }
22543            }
22544
22545            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22546                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22547                        : "Activity Resolver Table:", "  ", packageName,
22548                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22549                    dumpState.setTitlePrinted(true);
22550                }
22551            }
22552            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22553                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22554                        : "Receiver Resolver Table:", "  ", packageName,
22555                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22556                    dumpState.setTitlePrinted(true);
22557                }
22558            }
22559            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22560                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22561                        : "Service Resolver Table:", "  ", packageName,
22562                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22563                    dumpState.setTitlePrinted(true);
22564                }
22565            }
22566            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22567                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22568                        : "Provider Resolver Table:", "  ", packageName,
22569                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22570                    dumpState.setTitlePrinted(true);
22571                }
22572            }
22573
22574            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22575                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22576                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22577                    int user = mSettings.mPreferredActivities.keyAt(i);
22578                    if (pir.dump(pw,
22579                            dumpState.getTitlePrinted()
22580                                ? "\nPreferred Activities User " + user + ":"
22581                                : "Preferred Activities User " + user + ":", "  ",
22582                            packageName, true, false)) {
22583                        dumpState.setTitlePrinted(true);
22584                    }
22585                }
22586            }
22587
22588            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22589                pw.flush();
22590                FileOutputStream fout = new FileOutputStream(fd);
22591                BufferedOutputStream str = new BufferedOutputStream(fout);
22592                XmlSerializer serializer = new FastXmlSerializer();
22593                try {
22594                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22595                    serializer.startDocument(null, true);
22596                    serializer.setFeature(
22597                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22598                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22599                    serializer.endDocument();
22600                    serializer.flush();
22601                } catch (IllegalArgumentException e) {
22602                    pw.println("Failed writing: " + e);
22603                } catch (IllegalStateException e) {
22604                    pw.println("Failed writing: " + e);
22605                } catch (IOException e) {
22606                    pw.println("Failed writing: " + e);
22607                }
22608            }
22609
22610            if (!checkin
22611                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22612                    && packageName == null) {
22613                pw.println();
22614                int count = mSettings.mPackages.size();
22615                if (count == 0) {
22616                    pw.println("No applications!");
22617                    pw.println();
22618                } else {
22619                    final String prefix = "  ";
22620                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22621                    if (allPackageSettings.size() == 0) {
22622                        pw.println("No domain preferred apps!");
22623                        pw.println();
22624                    } else {
22625                        pw.println("App verification status:");
22626                        pw.println();
22627                        count = 0;
22628                        for (PackageSetting ps : allPackageSettings) {
22629                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22630                            if (ivi == null || ivi.getPackageName() == null) continue;
22631                            pw.println(prefix + "Package: " + ivi.getPackageName());
22632                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22633                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22634                            pw.println();
22635                            count++;
22636                        }
22637                        if (count == 0) {
22638                            pw.println(prefix + "No app verification established.");
22639                            pw.println();
22640                        }
22641                        for (int userId : sUserManager.getUserIds()) {
22642                            pw.println("App linkages for user " + userId + ":");
22643                            pw.println();
22644                            count = 0;
22645                            for (PackageSetting ps : allPackageSettings) {
22646                                final long status = ps.getDomainVerificationStatusForUser(userId);
22647                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22648                                        && !DEBUG_DOMAIN_VERIFICATION) {
22649                                    continue;
22650                                }
22651                                pw.println(prefix + "Package: " + ps.name);
22652                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22653                                String statusStr = IntentFilterVerificationInfo.
22654                                        getStatusStringFromValue(status);
22655                                pw.println(prefix + "Status:  " + statusStr);
22656                                pw.println();
22657                                count++;
22658                            }
22659                            if (count == 0) {
22660                                pw.println(prefix + "No configured app linkages.");
22661                                pw.println();
22662                            }
22663                        }
22664                    }
22665                }
22666            }
22667
22668            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22669                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22670                if (packageName == null && permissionNames == null) {
22671                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22672                        if (iperm == 0) {
22673                            if (dumpState.onTitlePrinted())
22674                                pw.println();
22675                            pw.println("AppOp Permissions:");
22676                        }
22677                        pw.print("  AppOp Permission ");
22678                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22679                        pw.println(":");
22680                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22681                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22682                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22683                        }
22684                    }
22685                }
22686            }
22687
22688            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22689                boolean printedSomething = false;
22690                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22691                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22692                        continue;
22693                    }
22694                    if (!printedSomething) {
22695                        if (dumpState.onTitlePrinted())
22696                            pw.println();
22697                        pw.println("Registered ContentProviders:");
22698                        printedSomething = true;
22699                    }
22700                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22701                    pw.print("    "); pw.println(p.toString());
22702                }
22703                printedSomething = false;
22704                for (Map.Entry<String, PackageParser.Provider> entry :
22705                        mProvidersByAuthority.entrySet()) {
22706                    PackageParser.Provider p = entry.getValue();
22707                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22708                        continue;
22709                    }
22710                    if (!printedSomething) {
22711                        if (dumpState.onTitlePrinted())
22712                            pw.println();
22713                        pw.println("ContentProvider Authorities:");
22714                        printedSomething = true;
22715                    }
22716                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22717                    pw.print("    "); pw.println(p.toString());
22718                    if (p.info != null && p.info.applicationInfo != null) {
22719                        final String appInfo = p.info.applicationInfo.toString();
22720                        pw.print("      applicationInfo="); pw.println(appInfo);
22721                    }
22722                }
22723            }
22724
22725            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22726                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22727            }
22728
22729            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22730                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22731            }
22732
22733            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22734                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22735            }
22736
22737            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22738                if (dumpState.onTitlePrinted()) pw.println();
22739                pw.println("Package Changes:");
22740                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22741                final int K = mChangedPackages.size();
22742                for (int i = 0; i < K; i++) {
22743                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22744                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22745                    final int N = changes.size();
22746                    if (N == 0) {
22747                        pw.print("    "); pw.println("No packages changed");
22748                    } else {
22749                        for (int j = 0; j < N; j++) {
22750                            final String pkgName = changes.valueAt(j);
22751                            final int sequenceNumber = changes.keyAt(j);
22752                            pw.print("    ");
22753                            pw.print("seq=");
22754                            pw.print(sequenceNumber);
22755                            pw.print(", package=");
22756                            pw.println(pkgName);
22757                        }
22758                    }
22759                }
22760            }
22761
22762            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22763                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22764            }
22765
22766            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22767                // XXX should handle packageName != null by dumping only install data that
22768                // the given package is involved with.
22769                if (dumpState.onTitlePrinted()) pw.println();
22770
22771                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22772                ipw.println();
22773                ipw.println("Frozen packages:");
22774                ipw.increaseIndent();
22775                if (mFrozenPackages.size() == 0) {
22776                    ipw.println("(none)");
22777                } else {
22778                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22779                        ipw.println(mFrozenPackages.valueAt(i));
22780                    }
22781                }
22782                ipw.decreaseIndent();
22783            }
22784
22785            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22786                if (dumpState.onTitlePrinted()) pw.println();
22787
22788                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22789                ipw.println();
22790                ipw.println("Loaded volumes:");
22791                ipw.increaseIndent();
22792                if (mLoadedVolumes.size() == 0) {
22793                    ipw.println("(none)");
22794                } else {
22795                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22796                        ipw.println(mLoadedVolumes.valueAt(i));
22797                    }
22798                }
22799                ipw.decreaseIndent();
22800            }
22801
22802            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22803                if (dumpState.onTitlePrinted()) pw.println();
22804                dumpDexoptStateLPr(pw, packageName);
22805            }
22806
22807            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22808                if (dumpState.onTitlePrinted()) pw.println();
22809                dumpCompilerStatsLPr(pw, packageName);
22810            }
22811
22812            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22813                if (dumpState.onTitlePrinted()) pw.println();
22814                mSettings.dumpReadMessagesLPr(pw, dumpState);
22815
22816                pw.println();
22817                pw.println("Package warning messages:");
22818                BufferedReader in = null;
22819                String line = null;
22820                try {
22821                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22822                    while ((line = in.readLine()) != null) {
22823                        if (line.contains("ignored: updated version")) continue;
22824                        pw.println(line);
22825                    }
22826                } catch (IOException ignored) {
22827                } finally {
22828                    IoUtils.closeQuietly(in);
22829                }
22830            }
22831
22832            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22833                BufferedReader in = null;
22834                String line = null;
22835                try {
22836                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22837                    while ((line = in.readLine()) != null) {
22838                        if (line.contains("ignored: updated version")) continue;
22839                        pw.print("msg,");
22840                        pw.println(line);
22841                    }
22842                } catch (IOException ignored) {
22843                } finally {
22844                    IoUtils.closeQuietly(in);
22845                }
22846            }
22847        }
22848
22849        // PackageInstaller should be called outside of mPackages lock
22850        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22851            // XXX should handle packageName != null by dumping only install data that
22852            // the given package is involved with.
22853            if (dumpState.onTitlePrinted()) pw.println();
22854            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22855        }
22856    }
22857
22858    private void dumpProto(FileDescriptor fd) {
22859        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22860
22861        synchronized (mPackages) {
22862            final long requiredVerifierPackageToken =
22863                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22864            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22865            proto.write(
22866                    PackageServiceDumpProto.PackageShortProto.UID,
22867                    getPackageUid(
22868                            mRequiredVerifierPackage,
22869                            MATCH_DEBUG_TRIAGED_MISSING,
22870                            UserHandle.USER_SYSTEM));
22871            proto.end(requiredVerifierPackageToken);
22872
22873            if (mIntentFilterVerifierComponent != null) {
22874                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22875                final long verifierPackageToken =
22876                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22877                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22878                proto.write(
22879                        PackageServiceDumpProto.PackageShortProto.UID,
22880                        getPackageUid(
22881                                verifierPackageName,
22882                                MATCH_DEBUG_TRIAGED_MISSING,
22883                                UserHandle.USER_SYSTEM));
22884                proto.end(verifierPackageToken);
22885            }
22886
22887            dumpSharedLibrariesProto(proto);
22888            dumpFeaturesProto(proto);
22889            mSettings.dumpPackagesProto(proto);
22890            mSettings.dumpSharedUsersProto(proto);
22891            dumpMessagesProto(proto);
22892        }
22893        proto.flush();
22894    }
22895
22896    private void dumpMessagesProto(ProtoOutputStream proto) {
22897        BufferedReader in = null;
22898        String line = null;
22899        try {
22900            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22901            while ((line = in.readLine()) != null) {
22902                if (line.contains("ignored: updated version")) continue;
22903                proto.write(PackageServiceDumpProto.MESSAGES, line);
22904            }
22905        } catch (IOException ignored) {
22906        } finally {
22907            IoUtils.closeQuietly(in);
22908        }
22909    }
22910
22911    private void dumpFeaturesProto(ProtoOutputStream proto) {
22912        synchronized (mAvailableFeatures) {
22913            final int count = mAvailableFeatures.size();
22914            for (int i = 0; i < count; i++) {
22915                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22916                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22917                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22918                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22919                proto.end(featureToken);
22920            }
22921        }
22922    }
22923
22924    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22925        final int count = mSharedLibraries.size();
22926        for (int i = 0; i < count; i++) {
22927            final String libName = mSharedLibraries.keyAt(i);
22928            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22929            if (versionedLib == null) {
22930                continue;
22931            }
22932            final int versionCount = versionedLib.size();
22933            for (int j = 0; j < versionCount; j++) {
22934                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22935                final long sharedLibraryToken =
22936                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22937                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22938                final boolean isJar = (libEntry.path != null);
22939                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22940                if (isJar) {
22941                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22942                } else {
22943                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22944                }
22945                proto.end(sharedLibraryToken);
22946            }
22947        }
22948    }
22949
22950    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22951        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22952        ipw.println();
22953        ipw.println("Dexopt state:");
22954        ipw.increaseIndent();
22955        Collection<PackageParser.Package> packages = null;
22956        if (packageName != null) {
22957            PackageParser.Package targetPackage = mPackages.get(packageName);
22958            if (targetPackage != null) {
22959                packages = Collections.singletonList(targetPackage);
22960            } else {
22961                ipw.println("Unable to find package: " + packageName);
22962                return;
22963            }
22964        } else {
22965            packages = mPackages.values();
22966        }
22967
22968        for (PackageParser.Package pkg : packages) {
22969            ipw.println("[" + pkg.packageName + "]");
22970            ipw.increaseIndent();
22971            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
22972                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
22973            ipw.decreaseIndent();
22974        }
22975    }
22976
22977    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22978        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22979        ipw.println();
22980        ipw.println("Compiler stats:");
22981        ipw.increaseIndent();
22982        Collection<PackageParser.Package> packages = null;
22983        if (packageName != null) {
22984            PackageParser.Package targetPackage = mPackages.get(packageName);
22985            if (targetPackage != null) {
22986                packages = Collections.singletonList(targetPackage);
22987            } else {
22988                ipw.println("Unable to find package: " + packageName);
22989                return;
22990            }
22991        } else {
22992            packages = mPackages.values();
22993        }
22994
22995        for (PackageParser.Package pkg : packages) {
22996            ipw.println("[" + pkg.packageName + "]");
22997            ipw.increaseIndent();
22998
22999            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
23000            if (stats == null) {
23001                ipw.println("(No recorded stats)");
23002            } else {
23003                stats.dump(ipw);
23004            }
23005            ipw.decreaseIndent();
23006        }
23007    }
23008
23009    private String dumpDomainString(String packageName) {
23010        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
23011                .getList();
23012        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
23013
23014        ArraySet<String> result = new ArraySet<>();
23015        if (iviList.size() > 0) {
23016            for (IntentFilterVerificationInfo ivi : iviList) {
23017                for (String host : ivi.getDomains()) {
23018                    result.add(host);
23019                }
23020            }
23021        }
23022        if (filters != null && filters.size() > 0) {
23023            for (IntentFilter filter : filters) {
23024                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
23025                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
23026                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
23027                    result.addAll(filter.getHostsList());
23028                }
23029            }
23030        }
23031
23032        StringBuilder sb = new StringBuilder(result.size() * 16);
23033        for (String domain : result) {
23034            if (sb.length() > 0) sb.append(" ");
23035            sb.append(domain);
23036        }
23037        return sb.toString();
23038    }
23039
23040    // ------- apps on sdcard specific code -------
23041    static final boolean DEBUG_SD_INSTALL = false;
23042
23043    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23044
23045    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23046
23047    private boolean mMediaMounted = false;
23048
23049    static String getEncryptKey() {
23050        try {
23051            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23052                    SD_ENCRYPTION_KEYSTORE_NAME);
23053            if (sdEncKey == null) {
23054                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23055                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23056                if (sdEncKey == null) {
23057                    Slog.e(TAG, "Failed to create encryption keys");
23058                    return null;
23059                }
23060            }
23061            return sdEncKey;
23062        } catch (NoSuchAlgorithmException nsae) {
23063            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23064            return null;
23065        } catch (IOException ioe) {
23066            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23067            return null;
23068        }
23069    }
23070
23071    /*
23072     * Update media status on PackageManager.
23073     */
23074    @Override
23075    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23076        enforceSystemOrRoot("Media status can only be updated by the system");
23077        // reader; this apparently protects mMediaMounted, but should probably
23078        // be a different lock in that case.
23079        synchronized (mPackages) {
23080            Log.i(TAG, "Updating external media status from "
23081                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
23082                    + (mediaStatus ? "mounted" : "unmounted"));
23083            if (DEBUG_SD_INSTALL)
23084                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23085                        + ", mMediaMounted=" + mMediaMounted);
23086            if (mediaStatus == mMediaMounted) {
23087                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23088                        : 0, -1);
23089                mHandler.sendMessage(msg);
23090                return;
23091            }
23092            mMediaMounted = mediaStatus;
23093        }
23094        // Queue up an async operation since the package installation may take a
23095        // little while.
23096        mHandler.post(new Runnable() {
23097            public void run() {
23098                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23099            }
23100        });
23101    }
23102
23103    /**
23104     * Called by StorageManagerService when the initial ASECs to scan are available.
23105     * Should block until all the ASEC containers are finished being scanned.
23106     */
23107    public void scanAvailableAsecs() {
23108        updateExternalMediaStatusInner(true, false, false);
23109    }
23110
23111    /*
23112     * Collect information of applications on external media, map them against
23113     * existing containers and update information based on current mount status.
23114     * Please note that we always have to report status if reportStatus has been
23115     * set to true especially when unloading packages.
23116     */
23117    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23118            boolean externalStorage) {
23119        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23120        int[] uidArr = EmptyArray.INT;
23121
23122        final String[] list = PackageHelper.getSecureContainerList();
23123        if (ArrayUtils.isEmpty(list)) {
23124            Log.i(TAG, "No secure containers found");
23125        } else {
23126            // Process list of secure containers and categorize them
23127            // as active or stale based on their package internal state.
23128
23129            // reader
23130            synchronized (mPackages) {
23131                for (String cid : list) {
23132                    // Leave stages untouched for now; installer service owns them
23133                    if (PackageInstallerService.isStageName(cid)) continue;
23134
23135                    if (DEBUG_SD_INSTALL)
23136                        Log.i(TAG, "Processing container " + cid);
23137                    String pkgName = getAsecPackageName(cid);
23138                    if (pkgName == null) {
23139                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23140                        continue;
23141                    }
23142                    if (DEBUG_SD_INSTALL)
23143                        Log.i(TAG, "Looking for pkg : " + pkgName);
23144
23145                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23146                    if (ps == null) {
23147                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23148                        continue;
23149                    }
23150
23151                    /*
23152                     * Skip packages that are not external if we're unmounting
23153                     * external storage.
23154                     */
23155                    if (externalStorage && !isMounted && !isExternal(ps)) {
23156                        continue;
23157                    }
23158
23159                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23160                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23161                    // The package status is changed only if the code path
23162                    // matches between settings and the container id.
23163                    if (ps.codePathString != null
23164                            && ps.codePathString.startsWith(args.getCodePath())) {
23165                        if (DEBUG_SD_INSTALL) {
23166                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23167                                    + " at code path: " + ps.codePathString);
23168                        }
23169
23170                        // We do have a valid package installed on sdcard
23171                        processCids.put(args, ps.codePathString);
23172                        final int uid = ps.appId;
23173                        if (uid != -1) {
23174                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23175                        }
23176                    } else {
23177                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23178                                + ps.codePathString);
23179                    }
23180                }
23181            }
23182
23183            Arrays.sort(uidArr);
23184        }
23185
23186        // Process packages with valid entries.
23187        if (isMounted) {
23188            if (DEBUG_SD_INSTALL)
23189                Log.i(TAG, "Loading packages");
23190            loadMediaPackages(processCids, uidArr, externalStorage);
23191            startCleaningPackages();
23192            mInstallerService.onSecureContainersAvailable();
23193        } else {
23194            if (DEBUG_SD_INSTALL)
23195                Log.i(TAG, "Unloading packages");
23196            unloadMediaPackages(processCids, uidArr, reportStatus);
23197        }
23198    }
23199
23200    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23201            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23202        final int size = infos.size();
23203        final String[] packageNames = new String[size];
23204        final int[] packageUids = new int[size];
23205        for (int i = 0; i < size; i++) {
23206            final ApplicationInfo info = infos.get(i);
23207            packageNames[i] = info.packageName;
23208            packageUids[i] = info.uid;
23209        }
23210        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23211                finishedReceiver);
23212    }
23213
23214    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23215            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23216        sendResourcesChangedBroadcast(mediaStatus, replacing,
23217                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23218    }
23219
23220    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23221            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23222        int size = pkgList.length;
23223        if (size > 0) {
23224            // Send broadcasts here
23225            Bundle extras = new Bundle();
23226            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23227            if (uidArr != null) {
23228                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23229            }
23230            if (replacing) {
23231                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23232            }
23233            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23234                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23235            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23236        }
23237    }
23238
23239   /*
23240     * Look at potentially valid container ids from processCids If package
23241     * information doesn't match the one on record or package scanning fails,
23242     * the cid is added to list of removeCids. We currently don't delete stale
23243     * containers.
23244     */
23245    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23246            boolean externalStorage) {
23247        ArrayList<String> pkgList = new ArrayList<String>();
23248        Set<AsecInstallArgs> keys = processCids.keySet();
23249
23250        for (AsecInstallArgs args : keys) {
23251            String codePath = processCids.get(args);
23252            if (DEBUG_SD_INSTALL)
23253                Log.i(TAG, "Loading container : " + args.cid);
23254            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23255            try {
23256                // Make sure there are no container errors first.
23257                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23258                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23259                            + " when installing from sdcard");
23260                    continue;
23261                }
23262                // Check code path here.
23263                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23264                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23265                            + " does not match one in settings " + codePath);
23266                    continue;
23267                }
23268                // Parse package
23269                int parseFlags = mDefParseFlags;
23270                if (args.isExternalAsec()) {
23271                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23272                }
23273                if (args.isFwdLocked()) {
23274                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23275                }
23276
23277                synchronized (mInstallLock) {
23278                    PackageParser.Package pkg = null;
23279                    try {
23280                        // Sadly we don't know the package name yet to freeze it
23281                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23282                                SCAN_IGNORE_FROZEN, 0, null);
23283                    } catch (PackageManagerException e) {
23284                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23285                    }
23286                    // Scan the package
23287                    if (pkg != null) {
23288                        /*
23289                         * TODO why is the lock being held? doPostInstall is
23290                         * called in other places without the lock. This needs
23291                         * to be straightened out.
23292                         */
23293                        // writer
23294                        synchronized (mPackages) {
23295                            retCode = PackageManager.INSTALL_SUCCEEDED;
23296                            pkgList.add(pkg.packageName);
23297                            // Post process args
23298                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23299                                    pkg.applicationInfo.uid);
23300                        }
23301                    } else {
23302                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23303                    }
23304                }
23305
23306            } finally {
23307                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23308                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23309                }
23310            }
23311        }
23312        // writer
23313        synchronized (mPackages) {
23314            // If the platform SDK has changed since the last time we booted,
23315            // we need to re-grant app permission to catch any new ones that
23316            // appear. This is really a hack, and means that apps can in some
23317            // cases get permissions that the user didn't initially explicitly
23318            // allow... it would be nice to have some better way to handle
23319            // this situation.
23320            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23321                    : mSettings.getInternalVersion();
23322            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23323                    : StorageManager.UUID_PRIVATE_INTERNAL;
23324
23325            int updateFlags = UPDATE_PERMISSIONS_ALL;
23326            if (ver.sdkVersion != mSdkVersion) {
23327                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23328                        + mSdkVersion + "; regranting permissions for external");
23329                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23330            }
23331            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23332
23333            // Yay, everything is now upgraded
23334            ver.forceCurrent();
23335
23336            // can downgrade to reader
23337            // Persist settings
23338            mSettings.writeLPr();
23339        }
23340        // Send a broadcast to let everyone know we are done processing
23341        if (pkgList.size() > 0) {
23342            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23343        }
23344    }
23345
23346   /*
23347     * Utility method to unload a list of specified containers
23348     */
23349    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23350        // Just unmount all valid containers.
23351        for (AsecInstallArgs arg : cidArgs) {
23352            synchronized (mInstallLock) {
23353                arg.doPostDeleteLI(false);
23354           }
23355       }
23356   }
23357
23358    /*
23359     * Unload packages mounted on external media. This involves deleting package
23360     * data from internal structures, sending broadcasts about disabled packages,
23361     * gc'ing to free up references, unmounting all secure containers
23362     * corresponding to packages on external media, and posting a
23363     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23364     * that we always have to post this message if status has been requested no
23365     * matter what.
23366     */
23367    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23368            final boolean reportStatus) {
23369        if (DEBUG_SD_INSTALL)
23370            Log.i(TAG, "unloading media packages");
23371        ArrayList<String> pkgList = new ArrayList<String>();
23372        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23373        final Set<AsecInstallArgs> keys = processCids.keySet();
23374        for (AsecInstallArgs args : keys) {
23375            String pkgName = args.getPackageName();
23376            if (DEBUG_SD_INSTALL)
23377                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23378            // Delete package internally
23379            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23380            synchronized (mInstallLock) {
23381                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23382                final boolean res;
23383                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23384                        "unloadMediaPackages")) {
23385                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23386                            null);
23387                }
23388                if (res) {
23389                    pkgList.add(pkgName);
23390                } else {
23391                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23392                    failedList.add(args);
23393                }
23394            }
23395        }
23396
23397        // reader
23398        synchronized (mPackages) {
23399            // We didn't update the settings after removing each package;
23400            // write them now for all packages.
23401            mSettings.writeLPr();
23402        }
23403
23404        // We have to absolutely send UPDATED_MEDIA_STATUS only
23405        // after confirming that all the receivers processed the ordered
23406        // broadcast when packages get disabled, force a gc to clean things up.
23407        // and unload all the containers.
23408        if (pkgList.size() > 0) {
23409            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23410                    new IIntentReceiver.Stub() {
23411                public void performReceive(Intent intent, int resultCode, String data,
23412                        Bundle extras, boolean ordered, boolean sticky,
23413                        int sendingUser) throws RemoteException {
23414                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23415                            reportStatus ? 1 : 0, 1, keys);
23416                    mHandler.sendMessage(msg);
23417                }
23418            });
23419        } else {
23420            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23421                    keys);
23422            mHandler.sendMessage(msg);
23423        }
23424    }
23425
23426    private void loadPrivatePackages(final VolumeInfo vol) {
23427        mHandler.post(new Runnable() {
23428            @Override
23429            public void run() {
23430                loadPrivatePackagesInner(vol);
23431            }
23432        });
23433    }
23434
23435    private void loadPrivatePackagesInner(VolumeInfo vol) {
23436        final String volumeUuid = vol.fsUuid;
23437        if (TextUtils.isEmpty(volumeUuid)) {
23438            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23439            return;
23440        }
23441
23442        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23443        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23444        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23445
23446        final VersionInfo ver;
23447        final List<PackageSetting> packages;
23448        synchronized (mPackages) {
23449            ver = mSettings.findOrCreateVersion(volumeUuid);
23450            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23451        }
23452
23453        for (PackageSetting ps : packages) {
23454            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23455            synchronized (mInstallLock) {
23456                final PackageParser.Package pkg;
23457                try {
23458                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23459                    loaded.add(pkg.applicationInfo);
23460
23461                } catch (PackageManagerException e) {
23462                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23463                }
23464
23465                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23466                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23467                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23468                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23469                }
23470            }
23471        }
23472
23473        // Reconcile app data for all started/unlocked users
23474        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23475        final UserManager um = mContext.getSystemService(UserManager.class);
23476        UserManagerInternal umInternal = getUserManagerInternal();
23477        for (UserInfo user : um.getUsers()) {
23478            final int flags;
23479            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23480                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23481            } else if (umInternal.isUserRunning(user.id)) {
23482                flags = StorageManager.FLAG_STORAGE_DE;
23483            } else {
23484                continue;
23485            }
23486
23487            try {
23488                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23489                synchronized (mInstallLock) {
23490                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23491                }
23492            } catch (IllegalStateException e) {
23493                // Device was probably ejected, and we'll process that event momentarily
23494                Slog.w(TAG, "Failed to prepare storage: " + e);
23495            }
23496        }
23497
23498        synchronized (mPackages) {
23499            int updateFlags = UPDATE_PERMISSIONS_ALL;
23500            if (ver.sdkVersion != mSdkVersion) {
23501                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23502                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23503                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23504            }
23505            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23506
23507            // Yay, everything is now upgraded
23508            ver.forceCurrent();
23509
23510            mSettings.writeLPr();
23511        }
23512
23513        for (PackageFreezer freezer : freezers) {
23514            freezer.close();
23515        }
23516
23517        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23518        sendResourcesChangedBroadcast(true, false, loaded, null);
23519        mLoadedVolumes.add(vol.getId());
23520    }
23521
23522    private void unloadPrivatePackages(final VolumeInfo vol) {
23523        mHandler.post(new Runnable() {
23524            @Override
23525            public void run() {
23526                unloadPrivatePackagesInner(vol);
23527            }
23528        });
23529    }
23530
23531    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23532        final String volumeUuid = vol.fsUuid;
23533        if (TextUtils.isEmpty(volumeUuid)) {
23534            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23535            return;
23536        }
23537
23538        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23539        synchronized (mInstallLock) {
23540        synchronized (mPackages) {
23541            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23542            for (PackageSetting ps : packages) {
23543                if (ps.pkg == null) continue;
23544
23545                final ApplicationInfo info = ps.pkg.applicationInfo;
23546                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23547                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23548
23549                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23550                        "unloadPrivatePackagesInner")) {
23551                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23552                            false, null)) {
23553                        unloaded.add(info);
23554                    } else {
23555                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23556                    }
23557                }
23558
23559                // Try very hard to release any references to this package
23560                // so we don't risk the system server being killed due to
23561                // open FDs
23562                AttributeCache.instance().removePackage(ps.name);
23563            }
23564
23565            mSettings.writeLPr();
23566        }
23567        }
23568
23569        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23570        sendResourcesChangedBroadcast(false, false, unloaded, null);
23571        mLoadedVolumes.remove(vol.getId());
23572
23573        // Try very hard to release any references to this path so we don't risk
23574        // the system server being killed due to open FDs
23575        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23576
23577        for (int i = 0; i < 3; i++) {
23578            System.gc();
23579            System.runFinalization();
23580        }
23581    }
23582
23583    private void assertPackageKnown(String volumeUuid, String packageName)
23584            throws PackageManagerException {
23585        synchronized (mPackages) {
23586            // Normalize package name to handle renamed packages
23587            packageName = normalizePackageNameLPr(packageName);
23588
23589            final PackageSetting ps = mSettings.mPackages.get(packageName);
23590            if (ps == null) {
23591                throw new PackageManagerException("Package " + packageName + " is unknown");
23592            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23593                throw new PackageManagerException(
23594                        "Package " + packageName + " found on unknown volume " + volumeUuid
23595                                + "; expected volume " + ps.volumeUuid);
23596            }
23597        }
23598    }
23599
23600    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23601            throws PackageManagerException {
23602        synchronized (mPackages) {
23603            // Normalize package name to handle renamed packages
23604            packageName = normalizePackageNameLPr(packageName);
23605
23606            final PackageSetting ps = mSettings.mPackages.get(packageName);
23607            if (ps == null) {
23608                throw new PackageManagerException("Package " + packageName + " is unknown");
23609            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23610                throw new PackageManagerException(
23611                        "Package " + packageName + " found on unknown volume " + volumeUuid
23612                                + "; expected volume " + ps.volumeUuid);
23613            } else if (!ps.getInstalled(userId)) {
23614                throw new PackageManagerException(
23615                        "Package " + packageName + " not installed for user " + userId);
23616            }
23617        }
23618    }
23619
23620    private List<String> collectAbsoluteCodePaths() {
23621        synchronized (mPackages) {
23622            List<String> codePaths = new ArrayList<>();
23623            final int packageCount = mSettings.mPackages.size();
23624            for (int i = 0; i < packageCount; i++) {
23625                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23626                codePaths.add(ps.codePath.getAbsolutePath());
23627            }
23628            return codePaths;
23629        }
23630    }
23631
23632    /**
23633     * Examine all apps present on given mounted volume, and destroy apps that
23634     * aren't expected, either due to uninstallation or reinstallation on
23635     * another volume.
23636     */
23637    private void reconcileApps(String volumeUuid) {
23638        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23639        List<File> filesToDelete = null;
23640
23641        final File[] files = FileUtils.listFilesOrEmpty(
23642                Environment.getDataAppDirectory(volumeUuid));
23643        for (File file : files) {
23644            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23645                    && !PackageInstallerService.isStageName(file.getName());
23646            if (!isPackage) {
23647                // Ignore entries which are not packages
23648                continue;
23649            }
23650
23651            String absolutePath = file.getAbsolutePath();
23652
23653            boolean pathValid = false;
23654            final int absoluteCodePathCount = absoluteCodePaths.size();
23655            for (int i = 0; i < absoluteCodePathCount; i++) {
23656                String absoluteCodePath = absoluteCodePaths.get(i);
23657                if (absolutePath.startsWith(absoluteCodePath)) {
23658                    pathValid = true;
23659                    break;
23660                }
23661            }
23662
23663            if (!pathValid) {
23664                if (filesToDelete == null) {
23665                    filesToDelete = new ArrayList<>();
23666                }
23667                filesToDelete.add(file);
23668            }
23669        }
23670
23671        if (filesToDelete != null) {
23672            final int fileToDeleteCount = filesToDelete.size();
23673            for (int i = 0; i < fileToDeleteCount; i++) {
23674                File fileToDelete = filesToDelete.get(i);
23675                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23676                synchronized (mInstallLock) {
23677                    removeCodePathLI(fileToDelete);
23678                }
23679            }
23680        }
23681    }
23682
23683    /**
23684     * Reconcile all app data for the given user.
23685     * <p>
23686     * Verifies that directories exist and that ownership and labeling is
23687     * correct for all installed apps on all mounted volumes.
23688     */
23689    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23690        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23691        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23692            final String volumeUuid = vol.getFsUuid();
23693            synchronized (mInstallLock) {
23694                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23695            }
23696        }
23697    }
23698
23699    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23700            boolean migrateAppData) {
23701        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23702    }
23703
23704    /**
23705     * Reconcile all app data on given mounted volume.
23706     * <p>
23707     * Destroys app data that isn't expected, either due to uninstallation or
23708     * reinstallation on another volume.
23709     * <p>
23710     * Verifies that directories exist and that ownership and labeling is
23711     * correct for all installed apps.
23712     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23713     */
23714    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23715            boolean migrateAppData, boolean onlyCoreApps) {
23716        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23717                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23718        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23719
23720        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23721        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23722
23723        // First look for stale data that doesn't belong, and check if things
23724        // have changed since we did our last restorecon
23725        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23726            if (StorageManager.isFileEncryptedNativeOrEmulated()
23727                    && !StorageManager.isUserKeyUnlocked(userId)) {
23728                throw new RuntimeException(
23729                        "Yikes, someone asked us to reconcile CE storage while " + userId
23730                                + " was still locked; this would have caused massive data loss!");
23731            }
23732
23733            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23734            for (File file : files) {
23735                final String packageName = file.getName();
23736                try {
23737                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23738                } catch (PackageManagerException e) {
23739                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23740                    try {
23741                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23742                                StorageManager.FLAG_STORAGE_CE, 0);
23743                    } catch (InstallerException e2) {
23744                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23745                    }
23746                }
23747            }
23748        }
23749        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23750            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23751            for (File file : files) {
23752                final String packageName = file.getName();
23753                try {
23754                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23755                } catch (PackageManagerException e) {
23756                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23757                    try {
23758                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23759                                StorageManager.FLAG_STORAGE_DE, 0);
23760                    } catch (InstallerException e2) {
23761                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23762                    }
23763                }
23764            }
23765        }
23766
23767        // Ensure that data directories are ready to roll for all packages
23768        // installed for this volume and user
23769        final List<PackageSetting> packages;
23770        synchronized (mPackages) {
23771            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23772        }
23773        int preparedCount = 0;
23774        for (PackageSetting ps : packages) {
23775            final String packageName = ps.name;
23776            if (ps.pkg == null) {
23777                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23778                // TODO: might be due to legacy ASEC apps; we should circle back
23779                // and reconcile again once they're scanned
23780                continue;
23781            }
23782            // Skip non-core apps if requested
23783            if (onlyCoreApps && !ps.pkg.coreApp) {
23784                result.add(packageName);
23785                continue;
23786            }
23787
23788            if (ps.getInstalled(userId)) {
23789                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23790                preparedCount++;
23791            }
23792        }
23793
23794        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23795        return result;
23796    }
23797
23798    /**
23799     * Prepare app data for the given app just after it was installed or
23800     * upgraded. This method carefully only touches users that it's installed
23801     * for, and it forces a restorecon to handle any seinfo changes.
23802     * <p>
23803     * Verifies that directories exist and that ownership and labeling is
23804     * correct for all installed apps. If there is an ownership mismatch, it
23805     * will try recovering system apps by wiping data; third-party app data is
23806     * left intact.
23807     * <p>
23808     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23809     */
23810    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23811        final PackageSetting ps;
23812        synchronized (mPackages) {
23813            ps = mSettings.mPackages.get(pkg.packageName);
23814            mSettings.writeKernelMappingLPr(ps);
23815        }
23816
23817        final UserManager um = mContext.getSystemService(UserManager.class);
23818        UserManagerInternal umInternal = getUserManagerInternal();
23819        for (UserInfo user : um.getUsers()) {
23820            final int flags;
23821            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23822                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23823            } else if (umInternal.isUserRunning(user.id)) {
23824                flags = StorageManager.FLAG_STORAGE_DE;
23825            } else {
23826                continue;
23827            }
23828
23829            if (ps.getInstalled(user.id)) {
23830                // TODO: when user data is locked, mark that we're still dirty
23831                prepareAppDataLIF(pkg, user.id, flags);
23832            }
23833        }
23834    }
23835
23836    /**
23837     * Prepare app data for the given app.
23838     * <p>
23839     * Verifies that directories exist and that ownership and labeling is
23840     * correct for all installed apps. If there is an ownership mismatch, this
23841     * will try recovering system apps by wiping data; third-party app data is
23842     * left intact.
23843     */
23844    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23845        if (pkg == null) {
23846            Slog.wtf(TAG, "Package was null!", new Throwable());
23847            return;
23848        }
23849        prepareAppDataLeafLIF(pkg, userId, flags);
23850        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23851        for (int i = 0; i < childCount; i++) {
23852            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23853        }
23854    }
23855
23856    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23857            boolean maybeMigrateAppData) {
23858        prepareAppDataLIF(pkg, userId, flags);
23859
23860        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23861            // We may have just shuffled around app data directories, so
23862            // prepare them one more time
23863            prepareAppDataLIF(pkg, userId, flags);
23864        }
23865    }
23866
23867    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23868        if (DEBUG_APP_DATA) {
23869            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23870                    + Integer.toHexString(flags));
23871        }
23872
23873        final String volumeUuid = pkg.volumeUuid;
23874        final String packageName = pkg.packageName;
23875        final ApplicationInfo app = pkg.applicationInfo;
23876        final int appId = UserHandle.getAppId(app.uid);
23877
23878        Preconditions.checkNotNull(app.seInfo);
23879
23880        long ceDataInode = -1;
23881        try {
23882            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23883                    appId, app.seInfo, app.targetSdkVersion);
23884        } catch (InstallerException e) {
23885            if (app.isSystemApp()) {
23886                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23887                        + ", but trying to recover: " + e);
23888                destroyAppDataLeafLIF(pkg, userId, flags);
23889                try {
23890                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23891                            appId, app.seInfo, app.targetSdkVersion);
23892                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23893                } catch (InstallerException e2) {
23894                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23895                }
23896            } else {
23897                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23898            }
23899        }
23900
23901        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23902            // TODO: mark this structure as dirty so we persist it!
23903            synchronized (mPackages) {
23904                final PackageSetting ps = mSettings.mPackages.get(packageName);
23905                if (ps != null) {
23906                    ps.setCeDataInode(ceDataInode, userId);
23907                }
23908            }
23909        }
23910
23911        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23912    }
23913
23914    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23915        if (pkg == null) {
23916            Slog.wtf(TAG, "Package was null!", new Throwable());
23917            return;
23918        }
23919        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23920        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23921        for (int i = 0; i < childCount; i++) {
23922            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23923        }
23924    }
23925
23926    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23927        final String volumeUuid = pkg.volumeUuid;
23928        final String packageName = pkg.packageName;
23929        final ApplicationInfo app = pkg.applicationInfo;
23930
23931        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23932            // Create a native library symlink only if we have native libraries
23933            // and if the native libraries are 32 bit libraries. We do not provide
23934            // this symlink for 64 bit libraries.
23935            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23936                final String nativeLibPath = app.nativeLibraryDir;
23937                try {
23938                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23939                            nativeLibPath, userId);
23940                } catch (InstallerException e) {
23941                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23942                }
23943            }
23944        }
23945    }
23946
23947    /**
23948     * For system apps on non-FBE devices, this method migrates any existing
23949     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23950     * requested by the app.
23951     */
23952    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23953        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23954                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23955            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23956                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23957            try {
23958                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23959                        storageTarget);
23960            } catch (InstallerException e) {
23961                logCriticalInfo(Log.WARN,
23962                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23963            }
23964            return true;
23965        } else {
23966            return false;
23967        }
23968    }
23969
23970    public PackageFreezer freezePackage(String packageName, String killReason) {
23971        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23972    }
23973
23974    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23975        return new PackageFreezer(packageName, userId, killReason);
23976    }
23977
23978    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23979            String killReason) {
23980        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23981    }
23982
23983    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23984            String killReason) {
23985        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23986            return new PackageFreezer();
23987        } else {
23988            return freezePackage(packageName, userId, killReason);
23989        }
23990    }
23991
23992    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23993            String killReason) {
23994        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23995    }
23996
23997    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23998            String killReason) {
23999        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
24000            return new PackageFreezer();
24001        } else {
24002            return freezePackage(packageName, userId, killReason);
24003        }
24004    }
24005
24006    /**
24007     * Class that freezes and kills the given package upon creation, and
24008     * unfreezes it upon closing. This is typically used when doing surgery on
24009     * app code/data to prevent the app from running while you're working.
24010     */
24011    private class PackageFreezer implements AutoCloseable {
24012        private final String mPackageName;
24013        private final PackageFreezer[] mChildren;
24014
24015        private final boolean mWeFroze;
24016
24017        private final AtomicBoolean mClosed = new AtomicBoolean();
24018        private final CloseGuard mCloseGuard = CloseGuard.get();
24019
24020        /**
24021         * Create and return a stub freezer that doesn't actually do anything,
24022         * typically used when someone requested
24023         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
24024         * {@link PackageManager#DELETE_DONT_KILL_APP}.
24025         */
24026        public PackageFreezer() {
24027            mPackageName = null;
24028            mChildren = null;
24029            mWeFroze = false;
24030            mCloseGuard.open("close");
24031        }
24032
24033        public PackageFreezer(String packageName, int userId, String killReason) {
24034            synchronized (mPackages) {
24035                mPackageName = packageName;
24036                mWeFroze = mFrozenPackages.add(mPackageName);
24037
24038                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24039                if (ps != null) {
24040                    killApplication(ps.name, ps.appId, userId, killReason);
24041                }
24042
24043                final PackageParser.Package p = mPackages.get(packageName);
24044                if (p != null && p.childPackages != null) {
24045                    final int N = p.childPackages.size();
24046                    mChildren = new PackageFreezer[N];
24047                    for (int i = 0; i < N; i++) {
24048                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24049                                userId, killReason);
24050                    }
24051                } else {
24052                    mChildren = null;
24053                }
24054            }
24055            mCloseGuard.open("close");
24056        }
24057
24058        @Override
24059        protected void finalize() throws Throwable {
24060            try {
24061                if (mCloseGuard != null) {
24062                    mCloseGuard.warnIfOpen();
24063                }
24064
24065                close();
24066            } finally {
24067                super.finalize();
24068            }
24069        }
24070
24071        @Override
24072        public void close() {
24073            mCloseGuard.close();
24074            if (mClosed.compareAndSet(false, true)) {
24075                synchronized (mPackages) {
24076                    if (mWeFroze) {
24077                        mFrozenPackages.remove(mPackageName);
24078                    }
24079
24080                    if (mChildren != null) {
24081                        for (PackageFreezer freezer : mChildren) {
24082                            freezer.close();
24083                        }
24084                    }
24085                }
24086            }
24087        }
24088    }
24089
24090    /**
24091     * Verify that given package is currently frozen.
24092     */
24093    private void checkPackageFrozen(String packageName) {
24094        synchronized (mPackages) {
24095            if (!mFrozenPackages.contains(packageName)) {
24096                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24097            }
24098        }
24099    }
24100
24101    @Override
24102    public int movePackage(final String packageName, final String volumeUuid) {
24103        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24104
24105        final int callingUid = Binder.getCallingUid();
24106        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24107        final int moveId = mNextMoveId.getAndIncrement();
24108        mHandler.post(new Runnable() {
24109            @Override
24110            public void run() {
24111                try {
24112                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24113                } catch (PackageManagerException e) {
24114                    Slog.w(TAG, "Failed to move " + packageName, e);
24115                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24116                }
24117            }
24118        });
24119        return moveId;
24120    }
24121
24122    private void movePackageInternal(final String packageName, final String volumeUuid,
24123            final int moveId, final int callingUid, UserHandle user)
24124                    throws PackageManagerException {
24125        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24126        final PackageManager pm = mContext.getPackageManager();
24127
24128        final boolean currentAsec;
24129        final String currentVolumeUuid;
24130        final File codeFile;
24131        final String installerPackageName;
24132        final String packageAbiOverride;
24133        final int appId;
24134        final String seinfo;
24135        final String label;
24136        final int targetSdkVersion;
24137        final PackageFreezer freezer;
24138        final int[] installedUserIds;
24139
24140        // reader
24141        synchronized (mPackages) {
24142            final PackageParser.Package pkg = mPackages.get(packageName);
24143            final PackageSetting ps = mSettings.mPackages.get(packageName);
24144            if (pkg == null
24145                    || ps == null
24146                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24147                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24148            }
24149            if (pkg.applicationInfo.isSystemApp()) {
24150                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24151                        "Cannot move system application");
24152            }
24153
24154            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24155            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24156                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24157            if (isInternalStorage && !allow3rdPartyOnInternal) {
24158                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24159                        "3rd party apps are not allowed on internal storage");
24160            }
24161
24162            if (pkg.applicationInfo.isExternalAsec()) {
24163                currentAsec = true;
24164                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24165            } else if (pkg.applicationInfo.isForwardLocked()) {
24166                currentAsec = true;
24167                currentVolumeUuid = "forward_locked";
24168            } else {
24169                currentAsec = false;
24170                currentVolumeUuid = ps.volumeUuid;
24171
24172                final File probe = new File(pkg.codePath);
24173                final File probeOat = new File(probe, "oat");
24174                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24175                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24176                            "Move only supported for modern cluster style installs");
24177                }
24178            }
24179
24180            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24181                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24182                        "Package already moved to " + volumeUuid);
24183            }
24184            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24185                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24186                        "Device admin cannot be moved");
24187            }
24188
24189            if (mFrozenPackages.contains(packageName)) {
24190                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24191                        "Failed to move already frozen package");
24192            }
24193
24194            codeFile = new File(pkg.codePath);
24195            installerPackageName = ps.installerPackageName;
24196            packageAbiOverride = ps.cpuAbiOverrideString;
24197            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24198            seinfo = pkg.applicationInfo.seInfo;
24199            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24200            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24201            freezer = freezePackage(packageName, "movePackageInternal");
24202            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24203        }
24204
24205        final Bundle extras = new Bundle();
24206        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24207        extras.putString(Intent.EXTRA_TITLE, label);
24208        mMoveCallbacks.notifyCreated(moveId, extras);
24209
24210        int installFlags;
24211        final boolean moveCompleteApp;
24212        final File measurePath;
24213
24214        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24215            installFlags = INSTALL_INTERNAL;
24216            moveCompleteApp = !currentAsec;
24217            measurePath = Environment.getDataAppDirectory(volumeUuid);
24218        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24219            installFlags = INSTALL_EXTERNAL;
24220            moveCompleteApp = false;
24221            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24222        } else {
24223            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24224            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24225                    || !volume.isMountedWritable()) {
24226                freezer.close();
24227                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24228                        "Move location not mounted private volume");
24229            }
24230
24231            Preconditions.checkState(!currentAsec);
24232
24233            installFlags = INSTALL_INTERNAL;
24234            moveCompleteApp = true;
24235            measurePath = Environment.getDataAppDirectory(volumeUuid);
24236        }
24237
24238        // If we're moving app data around, we need all the users unlocked
24239        if (moveCompleteApp) {
24240            for (int userId : installedUserIds) {
24241                if (StorageManager.isFileEncryptedNativeOrEmulated()
24242                        && !StorageManager.isUserKeyUnlocked(userId)) {
24243                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24244                            "User " + userId + " must be unlocked");
24245                }
24246            }
24247        }
24248
24249        final PackageStats stats = new PackageStats(null, -1);
24250        synchronized (mInstaller) {
24251            for (int userId : installedUserIds) {
24252                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24253                    freezer.close();
24254                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24255                            "Failed to measure package size");
24256                }
24257            }
24258        }
24259
24260        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24261                + stats.dataSize);
24262
24263        final long startFreeBytes = measurePath.getUsableSpace();
24264        final long sizeBytes;
24265        if (moveCompleteApp) {
24266            sizeBytes = stats.codeSize + stats.dataSize;
24267        } else {
24268            sizeBytes = stats.codeSize;
24269        }
24270
24271        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24272            freezer.close();
24273            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24274                    "Not enough free space to move");
24275        }
24276
24277        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24278
24279        final CountDownLatch installedLatch = new CountDownLatch(1);
24280        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24281            @Override
24282            public void onUserActionRequired(Intent intent) throws RemoteException {
24283                throw new IllegalStateException();
24284            }
24285
24286            @Override
24287            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24288                    Bundle extras) throws RemoteException {
24289                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24290                        + PackageManager.installStatusToString(returnCode, msg));
24291
24292                installedLatch.countDown();
24293                freezer.close();
24294
24295                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24296                switch (status) {
24297                    case PackageInstaller.STATUS_SUCCESS:
24298                        mMoveCallbacks.notifyStatusChanged(moveId,
24299                                PackageManager.MOVE_SUCCEEDED);
24300                        break;
24301                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24302                        mMoveCallbacks.notifyStatusChanged(moveId,
24303                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24304                        break;
24305                    default:
24306                        mMoveCallbacks.notifyStatusChanged(moveId,
24307                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24308                        break;
24309                }
24310            }
24311        };
24312
24313        final MoveInfo move;
24314        if (moveCompleteApp) {
24315            // Kick off a thread to report progress estimates
24316            new Thread() {
24317                @Override
24318                public void run() {
24319                    while (true) {
24320                        try {
24321                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24322                                break;
24323                            }
24324                        } catch (InterruptedException ignored) {
24325                        }
24326
24327                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24328                        final int progress = 10 + (int) MathUtils.constrain(
24329                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24330                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24331                    }
24332                }
24333            }.start();
24334
24335            final String dataAppName = codeFile.getName();
24336            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24337                    dataAppName, appId, seinfo, targetSdkVersion);
24338        } else {
24339            move = null;
24340        }
24341
24342        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24343
24344        final Message msg = mHandler.obtainMessage(INIT_COPY);
24345        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24346        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24347                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24348                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24349                PackageManager.INSTALL_REASON_UNKNOWN);
24350        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24351        msg.obj = params;
24352
24353        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24354                System.identityHashCode(msg.obj));
24355        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24356                System.identityHashCode(msg.obj));
24357
24358        mHandler.sendMessage(msg);
24359    }
24360
24361    @Override
24362    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24363        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24364
24365        final int realMoveId = mNextMoveId.getAndIncrement();
24366        final Bundle extras = new Bundle();
24367        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24368        mMoveCallbacks.notifyCreated(realMoveId, extras);
24369
24370        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24371            @Override
24372            public void onCreated(int moveId, Bundle extras) {
24373                // Ignored
24374            }
24375
24376            @Override
24377            public void onStatusChanged(int moveId, int status, long estMillis) {
24378                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24379            }
24380        };
24381
24382        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24383        storage.setPrimaryStorageUuid(volumeUuid, callback);
24384        return realMoveId;
24385    }
24386
24387    @Override
24388    public int getMoveStatus(int moveId) {
24389        mContext.enforceCallingOrSelfPermission(
24390                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24391        return mMoveCallbacks.mLastStatus.get(moveId);
24392    }
24393
24394    @Override
24395    public void registerMoveCallback(IPackageMoveObserver callback) {
24396        mContext.enforceCallingOrSelfPermission(
24397                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24398        mMoveCallbacks.register(callback);
24399    }
24400
24401    @Override
24402    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24403        mContext.enforceCallingOrSelfPermission(
24404                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24405        mMoveCallbacks.unregister(callback);
24406    }
24407
24408    @Override
24409    public boolean setInstallLocation(int loc) {
24410        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24411                null);
24412        if (getInstallLocation() == loc) {
24413            return true;
24414        }
24415        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24416                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24417            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24418                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24419            return true;
24420        }
24421        return false;
24422   }
24423
24424    @Override
24425    public int getInstallLocation() {
24426        // allow instant app access
24427        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24428                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24429                PackageHelper.APP_INSTALL_AUTO);
24430    }
24431
24432    /** Called by UserManagerService */
24433    void cleanUpUser(UserManagerService userManager, int userHandle) {
24434        synchronized (mPackages) {
24435            mDirtyUsers.remove(userHandle);
24436            mUserNeedsBadging.delete(userHandle);
24437            mSettings.removeUserLPw(userHandle);
24438            mPendingBroadcasts.remove(userHandle);
24439            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24440            removeUnusedPackagesLPw(userManager, userHandle);
24441        }
24442    }
24443
24444    /**
24445     * We're removing userHandle and would like to remove any downloaded packages
24446     * that are no longer in use by any other user.
24447     * @param userHandle the user being removed
24448     */
24449    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24450        final boolean DEBUG_CLEAN_APKS = false;
24451        int [] users = userManager.getUserIds();
24452        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24453        while (psit.hasNext()) {
24454            PackageSetting ps = psit.next();
24455            if (ps.pkg == null) {
24456                continue;
24457            }
24458            final String packageName = ps.pkg.packageName;
24459            // Skip over if system app
24460            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24461                continue;
24462            }
24463            if (DEBUG_CLEAN_APKS) {
24464                Slog.i(TAG, "Checking package " + packageName);
24465            }
24466            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24467            if (keep) {
24468                if (DEBUG_CLEAN_APKS) {
24469                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24470                }
24471            } else {
24472                for (int i = 0; i < users.length; i++) {
24473                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24474                        keep = true;
24475                        if (DEBUG_CLEAN_APKS) {
24476                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24477                                    + users[i]);
24478                        }
24479                        break;
24480                    }
24481                }
24482            }
24483            if (!keep) {
24484                if (DEBUG_CLEAN_APKS) {
24485                    Slog.i(TAG, "  Removing package " + packageName);
24486                }
24487                mHandler.post(new Runnable() {
24488                    public void run() {
24489                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24490                                userHandle, 0);
24491                    } //end run
24492                });
24493            }
24494        }
24495    }
24496
24497    /** Called by UserManagerService */
24498    void createNewUser(int userId, String[] disallowedPackages) {
24499        synchronized (mInstallLock) {
24500            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24501        }
24502        synchronized (mPackages) {
24503            scheduleWritePackageRestrictionsLocked(userId);
24504            scheduleWritePackageListLocked(userId);
24505            applyFactoryDefaultBrowserLPw(userId);
24506            primeDomainVerificationsLPw(userId);
24507        }
24508    }
24509
24510    void onNewUserCreated(final int userId) {
24511        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24512        // If permission review for legacy apps is required, we represent
24513        // dagerous permissions for such apps as always granted runtime
24514        // permissions to keep per user flag state whether review is needed.
24515        // Hence, if a new user is added we have to propagate dangerous
24516        // permission grants for these legacy apps.
24517        if (mPermissionReviewRequired) {
24518            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24519                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24520        }
24521    }
24522
24523    @Override
24524    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24525        mContext.enforceCallingOrSelfPermission(
24526                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24527                "Only package verification agents can read the verifier device identity");
24528
24529        synchronized (mPackages) {
24530            return mSettings.getVerifierDeviceIdentityLPw();
24531        }
24532    }
24533
24534    @Override
24535    public void setPermissionEnforced(String permission, boolean enforced) {
24536        // TODO: Now that we no longer change GID for storage, this should to away.
24537        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24538                "setPermissionEnforced");
24539        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24540            synchronized (mPackages) {
24541                if (mSettings.mReadExternalStorageEnforced == null
24542                        || mSettings.mReadExternalStorageEnforced != enforced) {
24543                    mSettings.mReadExternalStorageEnforced = enforced;
24544                    mSettings.writeLPr();
24545                }
24546            }
24547            // kill any non-foreground processes so we restart them and
24548            // grant/revoke the GID.
24549            final IActivityManager am = ActivityManager.getService();
24550            if (am != null) {
24551                final long token = Binder.clearCallingIdentity();
24552                try {
24553                    am.killProcessesBelowForeground("setPermissionEnforcement");
24554                } catch (RemoteException e) {
24555                } finally {
24556                    Binder.restoreCallingIdentity(token);
24557                }
24558            }
24559        } else {
24560            throw new IllegalArgumentException("No selective enforcement for " + permission);
24561        }
24562    }
24563
24564    @Override
24565    @Deprecated
24566    public boolean isPermissionEnforced(String permission) {
24567        // allow instant applications
24568        return true;
24569    }
24570
24571    @Override
24572    public boolean isStorageLow() {
24573        // allow instant applications
24574        final long token = Binder.clearCallingIdentity();
24575        try {
24576            final DeviceStorageMonitorInternal
24577                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24578            if (dsm != null) {
24579                return dsm.isMemoryLow();
24580            } else {
24581                return false;
24582            }
24583        } finally {
24584            Binder.restoreCallingIdentity(token);
24585        }
24586    }
24587
24588    @Override
24589    public IPackageInstaller getPackageInstaller() {
24590        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24591            return null;
24592        }
24593        return mInstallerService;
24594    }
24595
24596    private boolean userNeedsBadging(int userId) {
24597        int index = mUserNeedsBadging.indexOfKey(userId);
24598        if (index < 0) {
24599            final UserInfo userInfo;
24600            final long token = Binder.clearCallingIdentity();
24601            try {
24602                userInfo = sUserManager.getUserInfo(userId);
24603            } finally {
24604                Binder.restoreCallingIdentity(token);
24605            }
24606            final boolean b;
24607            if (userInfo != null && userInfo.isManagedProfile()) {
24608                b = true;
24609            } else {
24610                b = false;
24611            }
24612            mUserNeedsBadging.put(userId, b);
24613            return b;
24614        }
24615        return mUserNeedsBadging.valueAt(index);
24616    }
24617
24618    @Override
24619    public KeySet getKeySetByAlias(String packageName, String alias) {
24620        if (packageName == null || alias == null) {
24621            return null;
24622        }
24623        synchronized(mPackages) {
24624            final PackageParser.Package pkg = mPackages.get(packageName);
24625            if (pkg == null) {
24626                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24627                throw new IllegalArgumentException("Unknown package: " + packageName);
24628            }
24629            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24630            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24631                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24632                throw new IllegalArgumentException("Unknown package: " + packageName);
24633            }
24634            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24635            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24636        }
24637    }
24638
24639    @Override
24640    public KeySet getSigningKeySet(String packageName) {
24641        if (packageName == null) {
24642            return null;
24643        }
24644        synchronized(mPackages) {
24645            final int callingUid = Binder.getCallingUid();
24646            final int callingUserId = UserHandle.getUserId(callingUid);
24647            final PackageParser.Package pkg = mPackages.get(packageName);
24648            if (pkg == null) {
24649                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24650                throw new IllegalArgumentException("Unknown package: " + packageName);
24651            }
24652            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24653            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24654                // filter and pretend the package doesn't exist
24655                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24656                        + ", uid:" + callingUid);
24657                throw new IllegalArgumentException("Unknown package: " + packageName);
24658            }
24659            if (pkg.applicationInfo.uid != callingUid
24660                    && Process.SYSTEM_UID != callingUid) {
24661                throw new SecurityException("May not access signing KeySet of other apps.");
24662            }
24663            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24664            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24665        }
24666    }
24667
24668    @Override
24669    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24670        final int callingUid = Binder.getCallingUid();
24671        if (getInstantAppPackageName(callingUid) != null) {
24672            return false;
24673        }
24674        if (packageName == null || ks == null) {
24675            return false;
24676        }
24677        synchronized(mPackages) {
24678            final PackageParser.Package pkg = mPackages.get(packageName);
24679            if (pkg == null
24680                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24681                            UserHandle.getUserId(callingUid))) {
24682                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24683                throw new IllegalArgumentException("Unknown package: " + packageName);
24684            }
24685            IBinder ksh = ks.getToken();
24686            if (ksh instanceof KeySetHandle) {
24687                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24688                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24689            }
24690            return false;
24691        }
24692    }
24693
24694    @Override
24695    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24696        final int callingUid = Binder.getCallingUid();
24697        if (getInstantAppPackageName(callingUid) != null) {
24698            return false;
24699        }
24700        if (packageName == null || ks == null) {
24701            return false;
24702        }
24703        synchronized(mPackages) {
24704            final PackageParser.Package pkg = mPackages.get(packageName);
24705            if (pkg == null
24706                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24707                            UserHandle.getUserId(callingUid))) {
24708                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24709                throw new IllegalArgumentException("Unknown package: " + packageName);
24710            }
24711            IBinder ksh = ks.getToken();
24712            if (ksh instanceof KeySetHandle) {
24713                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24714                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24715            }
24716            return false;
24717        }
24718    }
24719
24720    private void deletePackageIfUnusedLPr(final String packageName) {
24721        PackageSetting ps = mSettings.mPackages.get(packageName);
24722        if (ps == null) {
24723            return;
24724        }
24725        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24726            // TODO Implement atomic delete if package is unused
24727            // It is currently possible that the package will be deleted even if it is installed
24728            // after this method returns.
24729            mHandler.post(new Runnable() {
24730                public void run() {
24731                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24732                            0, PackageManager.DELETE_ALL_USERS);
24733                }
24734            });
24735        }
24736    }
24737
24738    /**
24739     * Check and throw if the given before/after packages would be considered a
24740     * downgrade.
24741     */
24742    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24743            throws PackageManagerException {
24744        if (after.versionCode < before.mVersionCode) {
24745            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24746                    "Update version code " + after.versionCode + " is older than current "
24747                    + before.mVersionCode);
24748        } else if (after.versionCode == before.mVersionCode) {
24749            if (after.baseRevisionCode < before.baseRevisionCode) {
24750                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24751                        "Update base revision code " + after.baseRevisionCode
24752                        + " is older than current " + before.baseRevisionCode);
24753            }
24754
24755            if (!ArrayUtils.isEmpty(after.splitNames)) {
24756                for (int i = 0; i < after.splitNames.length; i++) {
24757                    final String splitName = after.splitNames[i];
24758                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24759                    if (j != -1) {
24760                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24761                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24762                                    "Update split " + splitName + " revision code "
24763                                    + after.splitRevisionCodes[i] + " is older than current "
24764                                    + before.splitRevisionCodes[j]);
24765                        }
24766                    }
24767                }
24768            }
24769        }
24770    }
24771
24772    private static class MoveCallbacks extends Handler {
24773        private static final int MSG_CREATED = 1;
24774        private static final int MSG_STATUS_CHANGED = 2;
24775
24776        private final RemoteCallbackList<IPackageMoveObserver>
24777                mCallbacks = new RemoteCallbackList<>();
24778
24779        private final SparseIntArray mLastStatus = new SparseIntArray();
24780
24781        public MoveCallbacks(Looper looper) {
24782            super(looper);
24783        }
24784
24785        public void register(IPackageMoveObserver callback) {
24786            mCallbacks.register(callback);
24787        }
24788
24789        public void unregister(IPackageMoveObserver callback) {
24790            mCallbacks.unregister(callback);
24791        }
24792
24793        @Override
24794        public void handleMessage(Message msg) {
24795            final SomeArgs args = (SomeArgs) msg.obj;
24796            final int n = mCallbacks.beginBroadcast();
24797            for (int i = 0; i < n; i++) {
24798                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24799                try {
24800                    invokeCallback(callback, msg.what, args);
24801                } catch (RemoteException ignored) {
24802                }
24803            }
24804            mCallbacks.finishBroadcast();
24805            args.recycle();
24806        }
24807
24808        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24809                throws RemoteException {
24810            switch (what) {
24811                case MSG_CREATED: {
24812                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24813                    break;
24814                }
24815                case MSG_STATUS_CHANGED: {
24816                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24817                    break;
24818                }
24819            }
24820        }
24821
24822        private void notifyCreated(int moveId, Bundle extras) {
24823            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24824
24825            final SomeArgs args = SomeArgs.obtain();
24826            args.argi1 = moveId;
24827            args.arg2 = extras;
24828            obtainMessage(MSG_CREATED, args).sendToTarget();
24829        }
24830
24831        private void notifyStatusChanged(int moveId, int status) {
24832            notifyStatusChanged(moveId, status, -1);
24833        }
24834
24835        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24836            Slog.v(TAG, "Move " + moveId + " status " + status);
24837
24838            final SomeArgs args = SomeArgs.obtain();
24839            args.argi1 = moveId;
24840            args.argi2 = status;
24841            args.arg3 = estMillis;
24842            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24843
24844            synchronized (mLastStatus) {
24845                mLastStatus.put(moveId, status);
24846            }
24847        }
24848    }
24849
24850    private final static class OnPermissionChangeListeners extends Handler {
24851        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24852
24853        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24854                new RemoteCallbackList<>();
24855
24856        public OnPermissionChangeListeners(Looper looper) {
24857            super(looper);
24858        }
24859
24860        @Override
24861        public void handleMessage(Message msg) {
24862            switch (msg.what) {
24863                case MSG_ON_PERMISSIONS_CHANGED: {
24864                    final int uid = msg.arg1;
24865                    handleOnPermissionsChanged(uid);
24866                } break;
24867            }
24868        }
24869
24870        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24871            mPermissionListeners.register(listener);
24872
24873        }
24874
24875        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24876            mPermissionListeners.unregister(listener);
24877        }
24878
24879        public void onPermissionsChanged(int uid) {
24880            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24881                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24882            }
24883        }
24884
24885        private void handleOnPermissionsChanged(int uid) {
24886            final int count = mPermissionListeners.beginBroadcast();
24887            try {
24888                for (int i = 0; i < count; i++) {
24889                    IOnPermissionsChangeListener callback = mPermissionListeners
24890                            .getBroadcastItem(i);
24891                    try {
24892                        callback.onPermissionsChanged(uid);
24893                    } catch (RemoteException e) {
24894                        Log.e(TAG, "Permission listener is dead", e);
24895                    }
24896                }
24897            } finally {
24898                mPermissionListeners.finishBroadcast();
24899            }
24900        }
24901    }
24902
24903    private class PackageManagerNative extends IPackageManagerNative.Stub {
24904        @Override
24905        public String[] getNamesForUids(int[] uids) throws RemoteException {
24906            final String[] results = PackageManagerService.this.getNamesForUids(uids);
24907            // massage results so they can be parsed by the native binder
24908            for (int i = results.length - 1; i >= 0; --i) {
24909                if (results[i] == null) {
24910                    results[i] = "";
24911                }
24912            }
24913            return results;
24914        }
24915    }
24916
24917    private class PackageManagerInternalImpl extends PackageManagerInternal {
24918        @Override
24919        public void setLocationPackagesProvider(PackagesProvider provider) {
24920            synchronized (mPackages) {
24921                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24922            }
24923        }
24924
24925        @Override
24926        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24927            synchronized (mPackages) {
24928                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24929            }
24930        }
24931
24932        @Override
24933        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24934            synchronized (mPackages) {
24935                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24936            }
24937        }
24938
24939        @Override
24940        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24941            synchronized (mPackages) {
24942                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24943            }
24944        }
24945
24946        @Override
24947        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24948            synchronized (mPackages) {
24949                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24950            }
24951        }
24952
24953        @Override
24954        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24955            synchronized (mPackages) {
24956                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24957            }
24958        }
24959
24960        @Override
24961        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24962            synchronized (mPackages) {
24963                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24964                        packageName, userId);
24965            }
24966        }
24967
24968        @Override
24969        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24970            synchronized (mPackages) {
24971                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24972                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24973                        packageName, userId);
24974            }
24975        }
24976
24977        @Override
24978        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24979            synchronized (mPackages) {
24980                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24981                        packageName, userId);
24982            }
24983        }
24984
24985        @Override
24986        public void setKeepUninstalledPackages(final List<String> packageList) {
24987            Preconditions.checkNotNull(packageList);
24988            List<String> removedFromList = null;
24989            synchronized (mPackages) {
24990                if (mKeepUninstalledPackages != null) {
24991                    final int packagesCount = mKeepUninstalledPackages.size();
24992                    for (int i = 0; i < packagesCount; i++) {
24993                        String oldPackage = mKeepUninstalledPackages.get(i);
24994                        if (packageList != null && packageList.contains(oldPackage)) {
24995                            continue;
24996                        }
24997                        if (removedFromList == null) {
24998                            removedFromList = new ArrayList<>();
24999                        }
25000                        removedFromList.add(oldPackage);
25001                    }
25002                }
25003                mKeepUninstalledPackages = new ArrayList<>(packageList);
25004                if (removedFromList != null) {
25005                    final int removedCount = removedFromList.size();
25006                    for (int i = 0; i < removedCount; i++) {
25007                        deletePackageIfUnusedLPr(removedFromList.get(i));
25008                    }
25009                }
25010            }
25011        }
25012
25013        @Override
25014        public boolean isPermissionsReviewRequired(String packageName, int userId) {
25015            synchronized (mPackages) {
25016                // If we do not support permission review, done.
25017                if (!mPermissionReviewRequired) {
25018                    return false;
25019                }
25020
25021                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
25022                if (packageSetting == null) {
25023                    return false;
25024                }
25025
25026                // Permission review applies only to apps not supporting the new permission model.
25027                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
25028                    return false;
25029                }
25030
25031                // Legacy apps have the permission and get user consent on launch.
25032                PermissionsState permissionsState = packageSetting.getPermissionsState();
25033                return permissionsState.isPermissionReviewRequired(userId);
25034            }
25035        }
25036
25037        @Override
25038        public PackageInfo getPackageInfo(
25039                String packageName, int flags, int filterCallingUid, int userId) {
25040            return PackageManagerService.this
25041                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25042                            flags, filterCallingUid, userId);
25043        }
25044
25045        @Override
25046        public ApplicationInfo getApplicationInfo(
25047                String packageName, int flags, int filterCallingUid, int userId) {
25048            return PackageManagerService.this
25049                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25050        }
25051
25052        @Override
25053        public ActivityInfo getActivityInfo(
25054                ComponentName component, int flags, int filterCallingUid, int userId) {
25055            return PackageManagerService.this
25056                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25057        }
25058
25059        @Override
25060        public List<ResolveInfo> queryIntentActivities(
25061                Intent intent, int flags, int filterCallingUid, int userId) {
25062            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25063            return PackageManagerService.this
25064                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25065                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25066        }
25067
25068        @Override
25069        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25070                int userId) {
25071            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25072        }
25073
25074        @Override
25075        public void setDeviceAndProfileOwnerPackages(
25076                int deviceOwnerUserId, String deviceOwnerPackage,
25077                SparseArray<String> profileOwnerPackages) {
25078            mProtectedPackages.setDeviceAndProfileOwnerPackages(
25079                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25080        }
25081
25082        @Override
25083        public boolean isPackageDataProtected(int userId, String packageName) {
25084            return mProtectedPackages.isPackageDataProtected(userId, packageName);
25085        }
25086
25087        @Override
25088        public boolean isPackageEphemeral(int userId, String packageName) {
25089            synchronized (mPackages) {
25090                final PackageSetting ps = mSettings.mPackages.get(packageName);
25091                return ps != null ? ps.getInstantApp(userId) : false;
25092            }
25093        }
25094
25095        @Override
25096        public boolean wasPackageEverLaunched(String packageName, int userId) {
25097            synchronized (mPackages) {
25098                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25099            }
25100        }
25101
25102        @Override
25103        public void grantRuntimePermission(String packageName, String name, int userId,
25104                boolean overridePolicy) {
25105            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25106                    overridePolicy);
25107        }
25108
25109        @Override
25110        public void revokeRuntimePermission(String packageName, String name, int userId,
25111                boolean overridePolicy) {
25112            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25113                    overridePolicy);
25114        }
25115
25116        @Override
25117        public String getNameForUid(int uid) {
25118            return PackageManagerService.this.getNameForUid(uid);
25119        }
25120
25121        @Override
25122        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25123                Intent origIntent, String resolvedType, String callingPackage,
25124                Bundle verificationBundle, int userId) {
25125            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25126                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25127                    userId);
25128        }
25129
25130        @Override
25131        public void grantEphemeralAccess(int userId, Intent intent,
25132                int targetAppId, int ephemeralAppId) {
25133            synchronized (mPackages) {
25134                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25135                        targetAppId, ephemeralAppId);
25136            }
25137        }
25138
25139        @Override
25140        public boolean isInstantAppInstallerComponent(ComponentName component) {
25141            synchronized (mPackages) {
25142                return mInstantAppInstallerActivity != null
25143                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25144            }
25145        }
25146
25147        @Override
25148        public void pruneInstantApps() {
25149            mInstantAppRegistry.pruneInstantApps();
25150        }
25151
25152        @Override
25153        public String getSetupWizardPackageName() {
25154            return mSetupWizardPackage;
25155        }
25156
25157        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25158            if (policy != null) {
25159                mExternalSourcesPolicy = policy;
25160            }
25161        }
25162
25163        @Override
25164        public boolean isPackagePersistent(String packageName) {
25165            synchronized (mPackages) {
25166                PackageParser.Package pkg = mPackages.get(packageName);
25167                return pkg != null
25168                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25169                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25170                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25171                        : false;
25172            }
25173        }
25174
25175        @Override
25176        public List<PackageInfo> getOverlayPackages(int userId) {
25177            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25178            synchronized (mPackages) {
25179                for (PackageParser.Package p : mPackages.values()) {
25180                    if (p.mOverlayTarget != null) {
25181                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25182                        if (pkg != null) {
25183                            overlayPackages.add(pkg);
25184                        }
25185                    }
25186                }
25187            }
25188            return overlayPackages;
25189        }
25190
25191        @Override
25192        public List<String> getTargetPackageNames(int userId) {
25193            List<String> targetPackages = new ArrayList<>();
25194            synchronized (mPackages) {
25195                for (PackageParser.Package p : mPackages.values()) {
25196                    if (p.mOverlayTarget == null) {
25197                        targetPackages.add(p.packageName);
25198                    }
25199                }
25200            }
25201            return targetPackages;
25202        }
25203
25204        @Override
25205        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25206                @Nullable List<String> overlayPackageNames) {
25207            synchronized (mPackages) {
25208                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25209                    Slog.e(TAG, "failed to find package " + targetPackageName);
25210                    return false;
25211                }
25212                ArrayList<String> overlayPaths = null;
25213                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25214                    final int N = overlayPackageNames.size();
25215                    overlayPaths = new ArrayList<>(N);
25216                    for (int i = 0; i < N; i++) {
25217                        final String packageName = overlayPackageNames.get(i);
25218                        final PackageParser.Package pkg = mPackages.get(packageName);
25219                        if (pkg == null) {
25220                            Slog.e(TAG, "failed to find package " + packageName);
25221                            return false;
25222                        }
25223                        overlayPaths.add(pkg.baseCodePath);
25224                    }
25225                }
25226
25227                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25228                ps.setOverlayPaths(overlayPaths, userId);
25229                return true;
25230            }
25231        }
25232
25233        @Override
25234        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25235                int flags, int userId) {
25236            return resolveIntentInternal(
25237                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25238        }
25239
25240        @Override
25241        public ResolveInfo resolveService(Intent intent, String resolvedType,
25242                int flags, int userId, int callingUid) {
25243            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25244        }
25245
25246        @Override
25247        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25248            synchronized (mPackages) {
25249                mIsolatedOwners.put(isolatedUid, ownerUid);
25250            }
25251        }
25252
25253        @Override
25254        public void removeIsolatedUid(int isolatedUid) {
25255            synchronized (mPackages) {
25256                mIsolatedOwners.delete(isolatedUid);
25257            }
25258        }
25259
25260        @Override
25261        public int getUidTargetSdkVersion(int uid) {
25262            synchronized (mPackages) {
25263                return getUidTargetSdkVersionLockedLPr(uid);
25264            }
25265        }
25266
25267        @Override
25268        public boolean canAccessInstantApps(int callingUid, int userId) {
25269            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25270        }
25271    }
25272
25273    @Override
25274    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25275        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25276        synchronized (mPackages) {
25277            final long identity = Binder.clearCallingIdentity();
25278            try {
25279                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25280                        packageNames, userId);
25281            } finally {
25282                Binder.restoreCallingIdentity(identity);
25283            }
25284        }
25285    }
25286
25287    @Override
25288    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25289        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25290        synchronized (mPackages) {
25291            final long identity = Binder.clearCallingIdentity();
25292            try {
25293                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25294                        packageNames, userId);
25295            } finally {
25296                Binder.restoreCallingIdentity(identity);
25297            }
25298        }
25299    }
25300
25301    private static void enforceSystemOrPhoneCaller(String tag) {
25302        int callingUid = Binder.getCallingUid();
25303        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25304            throw new SecurityException(
25305                    "Cannot call " + tag + " from UID " + callingUid);
25306        }
25307    }
25308
25309    boolean isHistoricalPackageUsageAvailable() {
25310        return mPackageUsage.isHistoricalPackageUsageAvailable();
25311    }
25312
25313    /**
25314     * Return a <b>copy</b> of the collection of packages known to the package manager.
25315     * @return A copy of the values of mPackages.
25316     */
25317    Collection<PackageParser.Package> getPackages() {
25318        synchronized (mPackages) {
25319            return new ArrayList<>(mPackages.values());
25320        }
25321    }
25322
25323    /**
25324     * Logs process start information (including base APK hash) to the security log.
25325     * @hide
25326     */
25327    @Override
25328    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25329            String apkFile, int pid) {
25330        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25331            return;
25332        }
25333        if (!SecurityLog.isLoggingEnabled()) {
25334            return;
25335        }
25336        Bundle data = new Bundle();
25337        data.putLong("startTimestamp", System.currentTimeMillis());
25338        data.putString("processName", processName);
25339        data.putInt("uid", uid);
25340        data.putString("seinfo", seinfo);
25341        data.putString("apkFile", apkFile);
25342        data.putInt("pid", pid);
25343        Message msg = mProcessLoggingHandler.obtainMessage(
25344                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25345        msg.setData(data);
25346        mProcessLoggingHandler.sendMessage(msg);
25347    }
25348
25349    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25350        return mCompilerStats.getPackageStats(pkgName);
25351    }
25352
25353    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25354        return getOrCreateCompilerPackageStats(pkg.packageName);
25355    }
25356
25357    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25358        return mCompilerStats.getOrCreatePackageStats(pkgName);
25359    }
25360
25361    public void deleteCompilerPackageStats(String pkgName) {
25362        mCompilerStats.deletePackageStats(pkgName);
25363    }
25364
25365    @Override
25366    public int getInstallReason(String packageName, int userId) {
25367        final int callingUid = Binder.getCallingUid();
25368        enforceCrossUserPermission(callingUid, userId,
25369                true /* requireFullPermission */, false /* checkShell */,
25370                "get install reason");
25371        synchronized (mPackages) {
25372            final PackageSetting ps = mSettings.mPackages.get(packageName);
25373            if (filterAppAccessLPr(ps, callingUid, userId)) {
25374                return PackageManager.INSTALL_REASON_UNKNOWN;
25375            }
25376            if (ps != null) {
25377                return ps.getInstallReason(userId);
25378            }
25379        }
25380        return PackageManager.INSTALL_REASON_UNKNOWN;
25381    }
25382
25383    @Override
25384    public boolean canRequestPackageInstalls(String packageName, int userId) {
25385        return canRequestPackageInstallsInternal(packageName, 0, userId,
25386                true /* throwIfPermNotDeclared*/);
25387    }
25388
25389    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25390            boolean throwIfPermNotDeclared) {
25391        int callingUid = Binder.getCallingUid();
25392        int uid = getPackageUid(packageName, 0, userId);
25393        if (callingUid != uid && callingUid != Process.ROOT_UID
25394                && callingUid != Process.SYSTEM_UID) {
25395            throw new SecurityException(
25396                    "Caller uid " + callingUid + " does not own package " + packageName);
25397        }
25398        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25399        if (info == null) {
25400            return false;
25401        }
25402        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25403            return false;
25404        }
25405        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25406        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25407        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25408            if (throwIfPermNotDeclared) {
25409                throw new SecurityException("Need to declare " + appOpPermission
25410                        + " to call this api");
25411            } else {
25412                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25413                return false;
25414            }
25415        }
25416        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25417            return false;
25418        }
25419        if (mExternalSourcesPolicy != null) {
25420            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25421            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25422                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25423            }
25424        }
25425        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25426    }
25427
25428    @Override
25429    public ComponentName getInstantAppResolverSettingsComponent() {
25430        return mInstantAppResolverSettingsComponent;
25431    }
25432
25433    @Override
25434    public ComponentName getInstantAppInstallerComponent() {
25435        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25436            return null;
25437        }
25438        return mInstantAppInstallerActivity == null
25439                ? null : mInstantAppInstallerActivity.getComponentName();
25440    }
25441
25442    @Override
25443    public String getInstantAppAndroidId(String packageName, int userId) {
25444        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25445                "getInstantAppAndroidId");
25446        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25447                true /* requireFullPermission */, false /* checkShell */,
25448                "getInstantAppAndroidId");
25449        // Make sure the target is an Instant App.
25450        if (!isInstantApp(packageName, userId)) {
25451            return null;
25452        }
25453        synchronized (mPackages) {
25454            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25455        }
25456    }
25457
25458    boolean canHaveOatDir(String packageName) {
25459        synchronized (mPackages) {
25460            PackageParser.Package p = mPackages.get(packageName);
25461            if (p == null) {
25462                return false;
25463            }
25464            return p.canHaveOatDir();
25465        }
25466    }
25467
25468    private String getOatDir(PackageParser.Package pkg) {
25469        if (!pkg.canHaveOatDir()) {
25470            return null;
25471        }
25472        File codePath = new File(pkg.codePath);
25473        if (codePath.isDirectory()) {
25474            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25475        }
25476        return null;
25477    }
25478
25479    void deleteOatArtifactsOfPackage(String packageName) {
25480        final String[] instructionSets;
25481        final List<String> codePaths;
25482        final String oatDir;
25483        final PackageParser.Package pkg;
25484        synchronized (mPackages) {
25485            pkg = mPackages.get(packageName);
25486        }
25487        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25488        codePaths = pkg.getAllCodePaths();
25489        oatDir = getOatDir(pkg);
25490
25491        for (String codePath : codePaths) {
25492            for (String isa : instructionSets) {
25493                try {
25494                    mInstaller.deleteOdex(codePath, isa, oatDir);
25495                } catch (InstallerException e) {
25496                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25497                }
25498            }
25499        }
25500    }
25501
25502    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25503        Set<String> unusedPackages = new HashSet<>();
25504        long currentTimeInMillis = System.currentTimeMillis();
25505        synchronized (mPackages) {
25506            for (PackageParser.Package pkg : mPackages.values()) {
25507                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25508                if (ps == null) {
25509                    continue;
25510                }
25511                PackageDexUsage.PackageUseInfo packageUseInfo =
25512                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25513                if (PackageManagerServiceUtils
25514                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25515                                downgradeTimeThresholdMillis, packageUseInfo,
25516                                pkg.getLatestPackageUseTimeInMills(),
25517                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25518                    unusedPackages.add(pkg.packageName);
25519                }
25520            }
25521        }
25522        return unusedPackages;
25523    }
25524}
25525
25526interface PackageSender {
25527    void sendPackageBroadcast(final String action, final String pkg,
25528        final Bundle extras, final int flags, final String targetPkg,
25529        final IIntentReceiver finishedReceiver, final int[] userIds);
25530    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25531        boolean includeStopped, int appId, int... userIds);
25532}
25533