PackageManagerService.java revision 563a5cad666555b8bed26fb4eb01c9bd20c2421a
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.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
66import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
67import static android.content.pm.PackageManager.MATCH_ALL;
68import static android.content.pm.PackageManager.MATCH_ANY_USER;
69import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
71import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
72import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
73import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
74import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
75import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
76import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
77import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
78import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
79import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
80import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
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;
90import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
92import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
93import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
94import static com.android.internal.util.ArrayUtils.appendInt;
95import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
98import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
99import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
105import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
106
107import android.Manifest;
108import android.annotation.IntDef;
109import android.annotation.NonNull;
110import android.annotation.Nullable;
111import android.app.ActivityManager;
112import android.app.AppOpsManager;
113import android.app.IActivityManager;
114import android.app.ResourcesManager;
115import android.app.admin.IDevicePolicyManager;
116import android.app.admin.SecurityLog;
117import android.app.backup.IBackupManager;
118import android.content.BroadcastReceiver;
119import android.content.ComponentName;
120import android.content.ContentResolver;
121import android.content.Context;
122import android.content.IIntentReceiver;
123import android.content.Intent;
124import android.content.IntentFilter;
125import android.content.IntentSender;
126import android.content.IntentSender.SendIntentException;
127import android.content.ServiceConnection;
128import android.content.pm.ActivityInfo;
129import android.content.pm.ApplicationInfo;
130import android.content.pm.AppsQueryHelper;
131import android.content.pm.AuxiliaryResolveInfo;
132import android.content.pm.ChangedPackages;
133import android.content.pm.FallbackCategoryProvider;
134import android.content.pm.FeatureInfo;
135import android.content.pm.IDexModuleRegisterCallback;
136import android.content.pm.IOnPermissionsChangeListener;
137import android.content.pm.IPackageDataObserver;
138import android.content.pm.IPackageDeleteObserver;
139import android.content.pm.IPackageDeleteObserver2;
140import android.content.pm.IPackageInstallObserver2;
141import android.content.pm.IPackageInstaller;
142import android.content.pm.IPackageManager;
143import android.content.pm.IPackageMoveObserver;
144import android.content.pm.IPackageStatsObserver;
145import android.content.pm.InstantAppInfo;
146import android.content.pm.InstantAppRequest;
147import android.content.pm.InstantAppResolveInfo;
148import android.content.pm.InstrumentationInfo;
149import android.content.pm.IntentFilterVerificationInfo;
150import android.content.pm.KeySet;
151import android.content.pm.PackageCleanItem;
152import android.content.pm.PackageInfo;
153import android.content.pm.PackageInfoLite;
154import android.content.pm.PackageInstaller;
155import android.content.pm.PackageManager;
156import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
157import android.content.pm.PackageManagerInternal;
158import android.content.pm.PackageParser;
159import android.content.pm.PackageParser.ActivityIntentInfo;
160import android.content.pm.PackageParser.PackageLite;
161import android.content.pm.PackageParser.PackageParserException;
162import android.content.pm.PackageStats;
163import android.content.pm.PackageUserState;
164import android.content.pm.ParceledListSlice;
165import android.content.pm.PermissionGroupInfo;
166import android.content.pm.PermissionInfo;
167import android.content.pm.ProviderInfo;
168import android.content.pm.ResolveInfo;
169import android.content.pm.ServiceInfo;
170import android.content.pm.SharedLibraryInfo;
171import android.content.pm.Signature;
172import android.content.pm.UserInfo;
173import android.content.pm.VerifierDeviceIdentity;
174import android.content.pm.VerifierInfo;
175import android.content.pm.VersionedPackage;
176import android.content.res.Resources;
177import android.database.ContentObserver;
178import android.graphics.Bitmap;
179import android.hardware.display.DisplayManager;
180import android.net.Uri;
181import android.os.Binder;
182import android.os.Build;
183import android.os.Bundle;
184import android.os.Debug;
185import android.os.Environment;
186import android.os.Environment.UserEnvironment;
187import android.os.FileUtils;
188import android.os.Handler;
189import android.os.IBinder;
190import android.os.Looper;
191import android.os.Message;
192import android.os.Parcel;
193import android.os.ParcelFileDescriptor;
194import android.os.PatternMatcher;
195import android.os.Process;
196import android.os.RemoteCallbackList;
197import android.os.RemoteException;
198import android.os.ResultReceiver;
199import android.os.SELinux;
200import android.os.ServiceManager;
201import android.os.ShellCallback;
202import android.os.SystemClock;
203import android.os.SystemProperties;
204import android.os.Trace;
205import android.os.UserHandle;
206import android.os.UserManager;
207import android.os.UserManagerInternal;
208import android.os.storage.IStorageManager;
209import android.os.storage.StorageEventListener;
210import android.os.storage.StorageManager;
211import android.os.storage.StorageManagerInternal;
212import android.os.storage.VolumeInfo;
213import android.os.storage.VolumeRecord;
214import android.provider.Settings.Global;
215import android.provider.Settings.Secure;
216import android.security.KeyStore;
217import android.security.SystemKeyStore;
218import android.service.pm.PackageServiceDumpProto;
219import android.system.ErrnoException;
220import android.system.Os;
221import android.text.TextUtils;
222import android.text.format.DateUtils;
223import android.util.ArrayMap;
224import android.util.ArraySet;
225import android.util.Base64;
226import android.util.BootTimingsTraceLog;
227import android.util.DisplayMetrics;
228import android.util.EventLog;
229import android.util.ExceptionUtils;
230import android.util.Log;
231import android.util.LogPrinter;
232import android.util.MathUtils;
233import android.util.PackageUtils;
234import android.util.Pair;
235import android.util.PrintStreamPrinter;
236import android.util.Slog;
237import android.util.SparseArray;
238import android.util.SparseBooleanArray;
239import android.util.SparseIntArray;
240import android.util.Xml;
241import android.util.jar.StrictJarFile;
242import android.util.proto.ProtoOutputStream;
243import android.view.Display;
244
245import com.android.internal.R;
246import com.android.internal.annotations.GuardedBy;
247import com.android.internal.app.IMediaContainerService;
248import com.android.internal.app.ResolverActivity;
249import com.android.internal.content.NativeLibraryHelper;
250import com.android.internal.content.PackageHelper;
251import com.android.internal.logging.MetricsLogger;
252import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
253import com.android.internal.os.IParcelFileDescriptorFactory;
254import com.android.internal.os.RoSystemProperties;
255import com.android.internal.os.SomeArgs;
256import com.android.internal.os.Zygote;
257import com.android.internal.telephony.CarrierAppUtils;
258import com.android.internal.util.ArrayUtils;
259import com.android.internal.util.ConcurrentUtils;
260import com.android.internal.util.DumpUtils;
261import com.android.internal.util.FastPrintWriter;
262import com.android.internal.util.FastXmlSerializer;
263import com.android.internal.util.IndentingPrintWriter;
264import com.android.internal.util.Preconditions;
265import com.android.internal.util.XmlUtils;
266import com.android.server.AttributeCache;
267import com.android.server.DeviceIdleController;
268import com.android.server.EventLogTags;
269import com.android.server.FgThread;
270import com.android.server.IntentResolver;
271import com.android.server.LocalServices;
272import com.android.server.LockGuard;
273import com.android.server.ServiceThread;
274import com.android.server.SystemConfig;
275import com.android.server.SystemServerInitThreadPool;
276import com.android.server.Watchdog;
277import com.android.server.net.NetworkPolicyManagerInternal;
278import com.android.server.pm.Installer.InstallerException;
279import com.android.server.pm.PermissionsState.PermissionState;
280import com.android.server.pm.Settings.DatabaseVersion;
281import com.android.server.pm.Settings.VersionInfo;
282import com.android.server.pm.dex.DexManager;
283import com.android.server.pm.dex.DexoptOptions;
284import com.android.server.pm.dex.PackageDexUsage;
285import com.android.server.storage.DeviceStorageMonitorInternal;
286
287import dalvik.system.CloseGuard;
288import dalvik.system.DexFile;
289import dalvik.system.VMRuntime;
290
291import libcore.io.IoUtils;
292import libcore.util.EmptyArray;
293
294import org.xmlpull.v1.XmlPullParser;
295import org.xmlpull.v1.XmlPullParserException;
296import org.xmlpull.v1.XmlSerializer;
297
298import java.io.BufferedOutputStream;
299import java.io.BufferedReader;
300import java.io.ByteArrayInputStream;
301import java.io.ByteArrayOutputStream;
302import java.io.File;
303import java.io.FileDescriptor;
304import java.io.FileInputStream;
305import java.io.FileOutputStream;
306import java.io.FileReader;
307import java.io.FilenameFilter;
308import java.io.IOException;
309import java.io.PrintWriter;
310import java.lang.annotation.Retention;
311import java.lang.annotation.RetentionPolicy;
312import java.nio.charset.StandardCharsets;
313import java.security.DigestInputStream;
314import java.security.MessageDigest;
315import java.security.NoSuchAlgorithmException;
316import java.security.PublicKey;
317import java.security.SecureRandom;
318import java.security.cert.Certificate;
319import java.security.cert.CertificateEncodingException;
320import java.security.cert.CertificateException;
321import java.text.SimpleDateFormat;
322import java.util.ArrayList;
323import java.util.Arrays;
324import java.util.Collection;
325import java.util.Collections;
326import java.util.Comparator;
327import java.util.Date;
328import java.util.HashMap;
329import java.util.HashSet;
330import java.util.Iterator;
331import java.util.LinkedHashSet;
332import java.util.List;
333import java.util.Map;
334import java.util.Objects;
335import java.util.Set;
336import java.util.concurrent.CountDownLatch;
337import java.util.concurrent.Future;
338import java.util.concurrent.TimeUnit;
339import java.util.concurrent.atomic.AtomicBoolean;
340import java.util.concurrent.atomic.AtomicInteger;
341
342/**
343 * Keep track of all those APKs everywhere.
344 * <p>
345 * Internally there are two important locks:
346 * <ul>
347 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
348 * and other related state. It is a fine-grained lock that should only be held
349 * momentarily, as it's one of the most contended locks in the system.
350 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
351 * operations typically involve heavy lifting of application data on disk. Since
352 * {@code installd} is single-threaded, and it's operations can often be slow,
353 * this lock should never be acquired while already holding {@link #mPackages}.
354 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
355 * holding {@link #mInstallLock}.
356 * </ul>
357 * Many internal methods rely on the caller to hold the appropriate locks, and
358 * this contract is expressed through method name suffixes:
359 * <ul>
360 * <li>fooLI(): the caller must hold {@link #mInstallLock}
361 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
362 * being modified must be frozen
363 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
364 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
365 * </ul>
366 * <p>
367 * Because this class is very central to the platform's security; please run all
368 * CTS and unit tests whenever making modifications:
369 *
370 * <pre>
371 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
372 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
373 * </pre>
374 */
375public class PackageManagerService extends IPackageManager.Stub
376        implements PackageSender {
377    static final String TAG = "PackageManager";
378    static final boolean DEBUG_SETTINGS = false;
379    static final boolean DEBUG_PREFERRED = false;
380    static final boolean DEBUG_UPGRADE = false;
381    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
382    private static final boolean DEBUG_BACKUP = false;
383    private static final boolean DEBUG_INSTALL = false;
384    private static final boolean DEBUG_REMOVE = false;
385    private static final boolean DEBUG_BROADCASTS = false;
386    private static final boolean DEBUG_SHOW_INFO = false;
387    private static final boolean DEBUG_PACKAGE_INFO = false;
388    private static final boolean DEBUG_INTENT_MATCHING = false;
389    private static final boolean DEBUG_PACKAGE_SCANNING = false;
390    private static final boolean DEBUG_VERIFY = false;
391    private static final boolean DEBUG_FILTERS = false;
392    private static final boolean DEBUG_PERMISSIONS = false;
393    private static final boolean DEBUG_SHARED_LIBRARIES = false;
394
395    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
396    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
397    // user, but by default initialize to this.
398    public static final boolean DEBUG_DEXOPT = false;
399
400    private static final boolean DEBUG_ABI_SELECTION = false;
401    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
402    private static final boolean DEBUG_TRIAGED_MISSING = false;
403    private static final boolean DEBUG_APP_DATA = false;
404
405    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
406    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
407
408    private static final boolean HIDE_EPHEMERAL_APIS = false;
409
410    private static final boolean ENABLE_FREE_CACHE_V2 =
411            SystemProperties.getBoolean("fw.free_cache_v2", true);
412
413    private static final int RADIO_UID = Process.PHONE_UID;
414    private static final int LOG_UID = Process.LOG_UID;
415    private static final int NFC_UID = Process.NFC_UID;
416    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
417    private static final int SHELL_UID = Process.SHELL_UID;
418
419    // Cap the size of permission trees that 3rd party apps can define
420    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
421
422    // Suffix used during package installation when copying/moving
423    // package apks to install directory.
424    private static final String INSTALL_PACKAGE_SUFFIX = "-";
425
426    static final int SCAN_NO_DEX = 1<<1;
427    static final int SCAN_FORCE_DEX = 1<<2;
428    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
429    static final int SCAN_NEW_INSTALL = 1<<4;
430    static final int SCAN_UPDATE_TIME = 1<<5;
431    static final int SCAN_BOOTING = 1<<6;
432    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
433    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
434    static final int SCAN_REPLACING = 1<<9;
435    static final int SCAN_REQUIRE_KNOWN = 1<<10;
436    static final int SCAN_MOVE = 1<<11;
437    static final int SCAN_INITIAL = 1<<12;
438    static final int SCAN_CHECK_ONLY = 1<<13;
439    static final int SCAN_DONT_KILL_APP = 1<<14;
440    static final int SCAN_IGNORE_FROZEN = 1<<15;
441    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
442    static final int SCAN_AS_INSTANT_APP = 1<<17;
443    static final int SCAN_AS_FULL_APP = 1<<18;
444    /** Should not be with the scan flags */
445    static final int FLAGS_REMOVE_CHATTY = 1<<31;
446
447    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
448
449    private static final int[] EMPTY_INT_ARRAY = new int[0];
450
451    private static final int TYPE_UNKNOWN = 0;
452    private static final int TYPE_ACTIVITY = 1;
453    private static final int TYPE_RECEIVER = 2;
454    private static final int TYPE_SERVICE = 3;
455    private static final int TYPE_PROVIDER = 4;
456    @IntDef(prefix = { "TYPE_" }, value = {
457            TYPE_UNKNOWN,
458            TYPE_ACTIVITY,
459            TYPE_RECEIVER,
460            TYPE_SERVICE,
461            TYPE_PROVIDER,
462    })
463    @Retention(RetentionPolicy.SOURCE)
464    public @interface ComponentType {}
465
466    /**
467     * Timeout (in milliseconds) after which the watchdog should declare that
468     * our handler thread is wedged.  The usual default for such things is one
469     * minute but we sometimes do very lengthy I/O operations on this thread,
470     * such as installing multi-gigabyte applications, so ours needs to be longer.
471     */
472    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
473
474    /**
475     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
476     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
477     * settings entry if available, otherwise we use the hardcoded default.  If it's been
478     * more than this long since the last fstrim, we force one during the boot sequence.
479     *
480     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
481     * one gets run at the next available charging+idle time.  This final mandatory
482     * no-fstrim check kicks in only of the other scheduling criteria is never met.
483     */
484    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
485
486    /**
487     * Whether verification is enabled by default.
488     */
489    private static final boolean DEFAULT_VERIFY_ENABLE = true;
490
491    /**
492     * The default maximum time to wait for the verification agent to return in
493     * milliseconds.
494     */
495    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
496
497    /**
498     * The default response for package verification timeout.
499     *
500     * This can be either PackageManager.VERIFICATION_ALLOW or
501     * PackageManager.VERIFICATION_REJECT.
502     */
503    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
504
505    static final String PLATFORM_PACKAGE_NAME = "android";
506
507    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
508
509    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
510            DEFAULT_CONTAINER_PACKAGE,
511            "com.android.defcontainer.DefaultContainerService");
512
513    private static final String KILL_APP_REASON_GIDS_CHANGED =
514            "permission grant or revoke changed gids";
515
516    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
517            "permissions revoked";
518
519    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
520
521    private static final String PACKAGE_SCHEME = "package";
522
523    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
524
525    /** Permission grant: not grant the permission. */
526    private static final int GRANT_DENIED = 1;
527
528    /** Permission grant: grant the permission as an install permission. */
529    private static final int GRANT_INSTALL = 2;
530
531    /** Permission grant: grant the permission as a runtime one. */
532    private static final int GRANT_RUNTIME = 3;
533
534    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
535    private static final int GRANT_UPGRADE = 4;
536
537    /** Canonical intent used to identify what counts as a "web browser" app */
538    private static final Intent sBrowserIntent;
539    static {
540        sBrowserIntent = new Intent();
541        sBrowserIntent.setAction(Intent.ACTION_VIEW);
542        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
543        sBrowserIntent.setData(Uri.parse("http:"));
544    }
545
546    /**
547     * The set of all protected actions [i.e. those actions for which a high priority
548     * intent filter is disallowed].
549     */
550    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
551    static {
552        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
553        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
554        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
555        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
556    }
557
558    // Compilation reasons.
559    public static final int REASON_FIRST_BOOT = 0;
560    public static final int REASON_BOOT = 1;
561    public static final int REASON_INSTALL = 2;
562    public static final int REASON_BACKGROUND_DEXOPT = 3;
563    public static final int REASON_AB_OTA = 4;
564    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
565
566    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
567
568    /** All dangerous permission names in the same order as the events in MetricsEvent */
569    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
570            Manifest.permission.READ_CALENDAR,
571            Manifest.permission.WRITE_CALENDAR,
572            Manifest.permission.CAMERA,
573            Manifest.permission.READ_CONTACTS,
574            Manifest.permission.WRITE_CONTACTS,
575            Manifest.permission.GET_ACCOUNTS,
576            Manifest.permission.ACCESS_FINE_LOCATION,
577            Manifest.permission.ACCESS_COARSE_LOCATION,
578            Manifest.permission.RECORD_AUDIO,
579            Manifest.permission.READ_PHONE_STATE,
580            Manifest.permission.CALL_PHONE,
581            Manifest.permission.READ_CALL_LOG,
582            Manifest.permission.WRITE_CALL_LOG,
583            Manifest.permission.ADD_VOICEMAIL,
584            Manifest.permission.USE_SIP,
585            Manifest.permission.PROCESS_OUTGOING_CALLS,
586            Manifest.permission.READ_CELL_BROADCASTS,
587            Manifest.permission.BODY_SENSORS,
588            Manifest.permission.SEND_SMS,
589            Manifest.permission.RECEIVE_SMS,
590            Manifest.permission.READ_SMS,
591            Manifest.permission.RECEIVE_WAP_PUSH,
592            Manifest.permission.RECEIVE_MMS,
593            Manifest.permission.READ_EXTERNAL_STORAGE,
594            Manifest.permission.WRITE_EXTERNAL_STORAGE,
595            Manifest.permission.READ_PHONE_NUMBERS,
596            Manifest.permission.ANSWER_PHONE_CALLS);
597
598
599    /**
600     * Version number for the package parser cache. Increment this whenever the format or
601     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
602     */
603    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
604
605    /**
606     * Whether the package parser cache is enabled.
607     */
608    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
609
610    final ServiceThread mHandlerThread;
611
612    final PackageHandler mHandler;
613
614    private final ProcessLoggingHandler mProcessLoggingHandler;
615
616    /**
617     * Messages for {@link #mHandler} that need to wait for system ready before
618     * being dispatched.
619     */
620    private ArrayList<Message> mPostSystemReadyMessages;
621
622    final int mSdkVersion = Build.VERSION.SDK_INT;
623
624    final Context mContext;
625    final boolean mFactoryTest;
626    final boolean mOnlyCore;
627    final DisplayMetrics mMetrics;
628    final int mDefParseFlags;
629    final String[] mSeparateProcesses;
630    final boolean mIsUpgrade;
631    final boolean mIsPreNUpgrade;
632    final boolean mIsPreNMR1Upgrade;
633
634    // Have we told the Activity Manager to whitelist the default container service by uid yet?
635    @GuardedBy("mPackages")
636    boolean mDefaultContainerWhitelisted = false;
637
638    @GuardedBy("mPackages")
639    private boolean mDexOptDialogShown;
640
641    /** The location for ASEC container files on internal storage. */
642    final String mAsecInternalPath;
643
644    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
645    // LOCK HELD.  Can be called with mInstallLock held.
646    @GuardedBy("mInstallLock")
647    final Installer mInstaller;
648
649    /** Directory where installed third-party apps stored */
650    final File mAppInstallDir;
651
652    /**
653     * Directory to which applications installed internally have their
654     * 32 bit native libraries copied.
655     */
656    private File mAppLib32InstallDir;
657
658    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
659    // apps.
660    final File mDrmAppPrivateInstallDir;
661
662    // ----------------------------------------------------------------
663
664    // Lock for state used when installing and doing other long running
665    // operations.  Methods that must be called with this lock held have
666    // the suffix "LI".
667    final Object mInstallLock = new Object();
668
669    // ----------------------------------------------------------------
670
671    // Keys are String (package name), values are Package.  This also serves
672    // as the lock for the global state.  Methods that must be called with
673    // this lock held have the prefix "LP".
674    @GuardedBy("mPackages")
675    final ArrayMap<String, PackageParser.Package> mPackages =
676            new ArrayMap<String, PackageParser.Package>();
677
678    final ArrayMap<String, Set<String>> mKnownCodebase =
679            new ArrayMap<String, Set<String>>();
680
681    // Keys are isolated uids and values are the uid of the application
682    // that created the isolated proccess.
683    @GuardedBy("mPackages")
684    final SparseIntArray mIsolatedOwners = new SparseIntArray();
685
686    /**
687     * Tracks new system packages [received in an OTA] that we expect to
688     * find updated user-installed versions. Keys are package name, values
689     * are package location.
690     */
691    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
692    /**
693     * Tracks high priority intent filters for protected actions. During boot, certain
694     * filter actions are protected and should never be allowed to have a high priority
695     * intent filter for them. However, there is one, and only one exception -- the
696     * setup wizard. It must be able to define a high priority intent filter for these
697     * actions to ensure there are no escapes from the wizard. We need to delay processing
698     * of these during boot as we need to look at all of the system packages in order
699     * to know which component is the setup wizard.
700     */
701    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
702    /**
703     * Whether or not processing protected filters should be deferred.
704     */
705    private boolean mDeferProtectedFilters = true;
706
707    /**
708     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
709     */
710    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
711    /**
712     * Whether or not system app permissions should be promoted from install to runtime.
713     */
714    boolean mPromoteSystemApps;
715
716    @GuardedBy("mPackages")
717    final Settings mSettings;
718
719    /**
720     * Set of package names that are currently "frozen", which means active
721     * surgery is being done on the code/data for that package. The platform
722     * will refuse to launch frozen packages to avoid race conditions.
723     *
724     * @see PackageFreezer
725     */
726    @GuardedBy("mPackages")
727    final ArraySet<String> mFrozenPackages = new ArraySet<>();
728
729    final ProtectedPackages mProtectedPackages;
730
731    boolean mFirstBoot;
732
733    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
734
735    // System configuration read by SystemConfig.
736    final int[] mGlobalGids;
737    final SparseArray<ArraySet<String>> mSystemPermissions;
738    @GuardedBy("mAvailableFeatures")
739    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
740
741    // If mac_permissions.xml was found for seinfo labeling.
742    boolean mFoundPolicyFile;
743
744    private final InstantAppRegistry mInstantAppRegistry;
745
746    @GuardedBy("mPackages")
747    int mChangedPackagesSequenceNumber;
748    /**
749     * List of changed [installed, removed or updated] packages.
750     * mapping from user id -> sequence number -> package name
751     */
752    @GuardedBy("mPackages")
753    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
754    /**
755     * The sequence number of the last change to a package.
756     * mapping from user id -> package name -> sequence number
757     */
758    @GuardedBy("mPackages")
759    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
760
761    class PackageParserCallback implements PackageParser.Callback {
762        @Override public final boolean hasFeature(String feature) {
763            return PackageManagerService.this.hasSystemFeature(feature, 0);
764        }
765
766        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
767                Collection<PackageParser.Package> allPackages, String targetPackageName) {
768            List<PackageParser.Package> overlayPackages = null;
769            for (PackageParser.Package p : allPackages) {
770                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
771                    if (overlayPackages == null) {
772                        overlayPackages = new ArrayList<PackageParser.Package>();
773                    }
774                    overlayPackages.add(p);
775                }
776            }
777            if (overlayPackages != null) {
778                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
779                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
780                        return p1.mOverlayPriority - p2.mOverlayPriority;
781                    }
782                };
783                Collections.sort(overlayPackages, cmp);
784            }
785            return overlayPackages;
786        }
787
788        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
789                String targetPackageName, String targetPath) {
790            if ("android".equals(targetPackageName)) {
791                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
792                // native AssetManager.
793                return null;
794            }
795            List<PackageParser.Package> overlayPackages =
796                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
797            if (overlayPackages == null || overlayPackages.isEmpty()) {
798                return null;
799            }
800            List<String> overlayPathList = null;
801            for (PackageParser.Package overlayPackage : overlayPackages) {
802                if (targetPath == null) {
803                    if (overlayPathList == null) {
804                        overlayPathList = new ArrayList<String>();
805                    }
806                    overlayPathList.add(overlayPackage.baseCodePath);
807                    continue;
808                }
809
810                try {
811                    // Creates idmaps for system to parse correctly the Android manifest of the
812                    // target package.
813                    //
814                    // OverlayManagerService will update each of them with a correct gid from its
815                    // target package app id.
816                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
817                            UserHandle.getSharedAppGid(
818                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
819                    if (overlayPathList == null) {
820                        overlayPathList = new ArrayList<String>();
821                    }
822                    overlayPathList.add(overlayPackage.baseCodePath);
823                } catch (InstallerException e) {
824                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
825                            overlayPackage.baseCodePath);
826                }
827            }
828            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
829        }
830
831        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
832            synchronized (mPackages) {
833                return getStaticOverlayPathsLocked(
834                        mPackages.values(), targetPackageName, targetPath);
835            }
836        }
837
838        @Override public final String[] getOverlayApks(String targetPackageName) {
839            return getStaticOverlayPaths(targetPackageName, null);
840        }
841
842        @Override public final String[] getOverlayPaths(String targetPackageName,
843                String targetPath) {
844            return getStaticOverlayPaths(targetPackageName, targetPath);
845        }
846    };
847
848    class ParallelPackageParserCallback extends PackageParserCallback {
849        List<PackageParser.Package> mOverlayPackages = null;
850
851        void findStaticOverlayPackages() {
852            synchronized (mPackages) {
853                for (PackageParser.Package p : mPackages.values()) {
854                    if (p.mIsStaticOverlay) {
855                        if (mOverlayPackages == null) {
856                            mOverlayPackages = new ArrayList<PackageParser.Package>();
857                        }
858                        mOverlayPackages.add(p);
859                    }
860                }
861            }
862        }
863
864        @Override
865        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
866            // We can trust mOverlayPackages without holding mPackages because package uninstall
867            // can't happen while running parallel parsing.
868            // Moreover holding mPackages on each parsing thread causes dead-lock.
869            return mOverlayPackages == null ? null :
870                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
871        }
872    }
873
874    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
875    final ParallelPackageParserCallback mParallelPackageParserCallback =
876            new ParallelPackageParserCallback();
877
878    public static final class SharedLibraryEntry {
879        public final @Nullable String path;
880        public final @Nullable String apk;
881        public final @NonNull SharedLibraryInfo info;
882
883        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
884                String declaringPackageName, int declaringPackageVersionCode) {
885            path = _path;
886            apk = _apk;
887            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
888                    declaringPackageName, declaringPackageVersionCode), null);
889        }
890    }
891
892    // Currently known shared libraries.
893    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
894    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
895            new ArrayMap<>();
896
897    // All available activities, for your resolving pleasure.
898    final ActivityIntentResolver mActivities =
899            new ActivityIntentResolver();
900
901    // All available receivers, for your resolving pleasure.
902    final ActivityIntentResolver mReceivers =
903            new ActivityIntentResolver();
904
905    // All available services, for your resolving pleasure.
906    final ServiceIntentResolver mServices = new ServiceIntentResolver();
907
908    // All available providers, for your resolving pleasure.
909    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
910
911    // Mapping from provider base names (first directory in content URI codePath)
912    // to the provider information.
913    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
914            new ArrayMap<String, PackageParser.Provider>();
915
916    // Mapping from instrumentation class names to info about them.
917    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
918            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
919
920    // Mapping from permission names to info about them.
921    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
922            new ArrayMap<String, PackageParser.PermissionGroup>();
923
924    // Packages whose data we have transfered into another package, thus
925    // should no longer exist.
926    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
927
928    // Broadcast actions that are only available to the system.
929    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
930
931    /** List of packages waiting for verification. */
932    final SparseArray<PackageVerificationState> mPendingVerification
933            = new SparseArray<PackageVerificationState>();
934
935    /** Set of packages associated with each app op permission. */
936    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
937
938    final PackageInstallerService mInstallerService;
939
940    private final PackageDexOptimizer mPackageDexOptimizer;
941    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
942    // is used by other apps).
943    private final DexManager mDexManager;
944
945    private AtomicInteger mNextMoveId = new AtomicInteger();
946    private final MoveCallbacks mMoveCallbacks;
947
948    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
949
950    // Cache of users who need badging.
951    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
952
953    /** Token for keys in mPendingVerification. */
954    private int mPendingVerificationToken = 0;
955
956    volatile boolean mSystemReady;
957    volatile boolean mSafeMode;
958    volatile boolean mHasSystemUidErrors;
959    private volatile boolean mEphemeralAppsDisabled;
960
961    ApplicationInfo mAndroidApplication;
962    final ActivityInfo mResolveActivity = new ActivityInfo();
963    final ResolveInfo mResolveInfo = new ResolveInfo();
964    ComponentName mResolveComponentName;
965    PackageParser.Package mPlatformPackage;
966    ComponentName mCustomResolverComponentName;
967
968    boolean mResolverReplaced = false;
969
970    private final @Nullable ComponentName mIntentFilterVerifierComponent;
971    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
972
973    private int mIntentFilterVerificationToken = 0;
974
975    /** The service connection to the ephemeral resolver */
976    final EphemeralResolverConnection mInstantAppResolverConnection;
977    /** Component used to show resolver settings for Instant Apps */
978    final ComponentName mInstantAppResolverSettingsComponent;
979
980    /** Activity used to install instant applications */
981    ActivityInfo mInstantAppInstallerActivity;
982    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
983
984    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
985            = new SparseArray<IntentFilterVerificationState>();
986
987    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
988
989    // List of packages names to keep cached, even if they are uninstalled for all users
990    private List<String> mKeepUninstalledPackages;
991
992    private UserManagerInternal mUserManagerInternal;
993
994    private DeviceIdleController.LocalService mDeviceIdleController;
995
996    private File mCacheDir;
997
998    private ArraySet<String> mPrivappPermissionsViolations;
999
1000    private Future<?> mPrepareAppDataFuture;
1001
1002    private static class IFVerificationParams {
1003        PackageParser.Package pkg;
1004        boolean replacing;
1005        int userId;
1006        int verifierUid;
1007
1008        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1009                int _userId, int _verifierUid) {
1010            pkg = _pkg;
1011            replacing = _replacing;
1012            userId = _userId;
1013            replacing = _replacing;
1014            verifierUid = _verifierUid;
1015        }
1016    }
1017
1018    private interface IntentFilterVerifier<T extends IntentFilter> {
1019        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1020                                               T filter, String packageName);
1021        void startVerifications(int userId);
1022        void receiveVerificationResponse(int verificationId);
1023    }
1024
1025    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1026        private Context mContext;
1027        private ComponentName mIntentFilterVerifierComponent;
1028        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1029
1030        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1031            mContext = context;
1032            mIntentFilterVerifierComponent = verifierComponent;
1033        }
1034
1035        private String getDefaultScheme() {
1036            return IntentFilter.SCHEME_HTTPS;
1037        }
1038
1039        @Override
1040        public void startVerifications(int userId) {
1041            // Launch verifications requests
1042            int count = mCurrentIntentFilterVerifications.size();
1043            for (int n=0; n<count; n++) {
1044                int verificationId = mCurrentIntentFilterVerifications.get(n);
1045                final IntentFilterVerificationState ivs =
1046                        mIntentFilterVerificationStates.get(verificationId);
1047
1048                String packageName = ivs.getPackageName();
1049
1050                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1051                final int filterCount = filters.size();
1052                ArraySet<String> domainsSet = new ArraySet<>();
1053                for (int m=0; m<filterCount; m++) {
1054                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1055                    domainsSet.addAll(filter.getHostsList());
1056                }
1057                synchronized (mPackages) {
1058                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1059                            packageName, domainsSet) != null) {
1060                        scheduleWriteSettingsLocked();
1061                    }
1062                }
1063                sendVerificationRequest(userId, verificationId, ivs);
1064            }
1065            mCurrentIntentFilterVerifications.clear();
1066        }
1067
1068        private void sendVerificationRequest(int userId, int verificationId,
1069                IntentFilterVerificationState ivs) {
1070
1071            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1072            verificationIntent.putExtra(
1073                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1074                    verificationId);
1075            verificationIntent.putExtra(
1076                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1077                    getDefaultScheme());
1078            verificationIntent.putExtra(
1079                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1080                    ivs.getHostsString());
1081            verificationIntent.putExtra(
1082                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1083                    ivs.getPackageName());
1084            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1085            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1086
1087            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1088            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1089                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1090                    userId, false, "intent filter verifier");
1091
1092            UserHandle user = new UserHandle(userId);
1093            mContext.sendBroadcastAsUser(verificationIntent, user);
1094            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1095                    "Sending IntentFilter verification broadcast");
1096        }
1097
1098        public void receiveVerificationResponse(int verificationId) {
1099            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1100
1101            final boolean verified = ivs.isVerified();
1102
1103            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1104            final int count = filters.size();
1105            if (DEBUG_DOMAIN_VERIFICATION) {
1106                Slog.i(TAG, "Received verification response " + verificationId
1107                        + " for " + count + " filters, verified=" + verified);
1108            }
1109            for (int n=0; n<count; n++) {
1110                PackageParser.ActivityIntentInfo filter = filters.get(n);
1111                filter.setVerified(verified);
1112
1113                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1114                        + " verified with result:" + verified + " and hosts:"
1115                        + ivs.getHostsString());
1116            }
1117
1118            mIntentFilterVerificationStates.remove(verificationId);
1119
1120            final String packageName = ivs.getPackageName();
1121            IntentFilterVerificationInfo ivi = null;
1122
1123            synchronized (mPackages) {
1124                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1125            }
1126            if (ivi == null) {
1127                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1128                        + verificationId + " packageName:" + packageName);
1129                return;
1130            }
1131            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1132                    "Updating IntentFilterVerificationInfo for package " + packageName
1133                            +" verificationId:" + verificationId);
1134
1135            synchronized (mPackages) {
1136                if (verified) {
1137                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1138                } else {
1139                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1140                }
1141                scheduleWriteSettingsLocked();
1142
1143                final int userId = ivs.getUserId();
1144                if (userId != UserHandle.USER_ALL) {
1145                    final int userStatus =
1146                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1147
1148                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1149                    boolean needUpdate = false;
1150
1151                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1152                    // already been set by the User thru the Disambiguation dialog
1153                    switch (userStatus) {
1154                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1155                            if (verified) {
1156                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1157                            } else {
1158                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1159                            }
1160                            needUpdate = true;
1161                            break;
1162
1163                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1164                            if (verified) {
1165                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1166                                needUpdate = true;
1167                            }
1168                            break;
1169
1170                        default:
1171                            // Nothing to do
1172                    }
1173
1174                    if (needUpdate) {
1175                        mSettings.updateIntentFilterVerificationStatusLPw(
1176                                packageName, updatedStatus, userId);
1177                        scheduleWritePackageRestrictionsLocked(userId);
1178                    }
1179                }
1180            }
1181        }
1182
1183        @Override
1184        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1185                    ActivityIntentInfo filter, String packageName) {
1186            if (!hasValidDomains(filter)) {
1187                return false;
1188            }
1189            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1190            if (ivs == null) {
1191                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1192                        packageName);
1193            }
1194            if (DEBUG_DOMAIN_VERIFICATION) {
1195                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1196            }
1197            ivs.addFilter(filter);
1198            return true;
1199        }
1200
1201        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1202                int userId, int verificationId, String packageName) {
1203            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1204                    verifierUid, userId, packageName);
1205            ivs.setPendingState();
1206            synchronized (mPackages) {
1207                mIntentFilterVerificationStates.append(verificationId, ivs);
1208                mCurrentIntentFilterVerifications.add(verificationId);
1209            }
1210            return ivs;
1211        }
1212    }
1213
1214    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1215        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1216                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1217                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1218    }
1219
1220    // Set of pending broadcasts for aggregating enable/disable of components.
1221    static class PendingPackageBroadcasts {
1222        // for each user id, a map of <package name -> components within that package>
1223        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1224
1225        public PendingPackageBroadcasts() {
1226            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1227        }
1228
1229        public ArrayList<String> get(int userId, String packageName) {
1230            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1231            return packages.get(packageName);
1232        }
1233
1234        public void put(int userId, String packageName, ArrayList<String> components) {
1235            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1236            packages.put(packageName, components);
1237        }
1238
1239        public void remove(int userId, String packageName) {
1240            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1241            if (packages != null) {
1242                packages.remove(packageName);
1243            }
1244        }
1245
1246        public void remove(int userId) {
1247            mUidMap.remove(userId);
1248        }
1249
1250        public int userIdCount() {
1251            return mUidMap.size();
1252        }
1253
1254        public int userIdAt(int n) {
1255            return mUidMap.keyAt(n);
1256        }
1257
1258        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1259            return mUidMap.get(userId);
1260        }
1261
1262        public int size() {
1263            // total number of pending broadcast entries across all userIds
1264            int num = 0;
1265            for (int i = 0; i< mUidMap.size(); i++) {
1266                num += mUidMap.valueAt(i).size();
1267            }
1268            return num;
1269        }
1270
1271        public void clear() {
1272            mUidMap.clear();
1273        }
1274
1275        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1276            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1277            if (map == null) {
1278                map = new ArrayMap<String, ArrayList<String>>();
1279                mUidMap.put(userId, map);
1280            }
1281            return map;
1282        }
1283    }
1284    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1285
1286    // Service Connection to remote media container service to copy
1287    // package uri's from external media onto secure containers
1288    // or internal storage.
1289    private IMediaContainerService mContainerService = null;
1290
1291    static final int SEND_PENDING_BROADCAST = 1;
1292    static final int MCS_BOUND = 3;
1293    static final int END_COPY = 4;
1294    static final int INIT_COPY = 5;
1295    static final int MCS_UNBIND = 6;
1296    static final int START_CLEANING_PACKAGE = 7;
1297    static final int FIND_INSTALL_LOC = 8;
1298    static final int POST_INSTALL = 9;
1299    static final int MCS_RECONNECT = 10;
1300    static final int MCS_GIVE_UP = 11;
1301    static final int UPDATED_MEDIA_STATUS = 12;
1302    static final int WRITE_SETTINGS = 13;
1303    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1304    static final int PACKAGE_VERIFIED = 15;
1305    static final int CHECK_PENDING_VERIFICATION = 16;
1306    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1307    static final int INTENT_FILTER_VERIFIED = 18;
1308    static final int WRITE_PACKAGE_LIST = 19;
1309    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1310
1311    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1312
1313    // Delay time in millisecs
1314    static final int BROADCAST_DELAY = 10 * 1000;
1315
1316    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1317            2 * 60 * 60 * 1000L; /* two hours */
1318
1319    static UserManagerService sUserManager;
1320
1321    // Stores a list of users whose package restrictions file needs to be updated
1322    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1323
1324    final private DefaultContainerConnection mDefContainerConn =
1325            new DefaultContainerConnection();
1326    class DefaultContainerConnection implements ServiceConnection {
1327        public void onServiceConnected(ComponentName name, IBinder service) {
1328            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1329            final IMediaContainerService imcs = IMediaContainerService.Stub
1330                    .asInterface(Binder.allowBlocking(service));
1331            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1332        }
1333
1334        public void onServiceDisconnected(ComponentName name) {
1335            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1336        }
1337    }
1338
1339    // Recordkeeping of restore-after-install operations that are currently in flight
1340    // between the Package Manager and the Backup Manager
1341    static class PostInstallData {
1342        public InstallArgs args;
1343        public PackageInstalledInfo res;
1344
1345        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1346            args = _a;
1347            res = _r;
1348        }
1349    }
1350
1351    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1352    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1353
1354    // XML tags for backup/restore of various bits of state
1355    private static final String TAG_PREFERRED_BACKUP = "pa";
1356    private static final String TAG_DEFAULT_APPS = "da";
1357    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1358
1359    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1360    private static final String TAG_ALL_GRANTS = "rt-grants";
1361    private static final String TAG_GRANT = "grant";
1362    private static final String ATTR_PACKAGE_NAME = "pkg";
1363
1364    private static final String TAG_PERMISSION = "perm";
1365    private static final String ATTR_PERMISSION_NAME = "name";
1366    private static final String ATTR_IS_GRANTED = "g";
1367    private static final String ATTR_USER_SET = "set";
1368    private static final String ATTR_USER_FIXED = "fixed";
1369    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1370
1371    // System/policy permission grants are not backed up
1372    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1373            FLAG_PERMISSION_POLICY_FIXED
1374            | FLAG_PERMISSION_SYSTEM_FIXED
1375            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1376
1377    // And we back up these user-adjusted states
1378    private static final int USER_RUNTIME_GRANT_MASK =
1379            FLAG_PERMISSION_USER_SET
1380            | FLAG_PERMISSION_USER_FIXED
1381            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1382
1383    final @Nullable String mRequiredVerifierPackage;
1384    final @NonNull String mRequiredInstallerPackage;
1385    final @NonNull String mRequiredUninstallerPackage;
1386    final @Nullable String mSetupWizardPackage;
1387    final @Nullable String mStorageManagerPackage;
1388    final @NonNull String mServicesSystemSharedLibraryPackageName;
1389    final @NonNull String mSharedSystemSharedLibraryPackageName;
1390
1391    final boolean mPermissionReviewRequired;
1392
1393    private final PackageUsage mPackageUsage = new PackageUsage();
1394    private final CompilerStats mCompilerStats = new CompilerStats();
1395
1396    class PackageHandler extends Handler {
1397        private boolean mBound = false;
1398        final ArrayList<HandlerParams> mPendingInstalls =
1399            new ArrayList<HandlerParams>();
1400
1401        private boolean connectToService() {
1402            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1403                    " DefaultContainerService");
1404            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1405            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1406            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1407                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1408                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1409                mBound = true;
1410                return true;
1411            }
1412            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1413            return false;
1414        }
1415
1416        private void disconnectService() {
1417            mContainerService = null;
1418            mBound = false;
1419            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1420            mContext.unbindService(mDefContainerConn);
1421            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1422        }
1423
1424        PackageHandler(Looper looper) {
1425            super(looper);
1426        }
1427
1428        public void handleMessage(Message msg) {
1429            try {
1430                doHandleMessage(msg);
1431            } finally {
1432                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1433            }
1434        }
1435
1436        void doHandleMessage(Message msg) {
1437            switch (msg.what) {
1438                case INIT_COPY: {
1439                    HandlerParams params = (HandlerParams) msg.obj;
1440                    int idx = mPendingInstalls.size();
1441                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1442                    // If a bind was already initiated we dont really
1443                    // need to do anything. The pending install
1444                    // will be processed later on.
1445                    if (!mBound) {
1446                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1447                                System.identityHashCode(mHandler));
1448                        // If this is the only one pending we might
1449                        // have to bind to the service again.
1450                        if (!connectToService()) {
1451                            Slog.e(TAG, "Failed to bind to media container service");
1452                            params.serviceError();
1453                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1454                                    System.identityHashCode(mHandler));
1455                            if (params.traceMethod != null) {
1456                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1457                                        params.traceCookie);
1458                            }
1459                            return;
1460                        } else {
1461                            // Once we bind to the service, the first
1462                            // pending request will be processed.
1463                            mPendingInstalls.add(idx, params);
1464                        }
1465                    } else {
1466                        mPendingInstalls.add(idx, params);
1467                        // Already bound to the service. Just make
1468                        // sure we trigger off processing the first request.
1469                        if (idx == 0) {
1470                            mHandler.sendEmptyMessage(MCS_BOUND);
1471                        }
1472                    }
1473                    break;
1474                }
1475                case MCS_BOUND: {
1476                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1477                    if (msg.obj != null) {
1478                        mContainerService = (IMediaContainerService) msg.obj;
1479                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1480                                System.identityHashCode(mHandler));
1481                    }
1482                    if (mContainerService == null) {
1483                        if (!mBound) {
1484                            // Something seriously wrong since we are not bound and we are not
1485                            // waiting for connection. Bail out.
1486                            Slog.e(TAG, "Cannot bind to media container service");
1487                            for (HandlerParams params : mPendingInstalls) {
1488                                // Indicate service bind error
1489                                params.serviceError();
1490                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1491                                        System.identityHashCode(params));
1492                                if (params.traceMethod != null) {
1493                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1494                                            params.traceMethod, params.traceCookie);
1495                                }
1496                                return;
1497                            }
1498                            mPendingInstalls.clear();
1499                        } else {
1500                            Slog.w(TAG, "Waiting to connect to media container service");
1501                        }
1502                    } else if (mPendingInstalls.size() > 0) {
1503                        HandlerParams params = mPendingInstalls.get(0);
1504                        if (params != null) {
1505                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1506                                    System.identityHashCode(params));
1507                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1508                            if (params.startCopy()) {
1509                                // We are done...  look for more work or to
1510                                // go idle.
1511                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1512                                        "Checking for more work or unbind...");
1513                                // Delete pending install
1514                                if (mPendingInstalls.size() > 0) {
1515                                    mPendingInstalls.remove(0);
1516                                }
1517                                if (mPendingInstalls.size() == 0) {
1518                                    if (mBound) {
1519                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1520                                                "Posting delayed MCS_UNBIND");
1521                                        removeMessages(MCS_UNBIND);
1522                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1523                                        // Unbind after a little delay, to avoid
1524                                        // continual thrashing.
1525                                        sendMessageDelayed(ubmsg, 10000);
1526                                    }
1527                                } else {
1528                                    // There are more pending requests in queue.
1529                                    // Just post MCS_BOUND message to trigger processing
1530                                    // of next pending install.
1531                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1532                                            "Posting MCS_BOUND for next work");
1533                                    mHandler.sendEmptyMessage(MCS_BOUND);
1534                                }
1535                            }
1536                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1537                        }
1538                    } else {
1539                        // Should never happen ideally.
1540                        Slog.w(TAG, "Empty queue");
1541                    }
1542                    break;
1543                }
1544                case MCS_RECONNECT: {
1545                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1546                    if (mPendingInstalls.size() > 0) {
1547                        if (mBound) {
1548                            disconnectService();
1549                        }
1550                        if (!connectToService()) {
1551                            Slog.e(TAG, "Failed to bind to media container service");
1552                            for (HandlerParams params : mPendingInstalls) {
1553                                // Indicate service bind error
1554                                params.serviceError();
1555                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1556                                        System.identityHashCode(params));
1557                            }
1558                            mPendingInstalls.clear();
1559                        }
1560                    }
1561                    break;
1562                }
1563                case MCS_UNBIND: {
1564                    // If there is no actual work left, then time to unbind.
1565                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1566
1567                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1568                        if (mBound) {
1569                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1570
1571                            disconnectService();
1572                        }
1573                    } else if (mPendingInstalls.size() > 0) {
1574                        // There are more pending requests in queue.
1575                        // Just post MCS_BOUND message to trigger processing
1576                        // of next pending install.
1577                        mHandler.sendEmptyMessage(MCS_BOUND);
1578                    }
1579
1580                    break;
1581                }
1582                case MCS_GIVE_UP: {
1583                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1584                    HandlerParams params = mPendingInstalls.remove(0);
1585                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1586                            System.identityHashCode(params));
1587                    break;
1588                }
1589                case SEND_PENDING_BROADCAST: {
1590                    String packages[];
1591                    ArrayList<String> components[];
1592                    int size = 0;
1593                    int uids[];
1594                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1595                    synchronized (mPackages) {
1596                        if (mPendingBroadcasts == null) {
1597                            return;
1598                        }
1599                        size = mPendingBroadcasts.size();
1600                        if (size <= 0) {
1601                            // Nothing to be done. Just return
1602                            return;
1603                        }
1604                        packages = new String[size];
1605                        components = new ArrayList[size];
1606                        uids = new int[size];
1607                        int i = 0;  // filling out the above arrays
1608
1609                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1610                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1611                            Iterator<Map.Entry<String, ArrayList<String>>> it
1612                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1613                                            .entrySet().iterator();
1614                            while (it.hasNext() && i < size) {
1615                                Map.Entry<String, ArrayList<String>> ent = it.next();
1616                                packages[i] = ent.getKey();
1617                                components[i] = ent.getValue();
1618                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1619                                uids[i] = (ps != null)
1620                                        ? UserHandle.getUid(packageUserId, ps.appId)
1621                                        : -1;
1622                                i++;
1623                            }
1624                        }
1625                        size = i;
1626                        mPendingBroadcasts.clear();
1627                    }
1628                    // Send broadcasts
1629                    for (int i = 0; i < size; i++) {
1630                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1631                    }
1632                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1633                    break;
1634                }
1635                case START_CLEANING_PACKAGE: {
1636                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1637                    final String packageName = (String)msg.obj;
1638                    final int userId = msg.arg1;
1639                    final boolean andCode = msg.arg2 != 0;
1640                    synchronized (mPackages) {
1641                        if (userId == UserHandle.USER_ALL) {
1642                            int[] users = sUserManager.getUserIds();
1643                            for (int user : users) {
1644                                mSettings.addPackageToCleanLPw(
1645                                        new PackageCleanItem(user, packageName, andCode));
1646                            }
1647                        } else {
1648                            mSettings.addPackageToCleanLPw(
1649                                    new PackageCleanItem(userId, packageName, andCode));
1650                        }
1651                    }
1652                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1653                    startCleaningPackages();
1654                } break;
1655                case POST_INSTALL: {
1656                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1657
1658                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1659                    final boolean didRestore = (msg.arg2 != 0);
1660                    mRunningInstalls.delete(msg.arg1);
1661
1662                    if (data != null) {
1663                        InstallArgs args = data.args;
1664                        PackageInstalledInfo parentRes = data.res;
1665
1666                        final boolean grantPermissions = (args.installFlags
1667                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1668                        final boolean killApp = (args.installFlags
1669                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1670                        final String[] grantedPermissions = args.installGrantPermissions;
1671
1672                        // Handle the parent package
1673                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1674                                grantedPermissions, didRestore, args.installerPackageName,
1675                                args.observer);
1676
1677                        // Handle the child packages
1678                        final int childCount = (parentRes.addedChildPackages != null)
1679                                ? parentRes.addedChildPackages.size() : 0;
1680                        for (int i = 0; i < childCount; i++) {
1681                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1682                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1683                                    grantedPermissions, false, args.installerPackageName,
1684                                    args.observer);
1685                        }
1686
1687                        // Log tracing if needed
1688                        if (args.traceMethod != null) {
1689                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1690                                    args.traceCookie);
1691                        }
1692                    } else {
1693                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1694                    }
1695
1696                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1697                } break;
1698                case UPDATED_MEDIA_STATUS: {
1699                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1700                    boolean reportStatus = msg.arg1 == 1;
1701                    boolean doGc = msg.arg2 == 1;
1702                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1703                    if (doGc) {
1704                        // Force a gc to clear up stale containers.
1705                        Runtime.getRuntime().gc();
1706                    }
1707                    if (msg.obj != null) {
1708                        @SuppressWarnings("unchecked")
1709                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1710                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1711                        // Unload containers
1712                        unloadAllContainers(args);
1713                    }
1714                    if (reportStatus) {
1715                        try {
1716                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1717                                    "Invoking StorageManagerService call back");
1718                            PackageHelper.getStorageManager().finishMediaUpdate();
1719                        } catch (RemoteException e) {
1720                            Log.e(TAG, "StorageManagerService not running?");
1721                        }
1722                    }
1723                } break;
1724                case WRITE_SETTINGS: {
1725                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1726                    synchronized (mPackages) {
1727                        removeMessages(WRITE_SETTINGS);
1728                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1729                        mSettings.writeLPr();
1730                        mDirtyUsers.clear();
1731                    }
1732                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1733                } break;
1734                case WRITE_PACKAGE_RESTRICTIONS: {
1735                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1736                    synchronized (mPackages) {
1737                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1738                        for (int userId : mDirtyUsers) {
1739                            mSettings.writePackageRestrictionsLPr(userId);
1740                        }
1741                        mDirtyUsers.clear();
1742                    }
1743                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1744                } break;
1745                case WRITE_PACKAGE_LIST: {
1746                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1747                    synchronized (mPackages) {
1748                        removeMessages(WRITE_PACKAGE_LIST);
1749                        mSettings.writePackageListLPr(msg.arg1);
1750                    }
1751                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1752                } break;
1753                case CHECK_PENDING_VERIFICATION: {
1754                    final int verificationId = msg.arg1;
1755                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1756
1757                    if ((state != null) && !state.timeoutExtended()) {
1758                        final InstallArgs args = state.getInstallArgs();
1759                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1760
1761                        Slog.i(TAG, "Verification timed out for " + originUri);
1762                        mPendingVerification.remove(verificationId);
1763
1764                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1765
1766                        final UserHandle user = args.getUser();
1767                        if (getDefaultVerificationResponse(user)
1768                                == PackageManager.VERIFICATION_ALLOW) {
1769                            Slog.i(TAG, "Continuing with installation of " + originUri);
1770                            state.setVerifierResponse(Binder.getCallingUid(),
1771                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1772                            broadcastPackageVerified(verificationId, originUri,
1773                                    PackageManager.VERIFICATION_ALLOW, user);
1774                            try {
1775                                ret = args.copyApk(mContainerService, true);
1776                            } catch (RemoteException e) {
1777                                Slog.e(TAG, "Could not contact the ContainerService");
1778                            }
1779                        } else {
1780                            broadcastPackageVerified(verificationId, originUri,
1781                                    PackageManager.VERIFICATION_REJECT, user);
1782                        }
1783
1784                        Trace.asyncTraceEnd(
1785                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1786
1787                        processPendingInstall(args, ret);
1788                        mHandler.sendEmptyMessage(MCS_UNBIND);
1789                    }
1790                    break;
1791                }
1792                case PACKAGE_VERIFIED: {
1793                    final int verificationId = msg.arg1;
1794
1795                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1796                    if (state == null) {
1797                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1798                        break;
1799                    }
1800
1801                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1802
1803                    state.setVerifierResponse(response.callerUid, response.code);
1804
1805                    if (state.isVerificationComplete()) {
1806                        mPendingVerification.remove(verificationId);
1807
1808                        final InstallArgs args = state.getInstallArgs();
1809                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1810
1811                        int ret;
1812                        if (state.isInstallAllowed()) {
1813                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1814                            broadcastPackageVerified(verificationId, originUri,
1815                                    response.code, state.getInstallArgs().getUser());
1816                            try {
1817                                ret = args.copyApk(mContainerService, true);
1818                            } catch (RemoteException e) {
1819                                Slog.e(TAG, "Could not contact the ContainerService");
1820                            }
1821                        } else {
1822                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1823                        }
1824
1825                        Trace.asyncTraceEnd(
1826                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1827
1828                        processPendingInstall(args, ret);
1829                        mHandler.sendEmptyMessage(MCS_UNBIND);
1830                    }
1831
1832                    break;
1833                }
1834                case START_INTENT_FILTER_VERIFICATIONS: {
1835                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1836                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1837                            params.replacing, params.pkg);
1838                    break;
1839                }
1840                case INTENT_FILTER_VERIFIED: {
1841                    final int verificationId = msg.arg1;
1842
1843                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1844                            verificationId);
1845                    if (state == null) {
1846                        Slog.w(TAG, "Invalid IntentFilter verification token "
1847                                + verificationId + " received");
1848                        break;
1849                    }
1850
1851                    final int userId = state.getUserId();
1852
1853                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1854                            "Processing IntentFilter verification with token:"
1855                            + verificationId + " and userId:" + userId);
1856
1857                    final IntentFilterVerificationResponse response =
1858                            (IntentFilterVerificationResponse) msg.obj;
1859
1860                    state.setVerifierResponse(response.callerUid, response.code);
1861
1862                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1863                            "IntentFilter verification with token:" + verificationId
1864                            + " and userId:" + userId
1865                            + " is settings verifier response with response code:"
1866                            + response.code);
1867
1868                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1869                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1870                                + response.getFailedDomainsString());
1871                    }
1872
1873                    if (state.isVerificationComplete()) {
1874                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1875                    } else {
1876                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1877                                "IntentFilter verification with token:" + verificationId
1878                                + " was not said to be complete");
1879                    }
1880
1881                    break;
1882                }
1883                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1884                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1885                            mInstantAppResolverConnection,
1886                            (InstantAppRequest) msg.obj,
1887                            mInstantAppInstallerActivity,
1888                            mHandler);
1889                }
1890            }
1891        }
1892    }
1893
1894    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1895            boolean killApp, String[] grantedPermissions,
1896            boolean launchedForRestore, String installerPackage,
1897            IPackageInstallObserver2 installObserver) {
1898        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1899            // Send the removed broadcasts
1900            if (res.removedInfo != null) {
1901                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1902            }
1903
1904            // Now that we successfully installed the package, grant runtime
1905            // permissions if requested before broadcasting the install. Also
1906            // for legacy apps in permission review mode we clear the permission
1907            // review flag which is used to emulate runtime permissions for
1908            // legacy apps.
1909            if (grantPermissions) {
1910                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1911            }
1912
1913            final boolean update = res.removedInfo != null
1914                    && res.removedInfo.removedPackage != null;
1915            final String origInstallerPackageName = res.removedInfo != null
1916                    ? res.removedInfo.installerPackageName : null;
1917
1918            // If this is the first time we have child packages for a disabled privileged
1919            // app that had no children, we grant requested runtime permissions to the new
1920            // children if the parent on the system image had them already granted.
1921            if (res.pkg.parentPackage != null) {
1922                synchronized (mPackages) {
1923                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1924                }
1925            }
1926
1927            synchronized (mPackages) {
1928                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1929            }
1930
1931            final String packageName = res.pkg.applicationInfo.packageName;
1932
1933            // Determine the set of users who are adding this package for
1934            // the first time vs. those who are seeing an update.
1935            int[] firstUsers = EMPTY_INT_ARRAY;
1936            int[] updateUsers = EMPTY_INT_ARRAY;
1937            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1938            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1939            for (int newUser : res.newUsers) {
1940                if (ps.getInstantApp(newUser)) {
1941                    continue;
1942                }
1943                if (allNewUsers) {
1944                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1945                    continue;
1946                }
1947                boolean isNew = true;
1948                for (int origUser : res.origUsers) {
1949                    if (origUser == newUser) {
1950                        isNew = false;
1951                        break;
1952                    }
1953                }
1954                if (isNew) {
1955                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1956                } else {
1957                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1958                }
1959            }
1960
1961            // Send installed broadcasts if the package is not a static shared lib.
1962            if (res.pkg.staticSharedLibName == null) {
1963                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1964
1965                // Send added for users that see the package for the first time
1966                // sendPackageAddedForNewUsers also deals with system apps
1967                int appId = UserHandle.getAppId(res.uid);
1968                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1969                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1970
1971                // Send added for users that don't see the package for the first time
1972                Bundle extras = new Bundle(1);
1973                extras.putInt(Intent.EXTRA_UID, res.uid);
1974                if (update) {
1975                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1976                }
1977                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1978                        extras, 0 /*flags*/,
1979                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1980                if (origInstallerPackageName != null) {
1981                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1982                            extras, 0 /*flags*/,
1983                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1984                }
1985
1986                // Send replaced for users that don't see the package for the first time
1987                if (update) {
1988                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1989                            packageName, extras, 0 /*flags*/,
1990                            null /*targetPackage*/, null /*finishedReceiver*/,
1991                            updateUsers);
1992                    if (origInstallerPackageName != null) {
1993                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1994                                extras, 0 /*flags*/,
1995                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1996                    }
1997                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1998                            null /*package*/, null /*extras*/, 0 /*flags*/,
1999                            packageName /*targetPackage*/,
2000                            null /*finishedReceiver*/, updateUsers);
2001                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2002                    // First-install and we did a restore, so we're responsible for the
2003                    // first-launch broadcast.
2004                    if (DEBUG_BACKUP) {
2005                        Slog.i(TAG, "Post-restore of " + packageName
2006                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2007                    }
2008                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2009                }
2010
2011                // Send broadcast package appeared if forward locked/external for all users
2012                // treat asec-hosted packages like removable media on upgrade
2013                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2014                    if (DEBUG_INSTALL) {
2015                        Slog.i(TAG, "upgrading pkg " + res.pkg
2016                                + " is ASEC-hosted -> AVAILABLE");
2017                    }
2018                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2019                    ArrayList<String> pkgList = new ArrayList<>(1);
2020                    pkgList.add(packageName);
2021                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2022                }
2023            }
2024
2025            // Work that needs to happen on first install within each user
2026            if (firstUsers != null && firstUsers.length > 0) {
2027                synchronized (mPackages) {
2028                    for (int userId : firstUsers) {
2029                        // If this app is a browser and it's newly-installed for some
2030                        // users, clear any default-browser state in those users. The
2031                        // app's nature doesn't depend on the user, so we can just check
2032                        // its browser nature in any user and generalize.
2033                        if (packageIsBrowser(packageName, userId)) {
2034                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2035                        }
2036
2037                        // We may also need to apply pending (restored) runtime
2038                        // permission grants within these users.
2039                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2040                    }
2041                }
2042            }
2043
2044            // Log current value of "unknown sources" setting
2045            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2046                    getUnknownSourcesSettings());
2047
2048            // Remove the replaced package's older resources safely now
2049            // We delete after a gc for applications  on sdcard.
2050            if (res.removedInfo != null && res.removedInfo.args != null) {
2051                Runtime.getRuntime().gc();
2052                synchronized (mInstallLock) {
2053                    res.removedInfo.args.doPostDeleteLI(true);
2054                }
2055            } else {
2056                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2057                // and not block here.
2058                VMRuntime.getRuntime().requestConcurrentGC();
2059            }
2060
2061            // Notify DexManager that the package was installed for new users.
2062            // The updated users should already be indexed and the package code paths
2063            // should not change.
2064            // Don't notify the manager for ephemeral apps as they are not expected to
2065            // survive long enough to benefit of background optimizations.
2066            for (int userId : firstUsers) {
2067                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2068                // There's a race currently where some install events may interleave with an uninstall.
2069                // This can lead to package info being null (b/36642664).
2070                if (info != null) {
2071                    mDexManager.notifyPackageInstalled(info, userId);
2072                }
2073            }
2074        }
2075
2076        // If someone is watching installs - notify them
2077        if (installObserver != null) {
2078            try {
2079                Bundle extras = extrasForInstallResult(res);
2080                installObserver.onPackageInstalled(res.name, res.returnCode,
2081                        res.returnMsg, extras);
2082            } catch (RemoteException e) {
2083                Slog.i(TAG, "Observer no longer exists.");
2084            }
2085        }
2086    }
2087
2088    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2089            PackageParser.Package pkg) {
2090        if (pkg.parentPackage == null) {
2091            return;
2092        }
2093        if (pkg.requestedPermissions == null) {
2094            return;
2095        }
2096        final PackageSetting disabledSysParentPs = mSettings
2097                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2098        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2099                || !disabledSysParentPs.isPrivileged()
2100                || (disabledSysParentPs.childPackageNames != null
2101                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2102            return;
2103        }
2104        final int[] allUserIds = sUserManager.getUserIds();
2105        final int permCount = pkg.requestedPermissions.size();
2106        for (int i = 0; i < permCount; i++) {
2107            String permission = pkg.requestedPermissions.get(i);
2108            BasePermission bp = mSettings.mPermissions.get(permission);
2109            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2110                continue;
2111            }
2112            for (int userId : allUserIds) {
2113                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2114                        permission, userId)) {
2115                    grantRuntimePermission(pkg.packageName, permission, userId);
2116                }
2117            }
2118        }
2119    }
2120
2121    private StorageEventListener mStorageListener = new StorageEventListener() {
2122        @Override
2123        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2124            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2125                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2126                    final String volumeUuid = vol.getFsUuid();
2127
2128                    // Clean up any users or apps that were removed or recreated
2129                    // while this volume was missing
2130                    sUserManager.reconcileUsers(volumeUuid);
2131                    reconcileApps(volumeUuid);
2132
2133                    // Clean up any install sessions that expired or were
2134                    // cancelled while this volume was missing
2135                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2136
2137                    loadPrivatePackages(vol);
2138
2139                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2140                    unloadPrivatePackages(vol);
2141                }
2142            }
2143
2144            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2145                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2146                    updateExternalMediaStatus(true, false);
2147                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2148                    updateExternalMediaStatus(false, false);
2149                }
2150            }
2151        }
2152
2153        @Override
2154        public void onVolumeForgotten(String fsUuid) {
2155            if (TextUtils.isEmpty(fsUuid)) {
2156                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2157                return;
2158            }
2159
2160            // Remove any apps installed on the forgotten volume
2161            synchronized (mPackages) {
2162                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2163                for (PackageSetting ps : packages) {
2164                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2165                    deletePackageVersioned(new VersionedPackage(ps.name,
2166                            PackageManager.VERSION_CODE_HIGHEST),
2167                            new LegacyPackageDeleteObserver(null).getBinder(),
2168                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2169                    // Try very hard to release any references to this package
2170                    // so we don't risk the system server being killed due to
2171                    // open FDs
2172                    AttributeCache.instance().removePackage(ps.name);
2173                }
2174
2175                mSettings.onVolumeForgotten(fsUuid);
2176                mSettings.writeLPr();
2177            }
2178        }
2179    };
2180
2181    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2182            String[] grantedPermissions) {
2183        for (int userId : userIds) {
2184            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2185        }
2186    }
2187
2188    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2189            String[] grantedPermissions) {
2190        PackageSetting ps = (PackageSetting) pkg.mExtras;
2191        if (ps == null) {
2192            return;
2193        }
2194
2195        PermissionsState permissionsState = ps.getPermissionsState();
2196
2197        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2198                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2199
2200        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2201                >= Build.VERSION_CODES.M;
2202
2203        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2204
2205        for (String permission : pkg.requestedPermissions) {
2206            final BasePermission bp;
2207            synchronized (mPackages) {
2208                bp = mSettings.mPermissions.get(permission);
2209            }
2210            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2211                    && (!instantApp || bp.isInstant())
2212                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2213                    && (grantedPermissions == null
2214                           || ArrayUtils.contains(grantedPermissions, permission))) {
2215                final int flags = permissionsState.getPermissionFlags(permission, userId);
2216                if (supportsRuntimePermissions) {
2217                    // Installer cannot change immutable permissions.
2218                    if ((flags & immutableFlags) == 0) {
2219                        grantRuntimePermission(pkg.packageName, permission, userId);
2220                    }
2221                } else if (mPermissionReviewRequired) {
2222                    // In permission review mode we clear the review flag when we
2223                    // are asked to install the app with all permissions granted.
2224                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2225                        updatePermissionFlags(permission, pkg.packageName,
2226                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2227                    }
2228                }
2229            }
2230        }
2231    }
2232
2233    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2234        Bundle extras = null;
2235        switch (res.returnCode) {
2236            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2237                extras = new Bundle();
2238                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2239                        res.origPermission);
2240                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2241                        res.origPackage);
2242                break;
2243            }
2244            case PackageManager.INSTALL_SUCCEEDED: {
2245                extras = new Bundle();
2246                extras.putBoolean(Intent.EXTRA_REPLACING,
2247                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2248                break;
2249            }
2250        }
2251        return extras;
2252    }
2253
2254    void scheduleWriteSettingsLocked() {
2255        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2256            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2257        }
2258    }
2259
2260    void scheduleWritePackageListLocked(int userId) {
2261        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2262            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2263            msg.arg1 = userId;
2264            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2265        }
2266    }
2267
2268    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2269        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2270        scheduleWritePackageRestrictionsLocked(userId);
2271    }
2272
2273    void scheduleWritePackageRestrictionsLocked(int userId) {
2274        final int[] userIds = (userId == UserHandle.USER_ALL)
2275                ? sUserManager.getUserIds() : new int[]{userId};
2276        for (int nextUserId : userIds) {
2277            if (!sUserManager.exists(nextUserId)) return;
2278            mDirtyUsers.add(nextUserId);
2279            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2280                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2281            }
2282        }
2283    }
2284
2285    public static PackageManagerService main(Context context, Installer installer,
2286            boolean factoryTest, boolean onlyCore) {
2287        // Self-check for initial settings.
2288        PackageManagerServiceCompilerMapping.checkProperties();
2289
2290        PackageManagerService m = new PackageManagerService(context, installer,
2291                factoryTest, onlyCore);
2292        m.enableSystemUserPackages();
2293        ServiceManager.addService("package", m);
2294        return m;
2295    }
2296
2297    private void enableSystemUserPackages() {
2298        if (!UserManager.isSplitSystemUser()) {
2299            return;
2300        }
2301        // For system user, enable apps based on the following conditions:
2302        // - app is whitelisted or belong to one of these groups:
2303        //   -- system app which has no launcher icons
2304        //   -- system app which has INTERACT_ACROSS_USERS permission
2305        //   -- system IME app
2306        // - app is not in the blacklist
2307        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2308        Set<String> enableApps = new ArraySet<>();
2309        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2310                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2311                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2312        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2313        enableApps.addAll(wlApps);
2314        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2315                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2316        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2317        enableApps.removeAll(blApps);
2318        Log.i(TAG, "Applications installed for system user: " + enableApps);
2319        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2320                UserHandle.SYSTEM);
2321        final int allAppsSize = allAps.size();
2322        synchronized (mPackages) {
2323            for (int i = 0; i < allAppsSize; i++) {
2324                String pName = allAps.get(i);
2325                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2326                // Should not happen, but we shouldn't be failing if it does
2327                if (pkgSetting == null) {
2328                    continue;
2329                }
2330                boolean install = enableApps.contains(pName);
2331                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2332                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2333                            + " for system user");
2334                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2335                }
2336            }
2337            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2338        }
2339    }
2340
2341    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2342        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2343                Context.DISPLAY_SERVICE);
2344        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2345    }
2346
2347    /**
2348     * Requests that files preopted on a secondary system partition be copied to the data partition
2349     * if possible.  Note that the actual copying of the files is accomplished by init for security
2350     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2351     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2352     */
2353    private static void requestCopyPreoptedFiles() {
2354        final int WAIT_TIME_MS = 100;
2355        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2356        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2357            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2358            // We will wait for up to 100 seconds.
2359            final long timeStart = SystemClock.uptimeMillis();
2360            final long timeEnd = timeStart + 100 * 1000;
2361            long timeNow = timeStart;
2362            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2363                try {
2364                    Thread.sleep(WAIT_TIME_MS);
2365                } catch (InterruptedException e) {
2366                    // Do nothing
2367                }
2368                timeNow = SystemClock.uptimeMillis();
2369                if (timeNow > timeEnd) {
2370                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2371                    Slog.wtf(TAG, "cppreopt did not finish!");
2372                    break;
2373                }
2374            }
2375
2376            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2377        }
2378    }
2379
2380    public PackageManagerService(Context context, Installer installer,
2381            boolean factoryTest, boolean onlyCore) {
2382        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2383        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2384        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2385                SystemClock.uptimeMillis());
2386
2387        if (mSdkVersion <= 0) {
2388            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2389        }
2390
2391        mContext = context;
2392
2393        mPermissionReviewRequired = context.getResources().getBoolean(
2394                R.bool.config_permissionReviewRequired);
2395
2396        mFactoryTest = factoryTest;
2397        mOnlyCore = onlyCore;
2398        mMetrics = new DisplayMetrics();
2399        mSettings = new Settings(mPackages);
2400        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2401                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2402        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2407                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2408        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2409                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2410        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2411                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2412
2413        String separateProcesses = SystemProperties.get("debug.separate_processes");
2414        if (separateProcesses != null && separateProcesses.length() > 0) {
2415            if ("*".equals(separateProcesses)) {
2416                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2417                mSeparateProcesses = null;
2418                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2419            } else {
2420                mDefParseFlags = 0;
2421                mSeparateProcesses = separateProcesses.split(",");
2422                Slog.w(TAG, "Running with debug.separate_processes: "
2423                        + separateProcesses);
2424            }
2425        } else {
2426            mDefParseFlags = 0;
2427            mSeparateProcesses = null;
2428        }
2429
2430        mInstaller = installer;
2431        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2432                "*dexopt*");
2433        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2434        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2435
2436        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2437                FgThread.get().getLooper());
2438
2439        getDefaultDisplayMetrics(context, mMetrics);
2440
2441        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2442        SystemConfig systemConfig = SystemConfig.getInstance();
2443        mGlobalGids = systemConfig.getGlobalGids();
2444        mSystemPermissions = systemConfig.getSystemPermissions();
2445        mAvailableFeatures = systemConfig.getAvailableFeatures();
2446        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2447
2448        mProtectedPackages = new ProtectedPackages(mContext);
2449
2450        synchronized (mInstallLock) {
2451        // writer
2452        synchronized (mPackages) {
2453            mHandlerThread = new ServiceThread(TAG,
2454                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2455            mHandlerThread.start();
2456            mHandler = new PackageHandler(mHandlerThread.getLooper());
2457            mProcessLoggingHandler = new ProcessLoggingHandler();
2458            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2459
2460            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2461            mInstantAppRegistry = new InstantAppRegistry(this);
2462
2463            File dataDir = Environment.getDataDirectory();
2464            mAppInstallDir = new File(dataDir, "app");
2465            mAppLib32InstallDir = new File(dataDir, "app-lib");
2466            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2467            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2468            sUserManager = new UserManagerService(context, this,
2469                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2470
2471            // Propagate permission configuration in to package manager.
2472            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2473                    = systemConfig.getPermissions();
2474            for (int i=0; i<permConfig.size(); i++) {
2475                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2476                BasePermission bp = mSettings.mPermissions.get(perm.name);
2477                if (bp == null) {
2478                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2479                    mSettings.mPermissions.put(perm.name, bp);
2480                }
2481                if (perm.gids != null) {
2482                    bp.setGids(perm.gids, perm.perUser);
2483                }
2484            }
2485
2486            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2487            final int builtInLibCount = libConfig.size();
2488            for (int i = 0; i < builtInLibCount; i++) {
2489                String name = libConfig.keyAt(i);
2490                String path = libConfig.valueAt(i);
2491                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2492                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2493            }
2494
2495            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2496
2497            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2498            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2499            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2500
2501            // Clean up orphaned packages for which the code path doesn't exist
2502            // and they are an update to a system app - caused by bug/32321269
2503            final int packageSettingCount = mSettings.mPackages.size();
2504            for (int i = packageSettingCount - 1; i >= 0; i--) {
2505                PackageSetting ps = mSettings.mPackages.valueAt(i);
2506                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2507                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2508                    mSettings.mPackages.removeAt(i);
2509                    mSettings.enableSystemPackageLPw(ps.name);
2510                }
2511            }
2512
2513            if (mFirstBoot) {
2514                requestCopyPreoptedFiles();
2515            }
2516
2517            String customResolverActivity = Resources.getSystem().getString(
2518                    R.string.config_customResolverActivity);
2519            if (TextUtils.isEmpty(customResolverActivity)) {
2520                customResolverActivity = null;
2521            } else {
2522                mCustomResolverComponentName = ComponentName.unflattenFromString(
2523                        customResolverActivity);
2524            }
2525
2526            long startTime = SystemClock.uptimeMillis();
2527
2528            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2529                    startTime);
2530
2531            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2532            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2533
2534            if (bootClassPath == null) {
2535                Slog.w(TAG, "No BOOTCLASSPATH found!");
2536            }
2537
2538            if (systemServerClassPath == null) {
2539                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2540            }
2541
2542            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2543
2544            final VersionInfo ver = mSettings.getInternalVersion();
2545            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2546            if (mIsUpgrade) {
2547                logCriticalInfo(Log.INFO,
2548                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2549            }
2550
2551            // when upgrading from pre-M, promote system app permissions from install to runtime
2552            mPromoteSystemApps =
2553                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2554
2555            // When upgrading from pre-N, we need to handle package extraction like first boot,
2556            // as there is no profiling data available.
2557            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2558
2559            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2560
2561            // save off the names of pre-existing system packages prior to scanning; we don't
2562            // want to automatically grant runtime permissions for new system apps
2563            if (mPromoteSystemApps) {
2564                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2565                while (pkgSettingIter.hasNext()) {
2566                    PackageSetting ps = pkgSettingIter.next();
2567                    if (isSystemApp(ps)) {
2568                        mExistingSystemPackages.add(ps.name);
2569                    }
2570                }
2571            }
2572
2573            mCacheDir = preparePackageParserCache(mIsUpgrade);
2574
2575            // Set flag to monitor and not change apk file paths when
2576            // scanning install directories.
2577            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2578
2579            if (mIsUpgrade || mFirstBoot) {
2580                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2581            }
2582
2583            // Collect vendor overlay packages. (Do this before scanning any apps.)
2584            // For security and version matching reason, only consider
2585            // overlay packages if they reside in the right directory.
2586            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2587                    | PackageParser.PARSE_IS_SYSTEM
2588                    | PackageParser.PARSE_IS_SYSTEM_DIR
2589                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2590
2591            mParallelPackageParserCallback.findStaticOverlayPackages();
2592
2593            // Find base frameworks (resource packages without code).
2594            scanDirTracedLI(frameworkDir, mDefParseFlags
2595                    | PackageParser.PARSE_IS_SYSTEM
2596                    | PackageParser.PARSE_IS_SYSTEM_DIR
2597                    | PackageParser.PARSE_IS_PRIVILEGED,
2598                    scanFlags | SCAN_NO_DEX, 0);
2599
2600            // Collected privileged system packages.
2601            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2602            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2603                    | PackageParser.PARSE_IS_SYSTEM
2604                    | PackageParser.PARSE_IS_SYSTEM_DIR
2605                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2606
2607            // Collect ordinary system packages.
2608            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2609            scanDirTracedLI(systemAppDir, mDefParseFlags
2610                    | PackageParser.PARSE_IS_SYSTEM
2611                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2612
2613            // Collect all vendor packages.
2614            File vendorAppDir = new File("/vendor/app");
2615            try {
2616                vendorAppDir = vendorAppDir.getCanonicalFile();
2617            } catch (IOException e) {
2618                // failed to look up canonical path, continue with original one
2619            }
2620            scanDirTracedLI(vendorAppDir, mDefParseFlags
2621                    | PackageParser.PARSE_IS_SYSTEM
2622                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2623
2624            // Collect all OEM packages.
2625            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2626            scanDirTracedLI(oemAppDir, mDefParseFlags
2627                    | PackageParser.PARSE_IS_SYSTEM
2628                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2629
2630            // Prune any system packages that no longer exist.
2631            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2632            if (!mOnlyCore) {
2633                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2634                while (psit.hasNext()) {
2635                    PackageSetting ps = psit.next();
2636
2637                    /*
2638                     * If this is not a system app, it can't be a
2639                     * disable system app.
2640                     */
2641                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2642                        continue;
2643                    }
2644
2645                    /*
2646                     * If the package is scanned, it's not erased.
2647                     */
2648                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2649                    if (scannedPkg != null) {
2650                        /*
2651                         * If the system app is both scanned and in the
2652                         * disabled packages list, then it must have been
2653                         * added via OTA. Remove it from the currently
2654                         * scanned package so the previously user-installed
2655                         * application can be scanned.
2656                         */
2657                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2658                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2659                                    + ps.name + "; removing system app.  Last known codePath="
2660                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2661                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2662                                    + scannedPkg.mVersionCode);
2663                            removePackageLI(scannedPkg, true);
2664                            mExpectingBetter.put(ps.name, ps.codePath);
2665                        }
2666
2667                        continue;
2668                    }
2669
2670                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2671                        psit.remove();
2672                        logCriticalInfo(Log.WARN, "System package " + ps.name
2673                                + " no longer exists; it's data will be wiped");
2674                        // Actual deletion of code and data will be handled by later
2675                        // reconciliation step
2676                    } else {
2677                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2678                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2679                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2680                        }
2681                    }
2682                }
2683            }
2684
2685            //look for any incomplete package installations
2686            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2687            for (int i = 0; i < deletePkgsList.size(); i++) {
2688                // Actual deletion of code and data will be handled by later
2689                // reconciliation step
2690                final String packageName = deletePkgsList.get(i).name;
2691                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2692                synchronized (mPackages) {
2693                    mSettings.removePackageLPw(packageName);
2694                }
2695            }
2696
2697            //delete tmp files
2698            deleteTempPackageFiles();
2699
2700            // Remove any shared userIDs that have no associated packages
2701            mSettings.pruneSharedUsersLPw();
2702
2703            if (!mOnlyCore) {
2704                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2705                        SystemClock.uptimeMillis());
2706                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2707
2708                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2709                        | PackageParser.PARSE_FORWARD_LOCK,
2710                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2711
2712                /**
2713                 * Remove disable package settings for any updated system
2714                 * apps that were removed via an OTA. If they're not a
2715                 * previously-updated app, remove them completely.
2716                 * Otherwise, just revoke their system-level permissions.
2717                 */
2718                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2719                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2720                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2721
2722                    String msg;
2723                    if (deletedPkg == null) {
2724                        msg = "Updated system package " + deletedAppName
2725                                + " no longer exists; it's data will be wiped";
2726                        // Actual deletion of code and data will be handled by later
2727                        // reconciliation step
2728                    } else {
2729                        msg = "Updated system app + " + deletedAppName
2730                                + " no longer present; removing system privileges for "
2731                                + deletedAppName;
2732
2733                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2734
2735                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2736                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2737                    }
2738                    logCriticalInfo(Log.WARN, msg);
2739                }
2740
2741                /**
2742                 * Make sure all system apps that we expected to appear on
2743                 * the userdata partition actually showed up. If they never
2744                 * appeared, crawl back and revive the system version.
2745                 */
2746                for (int i = 0; i < mExpectingBetter.size(); i++) {
2747                    final String packageName = mExpectingBetter.keyAt(i);
2748                    if (!mPackages.containsKey(packageName)) {
2749                        final File scanFile = mExpectingBetter.valueAt(i);
2750
2751                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2752                                + " but never showed up; reverting to system");
2753
2754                        int reparseFlags = mDefParseFlags;
2755                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2756                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2757                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2758                                    | PackageParser.PARSE_IS_PRIVILEGED;
2759                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2760                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2761                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2762                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2763                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2764                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2765                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2766                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2767                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2768                        } else {
2769                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2770                            continue;
2771                        }
2772
2773                        mSettings.enableSystemPackageLPw(packageName);
2774
2775                        try {
2776                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2777                        } catch (PackageManagerException e) {
2778                            Slog.e(TAG, "Failed to parse original system package: "
2779                                    + e.getMessage());
2780                        }
2781                    }
2782                }
2783            }
2784            mExpectingBetter.clear();
2785
2786            // Resolve the storage manager.
2787            mStorageManagerPackage = getStorageManagerPackageName();
2788
2789            // Resolve protected action filters. Only the setup wizard is allowed to
2790            // have a high priority filter for these actions.
2791            mSetupWizardPackage = getSetupWizardPackageName();
2792            if (mProtectedFilters.size() > 0) {
2793                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2794                    Slog.i(TAG, "No setup wizard;"
2795                        + " All protected intents capped to priority 0");
2796                }
2797                for (ActivityIntentInfo filter : mProtectedFilters) {
2798                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2799                        if (DEBUG_FILTERS) {
2800                            Slog.i(TAG, "Found setup wizard;"
2801                                + " allow priority " + filter.getPriority() + ";"
2802                                + " package: " + filter.activity.info.packageName
2803                                + " activity: " + filter.activity.className
2804                                + " priority: " + filter.getPriority());
2805                        }
2806                        // skip setup wizard; allow it to keep the high priority filter
2807                        continue;
2808                    }
2809                    if (DEBUG_FILTERS) {
2810                        Slog.i(TAG, "Protected action; cap priority to 0;"
2811                                + " package: " + filter.activity.info.packageName
2812                                + " activity: " + filter.activity.className
2813                                + " origPrio: " + filter.getPriority());
2814                    }
2815                    filter.setPriority(0);
2816                }
2817            }
2818            mDeferProtectedFilters = false;
2819            mProtectedFilters.clear();
2820
2821            // Now that we know all of the shared libraries, update all clients to have
2822            // the correct library paths.
2823            updateAllSharedLibrariesLPw(null);
2824
2825            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2826                // NOTE: We ignore potential failures here during a system scan (like
2827                // the rest of the commands above) because there's precious little we
2828                // can do about it. A settings error is reported, though.
2829                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2830            }
2831
2832            // Now that we know all the packages we are keeping,
2833            // read and update their last usage times.
2834            mPackageUsage.read(mPackages);
2835            mCompilerStats.read();
2836
2837            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2838                    SystemClock.uptimeMillis());
2839            Slog.i(TAG, "Time to scan packages: "
2840                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2841                    + " seconds");
2842
2843            // If the platform SDK has changed since the last time we booted,
2844            // we need to re-grant app permission to catch any new ones that
2845            // appear.  This is really a hack, and means that apps can in some
2846            // cases get permissions that the user didn't initially explicitly
2847            // allow...  it would be nice to have some better way to handle
2848            // this situation.
2849            int updateFlags = UPDATE_PERMISSIONS_ALL;
2850            if (ver.sdkVersion != mSdkVersion) {
2851                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2852                        + mSdkVersion + "; regranting permissions for internal storage");
2853                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2854            }
2855            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2856            ver.sdkVersion = mSdkVersion;
2857
2858            // If this is the first boot or an update from pre-M, and it is a normal
2859            // boot, then we need to initialize the default preferred apps across
2860            // all defined users.
2861            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2862                for (UserInfo user : sUserManager.getUsers(true)) {
2863                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2864                    applyFactoryDefaultBrowserLPw(user.id);
2865                    primeDomainVerificationsLPw(user.id);
2866                }
2867            }
2868
2869            // Prepare storage for system user really early during boot,
2870            // since core system apps like SettingsProvider and SystemUI
2871            // can't wait for user to start
2872            final int storageFlags;
2873            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2874                storageFlags = StorageManager.FLAG_STORAGE_DE;
2875            } else {
2876                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2877            }
2878            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2879                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2880                    true /* onlyCoreApps */);
2881            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2882                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2883                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2884                traceLog.traceBegin("AppDataFixup");
2885                try {
2886                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2887                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2888                } catch (InstallerException e) {
2889                    Slog.w(TAG, "Trouble fixing GIDs", e);
2890                }
2891                traceLog.traceEnd();
2892
2893                traceLog.traceBegin("AppDataPrepare");
2894                if (deferPackages == null || deferPackages.isEmpty()) {
2895                    return;
2896                }
2897                int count = 0;
2898                for (String pkgName : deferPackages) {
2899                    PackageParser.Package pkg = null;
2900                    synchronized (mPackages) {
2901                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2902                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2903                            pkg = ps.pkg;
2904                        }
2905                    }
2906                    if (pkg != null) {
2907                        synchronized (mInstallLock) {
2908                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2909                                    true /* maybeMigrateAppData */);
2910                        }
2911                        count++;
2912                    }
2913                }
2914                traceLog.traceEnd();
2915                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2916            }, "prepareAppData");
2917
2918            // If this is first boot after an OTA, and a normal boot, then
2919            // we need to clear code cache directories.
2920            // Note that we do *not* clear the application profiles. These remain valid
2921            // across OTAs and are used to drive profile verification (post OTA) and
2922            // profile compilation (without waiting to collect a fresh set of profiles).
2923            if (mIsUpgrade && !onlyCore) {
2924                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2925                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2926                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2927                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2928                        // No apps are running this early, so no need to freeze
2929                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2930                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2931                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2932                    }
2933                }
2934                ver.fingerprint = Build.FINGERPRINT;
2935            }
2936
2937            checkDefaultBrowser();
2938
2939            // clear only after permissions and other defaults have been updated
2940            mExistingSystemPackages.clear();
2941            mPromoteSystemApps = false;
2942
2943            // All the changes are done during package scanning.
2944            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2945
2946            // can downgrade to reader
2947            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2948            mSettings.writeLPr();
2949            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2950            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2951                    SystemClock.uptimeMillis());
2952
2953            if (!mOnlyCore) {
2954                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2955                mRequiredInstallerPackage = getRequiredInstallerLPr();
2956                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2957                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2958                if (mIntentFilterVerifierComponent != null) {
2959                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2960                            mIntentFilterVerifierComponent);
2961                } else {
2962                    mIntentFilterVerifier = null;
2963                }
2964                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2965                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2966                        SharedLibraryInfo.VERSION_UNDEFINED);
2967                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2968                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2969                        SharedLibraryInfo.VERSION_UNDEFINED);
2970            } else {
2971                mRequiredVerifierPackage = null;
2972                mRequiredInstallerPackage = null;
2973                mRequiredUninstallerPackage = null;
2974                mIntentFilterVerifierComponent = null;
2975                mIntentFilterVerifier = null;
2976                mServicesSystemSharedLibraryPackageName = null;
2977                mSharedSystemSharedLibraryPackageName = null;
2978            }
2979
2980            mInstallerService = new PackageInstallerService(context, this);
2981            final Pair<ComponentName, String> instantAppResolverComponent =
2982                    getInstantAppResolverLPr();
2983            if (instantAppResolverComponent != null) {
2984                if (DEBUG_EPHEMERAL) {
2985                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2986                }
2987                mInstantAppResolverConnection = new EphemeralResolverConnection(
2988                        mContext, instantAppResolverComponent.first,
2989                        instantAppResolverComponent.second);
2990                mInstantAppResolverSettingsComponent =
2991                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2992            } else {
2993                mInstantAppResolverConnection = null;
2994                mInstantAppResolverSettingsComponent = null;
2995            }
2996            updateInstantAppInstallerLocked(null);
2997
2998            // Read and update the usage of dex files.
2999            // Do this at the end of PM init so that all the packages have their
3000            // data directory reconciled.
3001            // At this point we know the code paths of the packages, so we can validate
3002            // the disk file and build the internal cache.
3003            // The usage file is expected to be small so loading and verifying it
3004            // should take a fairly small time compare to the other activities (e.g. package
3005            // scanning).
3006            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3007            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3008            for (int userId : currentUserIds) {
3009                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3010            }
3011            mDexManager.load(userPackages);
3012        } // synchronized (mPackages)
3013        } // synchronized (mInstallLock)
3014
3015        // Now after opening every single application zip, make sure they
3016        // are all flushed.  Not really needed, but keeps things nice and
3017        // tidy.
3018        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3019        Runtime.getRuntime().gc();
3020        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3021
3022        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3023        FallbackCategoryProvider.loadFallbacks();
3024        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3025
3026        // The initial scanning above does many calls into installd while
3027        // holding the mPackages lock, but we're mostly interested in yelling
3028        // once we have a booted system.
3029        mInstaller.setWarnIfHeld(mPackages);
3030
3031        // Expose private service for system components to use.
3032        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3033        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3034    }
3035
3036    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3037        // we're only interested in updating the installer appliction when 1) it's not
3038        // already set or 2) the modified package is the installer
3039        if (mInstantAppInstallerActivity != null
3040                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3041                        .equals(modifiedPackage)) {
3042            return;
3043        }
3044        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3045    }
3046
3047    private static File preparePackageParserCache(boolean isUpgrade) {
3048        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3049            return null;
3050        }
3051
3052        // Disable package parsing on eng builds to allow for faster incremental development.
3053        if ("eng".equals(Build.TYPE)) {
3054            return null;
3055        }
3056
3057        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3058            Slog.i(TAG, "Disabling package parser cache due to system property.");
3059            return null;
3060        }
3061
3062        // The base directory for the package parser cache lives under /data/system/.
3063        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3064                "package_cache");
3065        if (cacheBaseDir == null) {
3066            return null;
3067        }
3068
3069        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3070        // This also serves to "GC" unused entries when the package cache version changes (which
3071        // can only happen during upgrades).
3072        if (isUpgrade) {
3073            FileUtils.deleteContents(cacheBaseDir);
3074        }
3075
3076
3077        // Return the versioned package cache directory. This is something like
3078        // "/data/system/package_cache/1"
3079        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3080
3081        // The following is a workaround to aid development on non-numbered userdebug
3082        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3083        // the system partition is newer.
3084        //
3085        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3086        // that starts with "eng." to signify that this is an engineering build and not
3087        // destined for release.
3088        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3089            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3090
3091            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3092            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3093            // in general and should not be used for production changes. In this specific case,
3094            // we know that they will work.
3095            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3096            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3097                FileUtils.deleteContents(cacheBaseDir);
3098                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3099            }
3100        }
3101
3102        return cacheDir;
3103    }
3104
3105    @Override
3106    public boolean isFirstBoot() {
3107        // allow instant applications
3108        return mFirstBoot;
3109    }
3110
3111    @Override
3112    public boolean isOnlyCoreApps() {
3113        // allow instant applications
3114        return mOnlyCore;
3115    }
3116
3117    @Override
3118    public boolean isUpgrade() {
3119        // allow instant applications
3120        return mIsUpgrade;
3121    }
3122
3123    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3124        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3125
3126        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3127                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3128                UserHandle.USER_SYSTEM);
3129        if (matches.size() == 1) {
3130            return matches.get(0).getComponentInfo().packageName;
3131        } else if (matches.size() == 0) {
3132            Log.e(TAG, "There should probably be a verifier, but, none were found");
3133            return null;
3134        }
3135        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3136    }
3137
3138    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3139        synchronized (mPackages) {
3140            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3141            if (libraryEntry == null) {
3142                throw new IllegalStateException("Missing required shared library:" + name);
3143            }
3144            return libraryEntry.apk;
3145        }
3146    }
3147
3148    private @NonNull String getRequiredInstallerLPr() {
3149        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3150        intent.addCategory(Intent.CATEGORY_DEFAULT);
3151        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3152
3153        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3154                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3155                UserHandle.USER_SYSTEM);
3156        if (matches.size() == 1) {
3157            ResolveInfo resolveInfo = matches.get(0);
3158            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3159                throw new RuntimeException("The installer must be a privileged app");
3160            }
3161            return matches.get(0).getComponentInfo().packageName;
3162        } else {
3163            throw new RuntimeException("There must be exactly one installer; found " + matches);
3164        }
3165    }
3166
3167    private @NonNull String getRequiredUninstallerLPr() {
3168        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3169        intent.addCategory(Intent.CATEGORY_DEFAULT);
3170        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3171
3172        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3173                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3174                UserHandle.USER_SYSTEM);
3175        if (resolveInfo == null ||
3176                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3177            throw new RuntimeException("There must be exactly one uninstaller; found "
3178                    + resolveInfo);
3179        }
3180        return resolveInfo.getComponentInfo().packageName;
3181    }
3182
3183    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3184        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3185
3186        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3187                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3188                UserHandle.USER_SYSTEM);
3189        ResolveInfo best = null;
3190        final int N = matches.size();
3191        for (int i = 0; i < N; i++) {
3192            final ResolveInfo cur = matches.get(i);
3193            final String packageName = cur.getComponentInfo().packageName;
3194            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3195                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3196                continue;
3197            }
3198
3199            if (best == null || cur.priority > best.priority) {
3200                best = cur;
3201            }
3202        }
3203
3204        if (best != null) {
3205            return best.getComponentInfo().getComponentName();
3206        }
3207        Slog.w(TAG, "Intent filter verifier not found");
3208        return null;
3209    }
3210
3211    @Override
3212    public @Nullable ComponentName getInstantAppResolverComponent() {
3213        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3214            return null;
3215        }
3216        synchronized (mPackages) {
3217            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3218            if (instantAppResolver == null) {
3219                return null;
3220            }
3221            return instantAppResolver.first;
3222        }
3223    }
3224
3225    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3226        final String[] packageArray =
3227                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3228        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3229            if (DEBUG_EPHEMERAL) {
3230                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3231            }
3232            return null;
3233        }
3234
3235        final int callingUid = Binder.getCallingUid();
3236        final int resolveFlags =
3237                MATCH_DIRECT_BOOT_AWARE
3238                | MATCH_DIRECT_BOOT_UNAWARE
3239                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3240        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3241        final Intent resolverIntent = new Intent(actionName);
3242        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3243                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3244        // temporarily look for the old action
3245        if (resolvers.size() == 0) {
3246            if (DEBUG_EPHEMERAL) {
3247                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3248            }
3249            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3250            resolverIntent.setAction(actionName);
3251            resolvers = queryIntentServicesInternal(resolverIntent, null,
3252                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3253        }
3254        final int N = resolvers.size();
3255        if (N == 0) {
3256            if (DEBUG_EPHEMERAL) {
3257                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3258            }
3259            return null;
3260        }
3261
3262        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3263        for (int i = 0; i < N; i++) {
3264            final ResolveInfo info = resolvers.get(i);
3265
3266            if (info.serviceInfo == null) {
3267                continue;
3268            }
3269
3270            final String packageName = info.serviceInfo.packageName;
3271            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3272                if (DEBUG_EPHEMERAL) {
3273                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3274                            + " pkg: " + packageName + ", info:" + info);
3275                }
3276                continue;
3277            }
3278
3279            if (DEBUG_EPHEMERAL) {
3280                Slog.v(TAG, "Ephemeral resolver found;"
3281                        + " pkg: " + packageName + ", info:" + info);
3282            }
3283            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3284        }
3285        if (DEBUG_EPHEMERAL) {
3286            Slog.v(TAG, "Ephemeral resolver NOT found");
3287        }
3288        return null;
3289    }
3290
3291    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3292        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3293        intent.addCategory(Intent.CATEGORY_DEFAULT);
3294        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3295
3296        final int resolveFlags =
3297                MATCH_DIRECT_BOOT_AWARE
3298                | MATCH_DIRECT_BOOT_UNAWARE
3299                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3300        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3301                resolveFlags, UserHandle.USER_SYSTEM);
3302        // temporarily look for the old action
3303        if (matches.isEmpty()) {
3304            if (DEBUG_EPHEMERAL) {
3305                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3306            }
3307            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3308            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3309                    resolveFlags, UserHandle.USER_SYSTEM);
3310        }
3311        Iterator<ResolveInfo> iter = matches.iterator();
3312        while (iter.hasNext()) {
3313            final ResolveInfo rInfo = iter.next();
3314            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3315            if (ps != null) {
3316                final PermissionsState permissionsState = ps.getPermissionsState();
3317                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3318                    continue;
3319                }
3320            }
3321            iter.remove();
3322        }
3323        if (matches.size() == 0) {
3324            return null;
3325        } else if (matches.size() == 1) {
3326            return (ActivityInfo) matches.get(0).getComponentInfo();
3327        } else {
3328            throw new RuntimeException(
3329                    "There must be at most one ephemeral installer; found " + matches);
3330        }
3331    }
3332
3333    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3334            @NonNull ComponentName resolver) {
3335        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3336                .addCategory(Intent.CATEGORY_DEFAULT)
3337                .setPackage(resolver.getPackageName());
3338        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3339        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3340                UserHandle.USER_SYSTEM);
3341        // temporarily look for the old action
3342        if (matches.isEmpty()) {
3343            if (DEBUG_EPHEMERAL) {
3344                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3345            }
3346            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3347            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3348                    UserHandle.USER_SYSTEM);
3349        }
3350        if (matches.isEmpty()) {
3351            return null;
3352        }
3353        return matches.get(0).getComponentInfo().getComponentName();
3354    }
3355
3356    private void primeDomainVerificationsLPw(int userId) {
3357        if (DEBUG_DOMAIN_VERIFICATION) {
3358            Slog.d(TAG, "Priming domain verifications in user " + userId);
3359        }
3360
3361        SystemConfig systemConfig = SystemConfig.getInstance();
3362        ArraySet<String> packages = systemConfig.getLinkedApps();
3363
3364        for (String packageName : packages) {
3365            PackageParser.Package pkg = mPackages.get(packageName);
3366            if (pkg != null) {
3367                if (!pkg.isSystemApp()) {
3368                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3369                    continue;
3370                }
3371
3372                ArraySet<String> domains = null;
3373                for (PackageParser.Activity a : pkg.activities) {
3374                    for (ActivityIntentInfo filter : a.intents) {
3375                        if (hasValidDomains(filter)) {
3376                            if (domains == null) {
3377                                domains = new ArraySet<String>();
3378                            }
3379                            domains.addAll(filter.getHostsList());
3380                        }
3381                    }
3382                }
3383
3384                if (domains != null && domains.size() > 0) {
3385                    if (DEBUG_DOMAIN_VERIFICATION) {
3386                        Slog.v(TAG, "      + " + packageName);
3387                    }
3388                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3389                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3390                    // and then 'always' in the per-user state actually used for intent resolution.
3391                    final IntentFilterVerificationInfo ivi;
3392                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3393                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3394                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3395                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3396                } else {
3397                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3398                            + "' does not handle web links");
3399                }
3400            } else {
3401                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3402            }
3403        }
3404
3405        scheduleWritePackageRestrictionsLocked(userId);
3406        scheduleWriteSettingsLocked();
3407    }
3408
3409    private void applyFactoryDefaultBrowserLPw(int userId) {
3410        // The default browser app's package name is stored in a string resource,
3411        // with a product-specific overlay used for vendor customization.
3412        String browserPkg = mContext.getResources().getString(
3413                com.android.internal.R.string.default_browser);
3414        if (!TextUtils.isEmpty(browserPkg)) {
3415            // non-empty string => required to be a known package
3416            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3417            if (ps == null) {
3418                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3419                browserPkg = null;
3420            } else {
3421                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3422            }
3423        }
3424
3425        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3426        // default.  If there's more than one, just leave everything alone.
3427        if (browserPkg == null) {
3428            calculateDefaultBrowserLPw(userId);
3429        }
3430    }
3431
3432    private void calculateDefaultBrowserLPw(int userId) {
3433        List<String> allBrowsers = resolveAllBrowserApps(userId);
3434        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3435        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3436    }
3437
3438    private List<String> resolveAllBrowserApps(int userId) {
3439        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3440        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3441                PackageManager.MATCH_ALL, userId);
3442
3443        final int count = list.size();
3444        List<String> result = new ArrayList<String>(count);
3445        for (int i=0; i<count; i++) {
3446            ResolveInfo info = list.get(i);
3447            if (info.activityInfo == null
3448                    || !info.handleAllWebDataURI
3449                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3450                    || result.contains(info.activityInfo.packageName)) {
3451                continue;
3452            }
3453            result.add(info.activityInfo.packageName);
3454        }
3455
3456        return result;
3457    }
3458
3459    private boolean packageIsBrowser(String packageName, int userId) {
3460        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3461                PackageManager.MATCH_ALL, userId);
3462        final int N = list.size();
3463        for (int i = 0; i < N; i++) {
3464            ResolveInfo info = list.get(i);
3465            if (packageName.equals(info.activityInfo.packageName)) {
3466                return true;
3467            }
3468        }
3469        return false;
3470    }
3471
3472    private void checkDefaultBrowser() {
3473        final int myUserId = UserHandle.myUserId();
3474        final String packageName = getDefaultBrowserPackageName(myUserId);
3475        if (packageName != null) {
3476            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3477            if (info == null) {
3478                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3479                synchronized (mPackages) {
3480                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3481                }
3482            }
3483        }
3484    }
3485
3486    @Override
3487    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3488            throws RemoteException {
3489        try {
3490            return super.onTransact(code, data, reply, flags);
3491        } catch (RuntimeException e) {
3492            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3493                Slog.wtf(TAG, "Package Manager Crash", e);
3494            }
3495            throw e;
3496        }
3497    }
3498
3499    static int[] appendInts(int[] cur, int[] add) {
3500        if (add == null) return cur;
3501        if (cur == null) return add;
3502        final int N = add.length;
3503        for (int i=0; i<N; i++) {
3504            cur = appendInt(cur, add[i]);
3505        }
3506        return cur;
3507    }
3508
3509    /**
3510     * Returns whether or not a full application can see an instant application.
3511     * <p>
3512     * Currently, there are three cases in which this can occur:
3513     * <ol>
3514     * <li>The calling application is a "special" process. The special
3515     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3516     *     and {@code 0}</li>
3517     * <li>The calling application has the permission
3518     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3519     * <li>The calling application is the default launcher on the
3520     *     system partition.</li>
3521     * </ol>
3522     */
3523    private boolean canViewInstantApps(int callingUid, int userId) {
3524        if (callingUid == Process.SYSTEM_UID
3525                || callingUid == Process.SHELL_UID
3526                || callingUid == Process.ROOT_UID) {
3527            return true;
3528        }
3529        if (mContext.checkCallingOrSelfPermission(
3530                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3531            return true;
3532        }
3533        if (mContext.checkCallingOrSelfPermission(
3534                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3535            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3536            if (homeComponent != null
3537                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3538                return true;
3539            }
3540        }
3541        return false;
3542    }
3543
3544    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3545        if (!sUserManager.exists(userId)) return null;
3546        if (ps == null) {
3547            return null;
3548        }
3549        PackageParser.Package p = ps.pkg;
3550        if (p == null) {
3551            return null;
3552        }
3553        final int callingUid = Binder.getCallingUid();
3554        // Filter out ephemeral app metadata:
3555        //   * The system/shell/root can see metadata for any app
3556        //   * An installed app can see metadata for 1) other installed apps
3557        //     and 2) ephemeral apps that have explicitly interacted with it
3558        //   * Ephemeral apps can only see their own data and exposed installed apps
3559        //   * Holding a signature permission allows seeing instant apps
3560        if (filterAppAccessLPr(ps, callingUid, userId)) {
3561            return null;
3562        }
3563
3564        final PermissionsState permissionsState = ps.getPermissionsState();
3565
3566        // Compute GIDs only if requested
3567        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3568                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3569        // Compute granted permissions only if package has requested permissions
3570        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3571                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3572        final PackageUserState state = ps.readUserState(userId);
3573
3574        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3575                && ps.isSystem()) {
3576            flags |= MATCH_ANY_USER;
3577        }
3578
3579        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3580                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3581
3582        if (packageInfo == null) {
3583            return null;
3584        }
3585
3586        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3587                resolveExternalPackageNameLPr(p);
3588
3589        return packageInfo;
3590    }
3591
3592    @Override
3593    public void checkPackageStartable(String packageName, int userId) {
3594        final int callingUid = Binder.getCallingUid();
3595        if (getInstantAppPackageName(callingUid) != null) {
3596            throw new SecurityException("Instant applications don't have access to this method");
3597        }
3598        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3599        synchronized (mPackages) {
3600            final PackageSetting ps = mSettings.mPackages.get(packageName);
3601            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3602                throw new SecurityException("Package " + packageName + " was not found!");
3603            }
3604
3605            if (!ps.getInstalled(userId)) {
3606                throw new SecurityException(
3607                        "Package " + packageName + " was not installed for user " + userId + "!");
3608            }
3609
3610            if (mSafeMode && !ps.isSystem()) {
3611                throw new SecurityException("Package " + packageName + " not a system app!");
3612            }
3613
3614            if (mFrozenPackages.contains(packageName)) {
3615                throw new SecurityException("Package " + packageName + " is currently frozen!");
3616            }
3617
3618            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3619                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3620                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3621            }
3622        }
3623    }
3624
3625    @Override
3626    public boolean isPackageAvailable(String packageName, int userId) {
3627        if (!sUserManager.exists(userId)) return false;
3628        final int callingUid = Binder.getCallingUid();
3629        enforceCrossUserPermission(callingUid, userId,
3630                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3631        synchronized (mPackages) {
3632            PackageParser.Package p = mPackages.get(packageName);
3633            if (p != null) {
3634                final PackageSetting ps = (PackageSetting) p.mExtras;
3635                if (filterAppAccessLPr(ps, callingUid, userId)) {
3636                    return false;
3637                }
3638                if (ps != null) {
3639                    final PackageUserState state = ps.readUserState(userId);
3640                    if (state != null) {
3641                        return PackageParser.isAvailable(state);
3642                    }
3643                }
3644            }
3645        }
3646        return false;
3647    }
3648
3649    @Override
3650    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3651        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3652                flags, Binder.getCallingUid(), userId);
3653    }
3654
3655    @Override
3656    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3657            int flags, int userId) {
3658        return getPackageInfoInternal(versionedPackage.getPackageName(),
3659                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3660    }
3661
3662    /**
3663     * Important: The provided filterCallingUid is used exclusively to filter out packages
3664     * that can be seen based on user state. It's typically the original caller uid prior
3665     * to clearing. Because it can only be provided by trusted code, it's value can be
3666     * trusted and will be used as-is; unlike userId which will be validated by this method.
3667     */
3668    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3669            int flags, int filterCallingUid, int userId) {
3670        if (!sUserManager.exists(userId)) return null;
3671        flags = updateFlagsForPackage(flags, userId, packageName);
3672        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3673                false /* requireFullPermission */, false /* checkShell */, "get package info");
3674
3675        // reader
3676        synchronized (mPackages) {
3677            // Normalize package name to handle renamed packages and static libs
3678            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3679
3680            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3681            if (matchFactoryOnly) {
3682                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3683                if (ps != null) {
3684                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3685                        return null;
3686                    }
3687                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3688                        return null;
3689                    }
3690                    return generatePackageInfo(ps, flags, userId);
3691                }
3692            }
3693
3694            PackageParser.Package p = mPackages.get(packageName);
3695            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3696                return null;
3697            }
3698            if (DEBUG_PACKAGE_INFO)
3699                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3700            if (p != null) {
3701                final PackageSetting ps = (PackageSetting) p.mExtras;
3702                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3703                    return null;
3704                }
3705                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3706                    return null;
3707                }
3708                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3709            }
3710            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3711                final PackageSetting ps = mSettings.mPackages.get(packageName);
3712                if (ps == null) return null;
3713                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3714                    return null;
3715                }
3716                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3717                    return null;
3718                }
3719                return generatePackageInfo(ps, flags, userId);
3720            }
3721        }
3722        return null;
3723    }
3724
3725    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3726        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3727            return true;
3728        }
3729        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3730            return true;
3731        }
3732        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3733            return true;
3734        }
3735        return false;
3736    }
3737
3738    private boolean isComponentVisibleToInstantApp(
3739            @Nullable ComponentName component, @ComponentType int type) {
3740        if (type == TYPE_ACTIVITY) {
3741            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3742            return activity != null
3743                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3744                    : false;
3745        } else if (type == TYPE_RECEIVER) {
3746            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3747            return activity != null
3748                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3749                    : false;
3750        } else if (type == TYPE_SERVICE) {
3751            final PackageParser.Service service = mServices.mServices.get(component);
3752            return service != null
3753                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3754                    : false;
3755        } else if (type == TYPE_PROVIDER) {
3756            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3757            return provider != null
3758                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3759                    : false;
3760        } else if (type == TYPE_UNKNOWN) {
3761            return isComponentVisibleToInstantApp(component);
3762        }
3763        return false;
3764    }
3765
3766    /**
3767     * Returns whether or not access to the application should be filtered.
3768     * <p>
3769     * Access may be limited based upon whether the calling or target applications
3770     * are instant applications.
3771     *
3772     * @see #canAccessInstantApps(int)
3773     */
3774    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3775            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3776        // if we're in an isolated process, get the real calling UID
3777        if (Process.isIsolated(callingUid)) {
3778            callingUid = mIsolatedOwners.get(callingUid);
3779        }
3780        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3781        final boolean callerIsInstantApp = instantAppPkgName != null;
3782        if (ps == null) {
3783            if (callerIsInstantApp) {
3784                // pretend the application exists, but, needs to be filtered
3785                return true;
3786            }
3787            return false;
3788        }
3789        // if the target and caller are the same application, don't filter
3790        if (isCallerSameApp(ps.name, callingUid)) {
3791            return false;
3792        }
3793        if (callerIsInstantApp) {
3794            // request for a specific component; if it hasn't been explicitly exposed, filter
3795            if (component != null) {
3796                return !isComponentVisibleToInstantApp(component, componentType);
3797            }
3798            // request for application; if no components have been explicitly exposed, filter
3799            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3800        }
3801        if (ps.getInstantApp(userId)) {
3802            // caller can see all components of all instant applications, don't filter
3803            if (canViewInstantApps(callingUid, userId)) {
3804                return false;
3805            }
3806            // request for a specific instant application component, filter
3807            if (component != null) {
3808                return true;
3809            }
3810            // request for an instant application; if the caller hasn't been granted access, filter
3811            return !mInstantAppRegistry.isInstantAccessGranted(
3812                    userId, UserHandle.getAppId(callingUid), ps.appId);
3813        }
3814        return false;
3815    }
3816
3817    /**
3818     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3819     */
3820    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3821        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3822    }
3823
3824    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3825            int flags) {
3826        // Callers can access only the libs they depend on, otherwise they need to explicitly
3827        // ask for the shared libraries given the caller is allowed to access all static libs.
3828        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3829            // System/shell/root get to see all static libs
3830            final int appId = UserHandle.getAppId(uid);
3831            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3832                    || appId == Process.ROOT_UID) {
3833                return false;
3834            }
3835        }
3836
3837        // No package means no static lib as it is always on internal storage
3838        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3839            return false;
3840        }
3841
3842        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3843                ps.pkg.staticSharedLibVersion);
3844        if (libEntry == null) {
3845            return false;
3846        }
3847
3848        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3849        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3850        if (uidPackageNames == null) {
3851            return true;
3852        }
3853
3854        for (String uidPackageName : uidPackageNames) {
3855            if (ps.name.equals(uidPackageName)) {
3856                return false;
3857            }
3858            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3859            if (uidPs != null) {
3860                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3861                        libEntry.info.getName());
3862                if (index < 0) {
3863                    continue;
3864                }
3865                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3866                    return false;
3867                }
3868            }
3869        }
3870        return true;
3871    }
3872
3873    @Override
3874    public String[] currentToCanonicalPackageNames(String[] names) {
3875        final int callingUid = Binder.getCallingUid();
3876        if (getInstantAppPackageName(callingUid) != null) {
3877            return names;
3878        }
3879        final String[] out = new String[names.length];
3880        // reader
3881        synchronized (mPackages) {
3882            final int callingUserId = UserHandle.getUserId(callingUid);
3883            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3884            for (int i=names.length-1; i>=0; i--) {
3885                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3886                boolean translateName = false;
3887                if (ps != null && ps.realName != null) {
3888                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3889                    translateName = !targetIsInstantApp
3890                            || canViewInstantApps
3891                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3892                                    UserHandle.getAppId(callingUid), ps.appId);
3893                }
3894                out[i] = translateName ? ps.realName : names[i];
3895            }
3896        }
3897        return out;
3898    }
3899
3900    @Override
3901    public String[] canonicalToCurrentPackageNames(String[] names) {
3902        final int callingUid = Binder.getCallingUid();
3903        if (getInstantAppPackageName(callingUid) != null) {
3904            return names;
3905        }
3906        final String[] out = new String[names.length];
3907        // reader
3908        synchronized (mPackages) {
3909            final int callingUserId = UserHandle.getUserId(callingUid);
3910            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3911            for (int i=names.length-1; i>=0; i--) {
3912                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3913                boolean translateName = false;
3914                if (cur != null) {
3915                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3916                    final boolean targetIsInstantApp =
3917                            ps != null && ps.getInstantApp(callingUserId);
3918                    translateName = !targetIsInstantApp
3919                            || canViewInstantApps
3920                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3921                                    UserHandle.getAppId(callingUid), ps.appId);
3922                }
3923                out[i] = translateName ? cur : names[i];
3924            }
3925        }
3926        return out;
3927    }
3928
3929    @Override
3930    public int getPackageUid(String packageName, int flags, int userId) {
3931        if (!sUserManager.exists(userId)) return -1;
3932        final int callingUid = Binder.getCallingUid();
3933        flags = updateFlagsForPackage(flags, userId, packageName);
3934        enforceCrossUserPermission(callingUid, userId,
3935                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3936
3937        // reader
3938        synchronized (mPackages) {
3939            final PackageParser.Package p = mPackages.get(packageName);
3940            if (p != null && p.isMatch(flags)) {
3941                PackageSetting ps = (PackageSetting) p.mExtras;
3942                if (filterAppAccessLPr(ps, callingUid, userId)) {
3943                    return -1;
3944                }
3945                return UserHandle.getUid(userId, p.applicationInfo.uid);
3946            }
3947            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3948                final PackageSetting ps = mSettings.mPackages.get(packageName);
3949                if (ps != null && ps.isMatch(flags)
3950                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3951                    return UserHandle.getUid(userId, ps.appId);
3952                }
3953            }
3954        }
3955
3956        return -1;
3957    }
3958
3959    @Override
3960    public int[] getPackageGids(String packageName, int flags, int userId) {
3961        if (!sUserManager.exists(userId)) return null;
3962        final int callingUid = Binder.getCallingUid();
3963        flags = updateFlagsForPackage(flags, userId, packageName);
3964        enforceCrossUserPermission(callingUid, userId,
3965                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3966
3967        // reader
3968        synchronized (mPackages) {
3969            final PackageParser.Package p = mPackages.get(packageName);
3970            if (p != null && p.isMatch(flags)) {
3971                PackageSetting ps = (PackageSetting) p.mExtras;
3972                if (filterAppAccessLPr(ps, callingUid, userId)) {
3973                    return null;
3974                }
3975                // TODO: Shouldn't this be checking for package installed state for userId and
3976                // return null?
3977                return ps.getPermissionsState().computeGids(userId);
3978            }
3979            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3980                final PackageSetting ps = mSettings.mPackages.get(packageName);
3981                if (ps != null && ps.isMatch(flags)
3982                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3983                    return ps.getPermissionsState().computeGids(userId);
3984                }
3985            }
3986        }
3987
3988        return null;
3989    }
3990
3991    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3992        if (bp.perm != null) {
3993            return PackageParser.generatePermissionInfo(bp.perm, flags);
3994        }
3995        PermissionInfo pi = new PermissionInfo();
3996        pi.name = bp.name;
3997        pi.packageName = bp.sourcePackage;
3998        pi.nonLocalizedLabel = bp.name;
3999        pi.protectionLevel = bp.protectionLevel;
4000        return pi;
4001    }
4002
4003    @Override
4004    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4005        final int callingUid = Binder.getCallingUid();
4006        if (getInstantAppPackageName(callingUid) != null) {
4007            return null;
4008        }
4009        // reader
4010        synchronized (mPackages) {
4011            final BasePermission p = mSettings.mPermissions.get(name);
4012            if (p == null) {
4013                return null;
4014            }
4015            // If the caller is an app that targets pre 26 SDK drop protection flags.
4016            final PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4017            if (permissionInfo != null) {
4018                permissionInfo.protectionLevel = adjustPermissionProtectionFlagsLPr(
4019                        permissionInfo.protectionLevel, packageName, callingUid);
4020            }
4021            return permissionInfo;
4022        }
4023    }
4024
4025    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4026            String packageName, int uid) {
4027        // Signature permission flags area always reported
4028        final int protectionLevelMasked = protectionLevel
4029                & (PermissionInfo.PROTECTION_NORMAL
4030                | PermissionInfo.PROTECTION_DANGEROUS
4031                | PermissionInfo.PROTECTION_SIGNATURE);
4032        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4033            return protectionLevel;
4034        }
4035
4036        // System sees all flags.
4037        final int appId = UserHandle.getAppId(uid);
4038        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4039                || appId == Process.SHELL_UID) {
4040            return protectionLevel;
4041        }
4042
4043        // Normalize package name to handle renamed packages and static libs
4044        packageName = resolveInternalPackageNameLPr(packageName,
4045                PackageManager.VERSION_CODE_HIGHEST);
4046
4047        // Apps that target O see flags for all protection levels.
4048        final PackageSetting ps = mSettings.mPackages.get(packageName);
4049        if (ps == null) {
4050            return protectionLevel;
4051        }
4052        if (ps.appId != appId) {
4053            return protectionLevel;
4054        }
4055
4056        final PackageParser.Package pkg = mPackages.get(packageName);
4057        if (pkg == null) {
4058            return protectionLevel;
4059        }
4060        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4061            return protectionLevelMasked;
4062        }
4063
4064        return protectionLevel;
4065    }
4066
4067    @Override
4068    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4069            int flags) {
4070        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4071            return null;
4072        }
4073        // reader
4074        synchronized (mPackages) {
4075            if (group != null && !mPermissionGroups.containsKey(group)) {
4076                // This is thrown as NameNotFoundException
4077                return null;
4078            }
4079
4080            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4081            for (BasePermission p : mSettings.mPermissions.values()) {
4082                if (group == null) {
4083                    if (p.perm == null || p.perm.info.group == null) {
4084                        out.add(generatePermissionInfo(p, flags));
4085                    }
4086                } else {
4087                    if (p.perm != null && group.equals(p.perm.info.group)) {
4088                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4089                    }
4090                }
4091            }
4092            return new ParceledListSlice<>(out);
4093        }
4094    }
4095
4096    @Override
4097    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4098        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4099            return null;
4100        }
4101        // reader
4102        synchronized (mPackages) {
4103            return PackageParser.generatePermissionGroupInfo(
4104                    mPermissionGroups.get(name), flags);
4105        }
4106    }
4107
4108    @Override
4109    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4110        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4111            return ParceledListSlice.emptyList();
4112        }
4113        // reader
4114        synchronized (mPackages) {
4115            final int N = mPermissionGroups.size();
4116            ArrayList<PermissionGroupInfo> out
4117                    = new ArrayList<PermissionGroupInfo>(N);
4118            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4119                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4120            }
4121            return new ParceledListSlice<>(out);
4122        }
4123    }
4124
4125    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4126            int filterCallingUid, int userId) {
4127        if (!sUserManager.exists(userId)) return null;
4128        PackageSetting ps = mSettings.mPackages.get(packageName);
4129        if (ps != null) {
4130            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4131                return null;
4132            }
4133            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4134                return null;
4135            }
4136            if (ps.pkg == null) {
4137                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4138                if (pInfo != null) {
4139                    return pInfo.applicationInfo;
4140                }
4141                return null;
4142            }
4143            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4144                    ps.readUserState(userId), userId);
4145            if (ai != null) {
4146                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4147            }
4148            return ai;
4149        }
4150        return null;
4151    }
4152
4153    @Override
4154    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4155        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4156    }
4157
4158    /**
4159     * Important: The provided filterCallingUid is used exclusively to filter out applications
4160     * that can be seen based on user state. It's typically the original caller uid prior
4161     * to clearing. Because it can only be provided by trusted code, it's value can be
4162     * trusted and will be used as-is; unlike userId which will be validated by this method.
4163     */
4164    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4165            int filterCallingUid, int userId) {
4166        if (!sUserManager.exists(userId)) return null;
4167        flags = updateFlagsForApplication(flags, userId, packageName);
4168        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4169                false /* requireFullPermission */, false /* checkShell */, "get application info");
4170
4171        // writer
4172        synchronized (mPackages) {
4173            // Normalize package name to handle renamed packages and static libs
4174            packageName = resolveInternalPackageNameLPr(packageName,
4175                    PackageManager.VERSION_CODE_HIGHEST);
4176
4177            PackageParser.Package p = mPackages.get(packageName);
4178            if (DEBUG_PACKAGE_INFO) Log.v(
4179                    TAG, "getApplicationInfo " + packageName
4180                    + ": " + p);
4181            if (p != null) {
4182                PackageSetting ps = mSettings.mPackages.get(packageName);
4183                if (ps == null) return null;
4184                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4185                    return null;
4186                }
4187                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4188                    return null;
4189                }
4190                // Note: isEnabledLP() does not apply here - always return info
4191                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4192                        p, flags, ps.readUserState(userId), userId);
4193                if (ai != null) {
4194                    ai.packageName = resolveExternalPackageNameLPr(p);
4195                }
4196                return ai;
4197            }
4198            if ("android".equals(packageName)||"system".equals(packageName)) {
4199                return mAndroidApplication;
4200            }
4201            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4202                // Already generates the external package name
4203                return generateApplicationInfoFromSettingsLPw(packageName,
4204                        flags, filterCallingUid, userId);
4205            }
4206        }
4207        return null;
4208    }
4209
4210    private String normalizePackageNameLPr(String packageName) {
4211        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4212        return normalizedPackageName != null ? normalizedPackageName : packageName;
4213    }
4214
4215    @Override
4216    public void deletePreloadsFileCache() {
4217        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4218            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4219        }
4220        File dir = Environment.getDataPreloadsFileCacheDirectory();
4221        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4222        FileUtils.deleteContents(dir);
4223    }
4224
4225    @Override
4226    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4227            final int storageFlags, final IPackageDataObserver observer) {
4228        mContext.enforceCallingOrSelfPermission(
4229                android.Manifest.permission.CLEAR_APP_CACHE, null);
4230        mHandler.post(() -> {
4231            boolean success = false;
4232            try {
4233                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4234                success = true;
4235            } catch (IOException e) {
4236                Slog.w(TAG, e);
4237            }
4238            if (observer != null) {
4239                try {
4240                    observer.onRemoveCompleted(null, success);
4241                } catch (RemoteException e) {
4242                    Slog.w(TAG, e);
4243                }
4244            }
4245        });
4246    }
4247
4248    @Override
4249    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4250            final int storageFlags, final IntentSender pi) {
4251        mContext.enforceCallingOrSelfPermission(
4252                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4253        mHandler.post(() -> {
4254            boolean success = false;
4255            try {
4256                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4257                success = true;
4258            } catch (IOException e) {
4259                Slog.w(TAG, e);
4260            }
4261            if (pi != null) {
4262                try {
4263                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4264                } catch (SendIntentException e) {
4265                    Slog.w(TAG, e);
4266                }
4267            }
4268        });
4269    }
4270
4271    /**
4272     * Blocking call to clear various types of cached data across the system
4273     * until the requested bytes are available.
4274     */
4275    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4276        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4277        final File file = storage.findPathForUuid(volumeUuid);
4278        if (file.getUsableSpace() >= bytes) return;
4279
4280        if (ENABLE_FREE_CACHE_V2) {
4281            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4282                    volumeUuid);
4283            final boolean aggressive = (storageFlags
4284                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4285            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4286
4287            // 1. Pre-flight to determine if we have any chance to succeed
4288            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4289            if (internalVolume && (aggressive || SystemProperties
4290                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4291                deletePreloadsFileCache();
4292                if (file.getUsableSpace() >= bytes) return;
4293            }
4294
4295            // 3. Consider parsed APK data (aggressive only)
4296            if (internalVolume && aggressive) {
4297                FileUtils.deleteContents(mCacheDir);
4298                if (file.getUsableSpace() >= bytes) return;
4299            }
4300
4301            // 4. Consider cached app data (above quotas)
4302            try {
4303                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4304                        Installer.FLAG_FREE_CACHE_V2);
4305            } catch (InstallerException ignored) {
4306            }
4307            if (file.getUsableSpace() >= bytes) return;
4308
4309            // 5. Consider shared libraries with refcount=0 and age>min cache period
4310            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4311                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4312                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4313                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4314                return;
4315            }
4316
4317            // 6. Consider dexopt output (aggressive only)
4318            // TODO: Implement
4319
4320            // 7. Consider installed instant apps unused longer than min cache period
4321            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4322                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4323                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4324                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4325                return;
4326            }
4327
4328            // 8. Consider cached app data (below quotas)
4329            try {
4330                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4331                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4332            } catch (InstallerException ignored) {
4333            }
4334            if (file.getUsableSpace() >= bytes) return;
4335
4336            // 9. Consider DropBox entries
4337            // TODO: Implement
4338
4339            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4340            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4341                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4342                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4343                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4344                return;
4345            }
4346        } else {
4347            try {
4348                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4349            } catch (InstallerException ignored) {
4350            }
4351            if (file.getUsableSpace() >= bytes) return;
4352        }
4353
4354        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4355    }
4356
4357    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4358            throws IOException {
4359        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4360        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4361
4362        List<VersionedPackage> packagesToDelete = null;
4363        final long now = System.currentTimeMillis();
4364
4365        synchronized (mPackages) {
4366            final int[] allUsers = sUserManager.getUserIds();
4367            final int libCount = mSharedLibraries.size();
4368            for (int i = 0; i < libCount; i++) {
4369                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4370                if (versionedLib == null) {
4371                    continue;
4372                }
4373                final int versionCount = versionedLib.size();
4374                for (int j = 0; j < versionCount; j++) {
4375                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4376                    // Skip packages that are not static shared libs.
4377                    if (!libInfo.isStatic()) {
4378                        break;
4379                    }
4380                    // Important: We skip static shared libs used for some user since
4381                    // in such a case we need to keep the APK on the device. The check for
4382                    // a lib being used for any user is performed by the uninstall call.
4383                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4384                    // Resolve the package name - we use synthetic package names internally
4385                    final String internalPackageName = resolveInternalPackageNameLPr(
4386                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4387                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4388                    // Skip unused static shared libs cached less than the min period
4389                    // to prevent pruning a lib needed by a subsequently installed package.
4390                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4391                        continue;
4392                    }
4393                    if (packagesToDelete == null) {
4394                        packagesToDelete = new ArrayList<>();
4395                    }
4396                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4397                            declaringPackage.getVersionCode()));
4398                }
4399            }
4400        }
4401
4402        if (packagesToDelete != null) {
4403            final int packageCount = packagesToDelete.size();
4404            for (int i = 0; i < packageCount; i++) {
4405                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4406                // Delete the package synchronously (will fail of the lib used for any user).
4407                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4408                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4409                                == PackageManager.DELETE_SUCCEEDED) {
4410                    if (volume.getUsableSpace() >= neededSpace) {
4411                        return true;
4412                    }
4413                }
4414            }
4415        }
4416
4417        return false;
4418    }
4419
4420    /**
4421     * Update given flags based on encryption status of current user.
4422     */
4423    private int updateFlags(int flags, int userId) {
4424        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4425                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4426            // Caller expressed an explicit opinion about what encryption
4427            // aware/unaware components they want to see, so fall through and
4428            // give them what they want
4429        } else {
4430            // Caller expressed no opinion, so match based on user state
4431            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4432                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4433            } else {
4434                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4435            }
4436        }
4437        return flags;
4438    }
4439
4440    private UserManagerInternal getUserManagerInternal() {
4441        if (mUserManagerInternal == null) {
4442            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4443        }
4444        return mUserManagerInternal;
4445    }
4446
4447    private DeviceIdleController.LocalService getDeviceIdleController() {
4448        if (mDeviceIdleController == null) {
4449            mDeviceIdleController =
4450                    LocalServices.getService(DeviceIdleController.LocalService.class);
4451        }
4452        return mDeviceIdleController;
4453    }
4454
4455    /**
4456     * Update given flags when being used to request {@link PackageInfo}.
4457     */
4458    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4459        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4460        boolean triaged = true;
4461        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4462                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4463            // Caller is asking for component details, so they'd better be
4464            // asking for specific encryption matching behavior, or be triaged
4465            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4466                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4467                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4468                triaged = false;
4469            }
4470        }
4471        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4472                | PackageManager.MATCH_SYSTEM_ONLY
4473                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4474            triaged = false;
4475        }
4476        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4477            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4478                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4479                    + Debug.getCallers(5));
4480        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4481                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4482            // If the caller wants all packages and has a restricted profile associated with it,
4483            // then match all users. This is to make sure that launchers that need to access work
4484            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4485            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4486            flags |= PackageManager.MATCH_ANY_USER;
4487        }
4488        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4489            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4490                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4491        }
4492        return updateFlags(flags, userId);
4493    }
4494
4495    /**
4496     * Update given flags when being used to request {@link ApplicationInfo}.
4497     */
4498    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4499        return updateFlagsForPackage(flags, userId, cookie);
4500    }
4501
4502    /**
4503     * Update given flags when being used to request {@link ComponentInfo}.
4504     */
4505    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4506        if (cookie instanceof Intent) {
4507            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4508                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4509            }
4510        }
4511
4512        boolean triaged = true;
4513        // Caller is asking for component details, so they'd better be
4514        // asking for specific encryption matching behavior, or be triaged
4515        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4516                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4517                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4518            triaged = false;
4519        }
4520        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4521            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4522                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4523        }
4524
4525        return updateFlags(flags, userId);
4526    }
4527
4528    /**
4529     * Update given intent when being used to request {@link ResolveInfo}.
4530     */
4531    private Intent updateIntentForResolve(Intent intent) {
4532        if (intent.getSelector() != null) {
4533            intent = intent.getSelector();
4534        }
4535        if (DEBUG_PREFERRED) {
4536            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4537        }
4538        return intent;
4539    }
4540
4541    /**
4542     * Update given flags when being used to request {@link ResolveInfo}.
4543     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4544     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4545     * flag set. However, this flag is only honoured in three circumstances:
4546     * <ul>
4547     * <li>when called from a system process</li>
4548     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4549     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4550     * action and a {@code android.intent.category.BROWSABLE} category</li>
4551     * </ul>
4552     */
4553    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4554        return updateFlagsForResolve(flags, userId, intent, callingUid,
4555                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4556    }
4557    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4558            boolean wantInstantApps) {
4559        return updateFlagsForResolve(flags, userId, intent, callingUid,
4560                wantInstantApps, false /*onlyExposedExplicitly*/);
4561    }
4562    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4563            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4564        // Safe mode means we shouldn't match any third-party components
4565        if (mSafeMode) {
4566            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4567        }
4568        if (getInstantAppPackageName(callingUid) != null) {
4569            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4570            if (onlyExposedExplicitly) {
4571                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4572            }
4573            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4574            flags |= PackageManager.MATCH_INSTANT;
4575        } else {
4576            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4577            final boolean allowMatchInstant =
4578                    (wantInstantApps
4579                            && Intent.ACTION_VIEW.equals(intent.getAction())
4580                            && hasWebURI(intent))
4581                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4582            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4583                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4584            if (!allowMatchInstant) {
4585                flags &= ~PackageManager.MATCH_INSTANT;
4586            }
4587        }
4588        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4589    }
4590
4591    @Override
4592    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4593        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4594    }
4595
4596    /**
4597     * Important: The provided filterCallingUid is used exclusively to filter out activities
4598     * that can be seen based on user state. It's typically the original caller uid prior
4599     * to clearing. Because it can only be provided by trusted code, it's value can be
4600     * trusted and will be used as-is; unlike userId which will be validated by this method.
4601     */
4602    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4603            int filterCallingUid, int userId) {
4604        if (!sUserManager.exists(userId)) return null;
4605        flags = updateFlagsForComponent(flags, userId, component);
4606        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4607                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4608        synchronized (mPackages) {
4609            PackageParser.Activity a = mActivities.mActivities.get(component);
4610
4611            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4612            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4613                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4614                if (ps == null) return null;
4615                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4616                    return null;
4617                }
4618                return PackageParser.generateActivityInfo(
4619                        a, flags, ps.readUserState(userId), userId);
4620            }
4621            if (mResolveComponentName.equals(component)) {
4622                return PackageParser.generateActivityInfo(
4623                        mResolveActivity, flags, new PackageUserState(), userId);
4624            }
4625        }
4626        return null;
4627    }
4628
4629    @Override
4630    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4631            String resolvedType) {
4632        synchronized (mPackages) {
4633            if (component.equals(mResolveComponentName)) {
4634                // The resolver supports EVERYTHING!
4635                return true;
4636            }
4637            final int callingUid = Binder.getCallingUid();
4638            final int callingUserId = UserHandle.getUserId(callingUid);
4639            PackageParser.Activity a = mActivities.mActivities.get(component);
4640            if (a == null) {
4641                return false;
4642            }
4643            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4644            if (ps == null) {
4645                return false;
4646            }
4647            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4648                return false;
4649            }
4650            for (int i=0; i<a.intents.size(); i++) {
4651                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4652                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4653                    return true;
4654                }
4655            }
4656            return false;
4657        }
4658    }
4659
4660    @Override
4661    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4662        if (!sUserManager.exists(userId)) return null;
4663        final int callingUid = Binder.getCallingUid();
4664        flags = updateFlagsForComponent(flags, userId, component);
4665        enforceCrossUserPermission(callingUid, userId,
4666                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4667        synchronized (mPackages) {
4668            PackageParser.Activity a = mReceivers.mActivities.get(component);
4669            if (DEBUG_PACKAGE_INFO) Log.v(
4670                TAG, "getReceiverInfo " + component + ": " + a);
4671            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4672                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4673                if (ps == null) return null;
4674                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4675                    return null;
4676                }
4677                return PackageParser.generateActivityInfo(
4678                        a, flags, ps.readUserState(userId), userId);
4679            }
4680        }
4681        return null;
4682    }
4683
4684    @Override
4685    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4686            int flags, int userId) {
4687        if (!sUserManager.exists(userId)) return null;
4688        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4689        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4690            return null;
4691        }
4692
4693        flags = updateFlagsForPackage(flags, userId, null);
4694
4695        final boolean canSeeStaticLibraries =
4696                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4697                        == PERMISSION_GRANTED
4698                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4699                        == PERMISSION_GRANTED
4700                || canRequestPackageInstallsInternal(packageName,
4701                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4702                        false  /* throwIfPermNotDeclared*/)
4703                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4704                        == PERMISSION_GRANTED;
4705
4706        synchronized (mPackages) {
4707            List<SharedLibraryInfo> result = null;
4708
4709            final int libCount = mSharedLibraries.size();
4710            for (int i = 0; i < libCount; i++) {
4711                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4712                if (versionedLib == null) {
4713                    continue;
4714                }
4715
4716                final int versionCount = versionedLib.size();
4717                for (int j = 0; j < versionCount; j++) {
4718                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4719                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4720                        break;
4721                    }
4722                    final long identity = Binder.clearCallingIdentity();
4723                    try {
4724                        PackageInfo packageInfo = getPackageInfoVersioned(
4725                                libInfo.getDeclaringPackage(), flags
4726                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4727                        if (packageInfo == null) {
4728                            continue;
4729                        }
4730                    } finally {
4731                        Binder.restoreCallingIdentity(identity);
4732                    }
4733
4734                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4735                            libInfo.getVersion(), libInfo.getType(),
4736                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4737                            flags, userId));
4738
4739                    if (result == null) {
4740                        result = new ArrayList<>();
4741                    }
4742                    result.add(resLibInfo);
4743                }
4744            }
4745
4746            return result != null ? new ParceledListSlice<>(result) : null;
4747        }
4748    }
4749
4750    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4751            SharedLibraryInfo libInfo, int flags, int userId) {
4752        List<VersionedPackage> versionedPackages = null;
4753        final int packageCount = mSettings.mPackages.size();
4754        for (int i = 0; i < packageCount; i++) {
4755            PackageSetting ps = mSettings.mPackages.valueAt(i);
4756
4757            if (ps == null) {
4758                continue;
4759            }
4760
4761            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4762                continue;
4763            }
4764
4765            final String libName = libInfo.getName();
4766            if (libInfo.isStatic()) {
4767                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4768                if (libIdx < 0) {
4769                    continue;
4770                }
4771                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4772                    continue;
4773                }
4774                if (versionedPackages == null) {
4775                    versionedPackages = new ArrayList<>();
4776                }
4777                // If the dependent is a static shared lib, use the public package name
4778                String dependentPackageName = ps.name;
4779                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4780                    dependentPackageName = ps.pkg.manifestPackageName;
4781                }
4782                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4783            } else if (ps.pkg != null) {
4784                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4785                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4786                    if (versionedPackages == null) {
4787                        versionedPackages = new ArrayList<>();
4788                    }
4789                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4790                }
4791            }
4792        }
4793
4794        return versionedPackages;
4795    }
4796
4797    @Override
4798    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4799        if (!sUserManager.exists(userId)) return null;
4800        final int callingUid = Binder.getCallingUid();
4801        flags = updateFlagsForComponent(flags, userId, component);
4802        enforceCrossUserPermission(callingUid, userId,
4803                false /* requireFullPermission */, false /* checkShell */, "get service info");
4804        synchronized (mPackages) {
4805            PackageParser.Service s = mServices.mServices.get(component);
4806            if (DEBUG_PACKAGE_INFO) Log.v(
4807                TAG, "getServiceInfo " + component + ": " + s);
4808            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4809                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4810                if (ps == null) return null;
4811                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4812                    return null;
4813                }
4814                return PackageParser.generateServiceInfo(
4815                        s, flags, ps.readUserState(userId), userId);
4816            }
4817        }
4818        return null;
4819    }
4820
4821    @Override
4822    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4823        if (!sUserManager.exists(userId)) return null;
4824        final int callingUid = Binder.getCallingUid();
4825        flags = updateFlagsForComponent(flags, userId, component);
4826        enforceCrossUserPermission(callingUid, userId,
4827                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4828        synchronized (mPackages) {
4829            PackageParser.Provider p = mProviders.mProviders.get(component);
4830            if (DEBUG_PACKAGE_INFO) Log.v(
4831                TAG, "getProviderInfo " + component + ": " + p);
4832            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4833                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4834                if (ps == null) return null;
4835                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4836                    return null;
4837                }
4838                return PackageParser.generateProviderInfo(
4839                        p, flags, ps.readUserState(userId), userId);
4840            }
4841        }
4842        return null;
4843    }
4844
4845    @Override
4846    public String[] getSystemSharedLibraryNames() {
4847        // allow instant applications
4848        synchronized (mPackages) {
4849            Set<String> libs = null;
4850            final int libCount = mSharedLibraries.size();
4851            for (int i = 0; i < libCount; i++) {
4852                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4853                if (versionedLib == null) {
4854                    continue;
4855                }
4856                final int versionCount = versionedLib.size();
4857                for (int j = 0; j < versionCount; j++) {
4858                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4859                    if (!libEntry.info.isStatic()) {
4860                        if (libs == null) {
4861                            libs = new ArraySet<>();
4862                        }
4863                        libs.add(libEntry.info.getName());
4864                        break;
4865                    }
4866                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4867                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4868                            UserHandle.getUserId(Binder.getCallingUid()),
4869                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4870                        if (libs == null) {
4871                            libs = new ArraySet<>();
4872                        }
4873                        libs.add(libEntry.info.getName());
4874                        break;
4875                    }
4876                }
4877            }
4878
4879            if (libs != null) {
4880                String[] libsArray = new String[libs.size()];
4881                libs.toArray(libsArray);
4882                return libsArray;
4883            }
4884
4885            return null;
4886        }
4887    }
4888
4889    @Override
4890    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4891        // allow instant applications
4892        synchronized (mPackages) {
4893            return mServicesSystemSharedLibraryPackageName;
4894        }
4895    }
4896
4897    @Override
4898    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4899        // allow instant applications
4900        synchronized (mPackages) {
4901            return mSharedSystemSharedLibraryPackageName;
4902        }
4903    }
4904
4905    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4906        for (int i = userList.length - 1; i >= 0; --i) {
4907            final int userId = userList[i];
4908            // don't add instant app to the list of updates
4909            if (pkgSetting.getInstantApp(userId)) {
4910                continue;
4911            }
4912            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4913            if (changedPackages == null) {
4914                changedPackages = new SparseArray<>();
4915                mChangedPackages.put(userId, changedPackages);
4916            }
4917            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4918            if (sequenceNumbers == null) {
4919                sequenceNumbers = new HashMap<>();
4920                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4921            }
4922            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4923            if (sequenceNumber != null) {
4924                changedPackages.remove(sequenceNumber);
4925            }
4926            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4927            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4928        }
4929        mChangedPackagesSequenceNumber++;
4930    }
4931
4932    @Override
4933    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4934        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4935            return null;
4936        }
4937        synchronized (mPackages) {
4938            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4939                return null;
4940            }
4941            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4942            if (changedPackages == null) {
4943                return null;
4944            }
4945            final List<String> packageNames =
4946                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4947            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4948                final String packageName = changedPackages.get(i);
4949                if (packageName != null) {
4950                    packageNames.add(packageName);
4951                }
4952            }
4953            return packageNames.isEmpty()
4954                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4955        }
4956    }
4957
4958    @Override
4959    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4960        // allow instant applications
4961        ArrayList<FeatureInfo> res;
4962        synchronized (mAvailableFeatures) {
4963            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4964            res.addAll(mAvailableFeatures.values());
4965        }
4966        final FeatureInfo fi = new FeatureInfo();
4967        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4968                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4969        res.add(fi);
4970
4971        return new ParceledListSlice<>(res);
4972    }
4973
4974    @Override
4975    public boolean hasSystemFeature(String name, int version) {
4976        // allow instant applications
4977        synchronized (mAvailableFeatures) {
4978            final FeatureInfo feat = mAvailableFeatures.get(name);
4979            if (feat == null) {
4980                return false;
4981            } else {
4982                return feat.version >= version;
4983            }
4984        }
4985    }
4986
4987    @Override
4988    public int checkPermission(String permName, String pkgName, int userId) {
4989        if (!sUserManager.exists(userId)) {
4990            return PackageManager.PERMISSION_DENIED;
4991        }
4992        final int callingUid = Binder.getCallingUid();
4993
4994        synchronized (mPackages) {
4995            final PackageParser.Package p = mPackages.get(pkgName);
4996            if (p != null && p.mExtras != null) {
4997                final PackageSetting ps = (PackageSetting) p.mExtras;
4998                if (filterAppAccessLPr(ps, callingUid, userId)) {
4999                    return PackageManager.PERMISSION_DENIED;
5000                }
5001                final boolean instantApp = ps.getInstantApp(userId);
5002                final PermissionsState permissionsState = ps.getPermissionsState();
5003                if (permissionsState.hasPermission(permName, userId)) {
5004                    if (instantApp) {
5005                        BasePermission bp = mSettings.mPermissions.get(permName);
5006                        if (bp != null && bp.isInstant()) {
5007                            return PackageManager.PERMISSION_GRANTED;
5008                        }
5009                    } else {
5010                        return PackageManager.PERMISSION_GRANTED;
5011                    }
5012                }
5013                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5014                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5015                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5016                    return PackageManager.PERMISSION_GRANTED;
5017                }
5018            }
5019        }
5020
5021        return PackageManager.PERMISSION_DENIED;
5022    }
5023
5024    @Override
5025    public int checkUidPermission(String permName, int uid) {
5026        final int callingUid = Binder.getCallingUid();
5027        final int callingUserId = UserHandle.getUserId(callingUid);
5028        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5029        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5030        final int userId = UserHandle.getUserId(uid);
5031        if (!sUserManager.exists(userId)) {
5032            return PackageManager.PERMISSION_DENIED;
5033        }
5034
5035        synchronized (mPackages) {
5036            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5037            if (obj != null) {
5038                if (obj instanceof SharedUserSetting) {
5039                    if (isCallerInstantApp) {
5040                        return PackageManager.PERMISSION_DENIED;
5041                    }
5042                } else if (obj instanceof PackageSetting) {
5043                    final PackageSetting ps = (PackageSetting) obj;
5044                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5045                        return PackageManager.PERMISSION_DENIED;
5046                    }
5047                }
5048                final SettingBase settingBase = (SettingBase) obj;
5049                final PermissionsState permissionsState = settingBase.getPermissionsState();
5050                if (permissionsState.hasPermission(permName, userId)) {
5051                    if (isUidInstantApp) {
5052                        BasePermission bp = mSettings.mPermissions.get(permName);
5053                        if (bp != null && bp.isInstant()) {
5054                            return PackageManager.PERMISSION_GRANTED;
5055                        }
5056                    } else {
5057                        return PackageManager.PERMISSION_GRANTED;
5058                    }
5059                }
5060                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5061                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5062                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5063                    return PackageManager.PERMISSION_GRANTED;
5064                }
5065            } else {
5066                ArraySet<String> perms = mSystemPermissions.get(uid);
5067                if (perms != null) {
5068                    if (perms.contains(permName)) {
5069                        return PackageManager.PERMISSION_GRANTED;
5070                    }
5071                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5072                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5073                        return PackageManager.PERMISSION_GRANTED;
5074                    }
5075                }
5076            }
5077        }
5078
5079        return PackageManager.PERMISSION_DENIED;
5080    }
5081
5082    @Override
5083    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5084        if (UserHandle.getCallingUserId() != userId) {
5085            mContext.enforceCallingPermission(
5086                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5087                    "isPermissionRevokedByPolicy for user " + userId);
5088        }
5089
5090        if (checkPermission(permission, packageName, userId)
5091                == PackageManager.PERMISSION_GRANTED) {
5092            return false;
5093        }
5094
5095        final int callingUid = Binder.getCallingUid();
5096        if (getInstantAppPackageName(callingUid) != null) {
5097            if (!isCallerSameApp(packageName, callingUid)) {
5098                return false;
5099            }
5100        } else {
5101            if (isInstantApp(packageName, userId)) {
5102                return false;
5103            }
5104        }
5105
5106        final long identity = Binder.clearCallingIdentity();
5107        try {
5108            final int flags = getPermissionFlags(permission, packageName, userId);
5109            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5110        } finally {
5111            Binder.restoreCallingIdentity(identity);
5112        }
5113    }
5114
5115    @Override
5116    public String getPermissionControllerPackageName() {
5117        synchronized (mPackages) {
5118            return mRequiredInstallerPackage;
5119        }
5120    }
5121
5122    /**
5123     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5124     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5125     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5126     * @param message the message to log on security exception
5127     */
5128    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5129            boolean checkShell, String message) {
5130        if (userId < 0) {
5131            throw new IllegalArgumentException("Invalid userId " + userId);
5132        }
5133        if (checkShell) {
5134            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5135        }
5136        if (userId == UserHandle.getUserId(callingUid)) return;
5137        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5138            if (requireFullPermission) {
5139                mContext.enforceCallingOrSelfPermission(
5140                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5141            } else {
5142                try {
5143                    mContext.enforceCallingOrSelfPermission(
5144                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5145                } catch (SecurityException se) {
5146                    mContext.enforceCallingOrSelfPermission(
5147                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5148                }
5149            }
5150        }
5151    }
5152
5153    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5154        if (callingUid == Process.SHELL_UID) {
5155            if (userHandle >= 0
5156                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5157                throw new SecurityException("Shell does not have permission to access user "
5158                        + userHandle);
5159            } else if (userHandle < 0) {
5160                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5161                        + Debug.getCallers(3));
5162            }
5163        }
5164    }
5165
5166    private BasePermission findPermissionTreeLP(String permName) {
5167        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5168            if (permName.startsWith(bp.name) &&
5169                    permName.length() > bp.name.length() &&
5170                    permName.charAt(bp.name.length()) == '.') {
5171                return bp;
5172            }
5173        }
5174        return null;
5175    }
5176
5177    private BasePermission checkPermissionTreeLP(String permName) {
5178        if (permName != null) {
5179            BasePermission bp = findPermissionTreeLP(permName);
5180            if (bp != null) {
5181                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5182                    return bp;
5183                }
5184                throw new SecurityException("Calling uid "
5185                        + Binder.getCallingUid()
5186                        + " is not allowed to add to permission tree "
5187                        + bp.name + " owned by uid " + bp.uid);
5188            }
5189        }
5190        throw new SecurityException("No permission tree found for " + permName);
5191    }
5192
5193    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5194        if (s1 == null) {
5195            return s2 == null;
5196        }
5197        if (s2 == null) {
5198            return false;
5199        }
5200        if (s1.getClass() != s2.getClass()) {
5201            return false;
5202        }
5203        return s1.equals(s2);
5204    }
5205
5206    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5207        if (pi1.icon != pi2.icon) return false;
5208        if (pi1.logo != pi2.logo) return false;
5209        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5210        if (!compareStrings(pi1.name, pi2.name)) return false;
5211        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5212        // We'll take care of setting this one.
5213        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5214        // These are not currently stored in settings.
5215        //if (!compareStrings(pi1.group, pi2.group)) return false;
5216        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5217        //if (pi1.labelRes != pi2.labelRes) return false;
5218        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5219        return true;
5220    }
5221
5222    int permissionInfoFootprint(PermissionInfo info) {
5223        int size = info.name.length();
5224        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5225        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5226        return size;
5227    }
5228
5229    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5230        int size = 0;
5231        for (BasePermission perm : mSettings.mPermissions.values()) {
5232            if (perm.uid == tree.uid) {
5233                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5234            }
5235        }
5236        return size;
5237    }
5238
5239    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5240        // We calculate the max size of permissions defined by this uid and throw
5241        // if that plus the size of 'info' would exceed our stated maximum.
5242        if (tree.uid != Process.SYSTEM_UID) {
5243            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5244            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5245                throw new SecurityException("Permission tree size cap exceeded");
5246            }
5247        }
5248    }
5249
5250    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5251        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5252            throw new SecurityException("Instant apps can't add permissions");
5253        }
5254        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5255            throw new SecurityException("Label must be specified in permission");
5256        }
5257        BasePermission tree = checkPermissionTreeLP(info.name);
5258        BasePermission bp = mSettings.mPermissions.get(info.name);
5259        boolean added = bp == null;
5260        boolean changed = true;
5261        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5262        if (added) {
5263            enforcePermissionCapLocked(info, tree);
5264            bp = new BasePermission(info.name, tree.sourcePackage,
5265                    BasePermission.TYPE_DYNAMIC);
5266        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5267            throw new SecurityException(
5268                    "Not allowed to modify non-dynamic permission "
5269                    + info.name);
5270        } else {
5271            if (bp.protectionLevel == fixedLevel
5272                    && bp.perm.owner.equals(tree.perm.owner)
5273                    && bp.uid == tree.uid
5274                    && comparePermissionInfos(bp.perm.info, info)) {
5275                changed = false;
5276            }
5277        }
5278        bp.protectionLevel = fixedLevel;
5279        info = new PermissionInfo(info);
5280        info.protectionLevel = fixedLevel;
5281        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5282        bp.perm.info.packageName = tree.perm.info.packageName;
5283        bp.uid = tree.uid;
5284        if (added) {
5285            mSettings.mPermissions.put(info.name, bp);
5286        }
5287        if (changed) {
5288            if (!async) {
5289                mSettings.writeLPr();
5290            } else {
5291                scheduleWriteSettingsLocked();
5292            }
5293        }
5294        return added;
5295    }
5296
5297    @Override
5298    public boolean addPermission(PermissionInfo info) {
5299        synchronized (mPackages) {
5300            return addPermissionLocked(info, false);
5301        }
5302    }
5303
5304    @Override
5305    public boolean addPermissionAsync(PermissionInfo info) {
5306        synchronized (mPackages) {
5307            return addPermissionLocked(info, true);
5308        }
5309    }
5310
5311    @Override
5312    public void removePermission(String name) {
5313        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5314            throw new SecurityException("Instant applications don't have access to this method");
5315        }
5316        synchronized (mPackages) {
5317            checkPermissionTreeLP(name);
5318            BasePermission bp = mSettings.mPermissions.get(name);
5319            if (bp != null) {
5320                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5321                    throw new SecurityException(
5322                            "Not allowed to modify non-dynamic permission "
5323                            + name);
5324                }
5325                mSettings.mPermissions.remove(name);
5326                mSettings.writeLPr();
5327            }
5328        }
5329    }
5330
5331    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5332            PackageParser.Package pkg, BasePermission bp) {
5333        int index = pkg.requestedPermissions.indexOf(bp.name);
5334        if (index == -1) {
5335            throw new SecurityException("Package " + pkg.packageName
5336                    + " has not requested permission " + bp.name);
5337        }
5338        if (!bp.isRuntime() && !bp.isDevelopment()) {
5339            throw new SecurityException("Permission " + bp.name
5340                    + " is not a changeable permission type");
5341        }
5342    }
5343
5344    @Override
5345    public void grantRuntimePermission(String packageName, String name, final int userId) {
5346        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5347    }
5348
5349    private void grantRuntimePermission(String packageName, String name, final int userId,
5350            boolean overridePolicy) {
5351        if (!sUserManager.exists(userId)) {
5352            Log.e(TAG, "No such user:" + userId);
5353            return;
5354        }
5355        final int callingUid = Binder.getCallingUid();
5356
5357        mContext.enforceCallingOrSelfPermission(
5358                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5359                "grantRuntimePermission");
5360
5361        enforceCrossUserPermission(callingUid, userId,
5362                true /* requireFullPermission */, true /* checkShell */,
5363                "grantRuntimePermission");
5364
5365        final int uid;
5366        final PackageSetting ps;
5367
5368        synchronized (mPackages) {
5369            final PackageParser.Package pkg = mPackages.get(packageName);
5370            if (pkg == null) {
5371                throw new IllegalArgumentException("Unknown package: " + packageName);
5372            }
5373            final BasePermission bp = mSettings.mPermissions.get(name);
5374            if (bp == null) {
5375                throw new IllegalArgumentException("Unknown permission: " + name);
5376            }
5377            ps = (PackageSetting) pkg.mExtras;
5378            if (ps == null
5379                    || filterAppAccessLPr(ps, callingUid, userId)) {
5380                throw new IllegalArgumentException("Unknown package: " + packageName);
5381            }
5382
5383            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5384
5385            // If a permission review is required for legacy apps we represent
5386            // their permissions as always granted runtime ones since we need
5387            // to keep the review required permission flag per user while an
5388            // install permission's state is shared across all users.
5389            if (mPermissionReviewRequired
5390                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5391                    && bp.isRuntime()) {
5392                return;
5393            }
5394
5395            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5396
5397            final PermissionsState permissionsState = ps.getPermissionsState();
5398
5399            final int flags = permissionsState.getPermissionFlags(name, userId);
5400            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5401                throw new SecurityException("Cannot grant system fixed permission "
5402                        + name + " for package " + packageName);
5403            }
5404            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5405                throw new SecurityException("Cannot grant policy fixed permission "
5406                        + name + " for package " + packageName);
5407            }
5408
5409            if (bp.isDevelopment()) {
5410                // Development permissions must be handled specially, since they are not
5411                // normal runtime permissions.  For now they apply to all users.
5412                if (permissionsState.grantInstallPermission(bp) !=
5413                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5414                    scheduleWriteSettingsLocked();
5415                }
5416                return;
5417            }
5418
5419            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5420                throw new SecurityException("Cannot grant non-ephemeral permission"
5421                        + name + " for package " + packageName);
5422            }
5423
5424            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5425                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5426                return;
5427            }
5428
5429            final int result = permissionsState.grantRuntimePermission(bp, userId);
5430            switch (result) {
5431                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5432                    return;
5433                }
5434
5435                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5436                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5437                    mHandler.post(new Runnable() {
5438                        @Override
5439                        public void run() {
5440                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5441                        }
5442                    });
5443                }
5444                break;
5445            }
5446
5447            if (bp.isRuntime()) {
5448                logPermissionGranted(mContext, name, packageName);
5449            }
5450
5451            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5452
5453            // Not critical if that is lost - app has to request again.
5454            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5455        }
5456
5457        // Only need to do this if user is initialized. Otherwise it's a new user
5458        // and there are no processes running as the user yet and there's no need
5459        // to make an expensive call to remount processes for the changed permissions.
5460        if (READ_EXTERNAL_STORAGE.equals(name)
5461                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5462            final long token = Binder.clearCallingIdentity();
5463            try {
5464                if (sUserManager.isInitialized(userId)) {
5465                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5466                            StorageManagerInternal.class);
5467                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5468                }
5469            } finally {
5470                Binder.restoreCallingIdentity(token);
5471            }
5472        }
5473    }
5474
5475    @Override
5476    public void revokeRuntimePermission(String packageName, String name, int userId) {
5477        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5478    }
5479
5480    private void revokeRuntimePermission(String packageName, String name, int userId,
5481            boolean overridePolicy) {
5482        if (!sUserManager.exists(userId)) {
5483            Log.e(TAG, "No such user:" + userId);
5484            return;
5485        }
5486
5487        mContext.enforceCallingOrSelfPermission(
5488                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5489                "revokeRuntimePermission");
5490
5491        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5492                true /* requireFullPermission */, true /* checkShell */,
5493                "revokeRuntimePermission");
5494
5495        final int appId;
5496
5497        synchronized (mPackages) {
5498            final PackageParser.Package pkg = mPackages.get(packageName);
5499            if (pkg == null) {
5500                throw new IllegalArgumentException("Unknown package: " + packageName);
5501            }
5502            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5503            if (ps == null
5504                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5505                throw new IllegalArgumentException("Unknown package: " + packageName);
5506            }
5507            final BasePermission bp = mSettings.mPermissions.get(name);
5508            if (bp == null) {
5509                throw new IllegalArgumentException("Unknown permission: " + name);
5510            }
5511
5512            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5513
5514            // If a permission review is required for legacy apps we represent
5515            // their permissions as always granted runtime ones since we need
5516            // to keep the review required permission flag per user while an
5517            // install permission's state is shared across all users.
5518            if (mPermissionReviewRequired
5519                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5520                    && bp.isRuntime()) {
5521                return;
5522            }
5523
5524            final PermissionsState permissionsState = ps.getPermissionsState();
5525
5526            final int flags = permissionsState.getPermissionFlags(name, userId);
5527            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5528                throw new SecurityException("Cannot revoke system fixed permission "
5529                        + name + " for package " + packageName);
5530            }
5531            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5532                throw new SecurityException("Cannot revoke policy fixed permission "
5533                        + name + " for package " + packageName);
5534            }
5535
5536            if (bp.isDevelopment()) {
5537                // Development permissions must be handled specially, since they are not
5538                // normal runtime permissions.  For now they apply to all users.
5539                if (permissionsState.revokeInstallPermission(bp) !=
5540                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5541                    scheduleWriteSettingsLocked();
5542                }
5543                return;
5544            }
5545
5546            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5547                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5548                return;
5549            }
5550
5551            if (bp.isRuntime()) {
5552                logPermissionRevoked(mContext, name, packageName);
5553            }
5554
5555            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5556
5557            // Critical, after this call app should never have the permission.
5558            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5559
5560            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5561        }
5562
5563        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5564    }
5565
5566    /**
5567     * Get the first event id for the permission.
5568     *
5569     * <p>There are four events for each permission: <ul>
5570     *     <li>Request permission: first id + 0</li>
5571     *     <li>Grant permission: first id + 1</li>
5572     *     <li>Request for permission denied: first id + 2</li>
5573     *     <li>Revoke permission: first id + 3</li>
5574     * </ul></p>
5575     *
5576     * @param name name of the permission
5577     *
5578     * @return The first event id for the permission
5579     */
5580    private static int getBaseEventId(@NonNull String name) {
5581        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5582
5583        if (eventIdIndex == -1) {
5584            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5585                    || "user".equals(Build.TYPE)) {
5586                Log.i(TAG, "Unknown permission " + name);
5587
5588                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5589            } else {
5590                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5591                //
5592                // Also update
5593                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5594                // - metrics_constants.proto
5595                throw new IllegalStateException("Unknown permission " + name);
5596            }
5597        }
5598
5599        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5600    }
5601
5602    /**
5603     * Log that a permission was revoked.
5604     *
5605     * @param context Context of the caller
5606     * @param name name of the permission
5607     * @param packageName package permission if for
5608     */
5609    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5610            @NonNull String packageName) {
5611        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5612    }
5613
5614    /**
5615     * Log that a permission request was granted.
5616     *
5617     * @param context Context of the caller
5618     * @param name name of the permission
5619     * @param packageName package permission if for
5620     */
5621    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5622            @NonNull String packageName) {
5623        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5624    }
5625
5626    @Override
5627    public void resetRuntimePermissions() {
5628        mContext.enforceCallingOrSelfPermission(
5629                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5630                "revokeRuntimePermission");
5631
5632        int callingUid = Binder.getCallingUid();
5633        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5634            mContext.enforceCallingOrSelfPermission(
5635                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5636                    "resetRuntimePermissions");
5637        }
5638
5639        synchronized (mPackages) {
5640            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5641            for (int userId : UserManagerService.getInstance().getUserIds()) {
5642                final int packageCount = mPackages.size();
5643                for (int i = 0; i < packageCount; i++) {
5644                    PackageParser.Package pkg = mPackages.valueAt(i);
5645                    if (!(pkg.mExtras instanceof PackageSetting)) {
5646                        continue;
5647                    }
5648                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5649                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5650                }
5651            }
5652        }
5653    }
5654
5655    @Override
5656    public int getPermissionFlags(String name, String packageName, int userId) {
5657        if (!sUserManager.exists(userId)) {
5658            return 0;
5659        }
5660
5661        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5662
5663        final int callingUid = Binder.getCallingUid();
5664        enforceCrossUserPermission(callingUid, userId,
5665                true /* requireFullPermission */, false /* checkShell */,
5666                "getPermissionFlags");
5667
5668        synchronized (mPackages) {
5669            final PackageParser.Package pkg = mPackages.get(packageName);
5670            if (pkg == null) {
5671                return 0;
5672            }
5673            final BasePermission bp = mSettings.mPermissions.get(name);
5674            if (bp == null) {
5675                return 0;
5676            }
5677            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5678            if (ps == null
5679                    || filterAppAccessLPr(ps, callingUid, userId)) {
5680                return 0;
5681            }
5682            PermissionsState permissionsState = ps.getPermissionsState();
5683            return permissionsState.getPermissionFlags(name, userId);
5684        }
5685    }
5686
5687    @Override
5688    public void updatePermissionFlags(String name, String packageName, int flagMask,
5689            int flagValues, int userId) {
5690        if (!sUserManager.exists(userId)) {
5691            return;
5692        }
5693
5694        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5695
5696        final int callingUid = Binder.getCallingUid();
5697        enforceCrossUserPermission(callingUid, userId,
5698                true /* requireFullPermission */, true /* checkShell */,
5699                "updatePermissionFlags");
5700
5701        // Only the system can change these flags and nothing else.
5702        if (getCallingUid() != Process.SYSTEM_UID) {
5703            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5704            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5705            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5706            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5707            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5708        }
5709
5710        synchronized (mPackages) {
5711            final PackageParser.Package pkg = mPackages.get(packageName);
5712            if (pkg == null) {
5713                throw new IllegalArgumentException("Unknown package: " + packageName);
5714            }
5715            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5716            if (ps == null
5717                    || filterAppAccessLPr(ps, callingUid, userId)) {
5718                throw new IllegalArgumentException("Unknown package: " + packageName);
5719            }
5720
5721            final BasePermission bp = mSettings.mPermissions.get(name);
5722            if (bp == null) {
5723                throw new IllegalArgumentException("Unknown permission: " + name);
5724            }
5725
5726            PermissionsState permissionsState = ps.getPermissionsState();
5727
5728            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5729
5730            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5731                // Install and runtime permissions are stored in different places,
5732                // so figure out what permission changed and persist the change.
5733                if (permissionsState.getInstallPermissionState(name) != null) {
5734                    scheduleWriteSettingsLocked();
5735                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5736                        || hadState) {
5737                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5738                }
5739            }
5740        }
5741    }
5742
5743    /**
5744     * Update the permission flags for all packages and runtime permissions of a user in order
5745     * to allow device or profile owner to remove POLICY_FIXED.
5746     */
5747    @Override
5748    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5749        if (!sUserManager.exists(userId)) {
5750            return;
5751        }
5752
5753        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5754
5755        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5756                true /* requireFullPermission */, true /* checkShell */,
5757                "updatePermissionFlagsForAllApps");
5758
5759        // Only the system can change system fixed flags.
5760        if (getCallingUid() != Process.SYSTEM_UID) {
5761            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5762            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5763        }
5764
5765        synchronized (mPackages) {
5766            boolean changed = false;
5767            final int packageCount = mPackages.size();
5768            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5769                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5770                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5771                if (ps == null) {
5772                    continue;
5773                }
5774                PermissionsState permissionsState = ps.getPermissionsState();
5775                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5776                        userId, flagMask, flagValues);
5777            }
5778            if (changed) {
5779                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5780            }
5781        }
5782    }
5783
5784    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5785        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5786                != PackageManager.PERMISSION_GRANTED
5787            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5788                != PackageManager.PERMISSION_GRANTED) {
5789            throw new SecurityException(message + " requires "
5790                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5791                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5792        }
5793    }
5794
5795    @Override
5796    public boolean shouldShowRequestPermissionRationale(String permissionName,
5797            String packageName, int userId) {
5798        if (UserHandle.getCallingUserId() != userId) {
5799            mContext.enforceCallingPermission(
5800                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5801                    "canShowRequestPermissionRationale for user " + userId);
5802        }
5803
5804        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5805        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5806            return false;
5807        }
5808
5809        if (checkPermission(permissionName, packageName, userId)
5810                == PackageManager.PERMISSION_GRANTED) {
5811            return false;
5812        }
5813
5814        final int flags;
5815
5816        final long identity = Binder.clearCallingIdentity();
5817        try {
5818            flags = getPermissionFlags(permissionName,
5819                    packageName, userId);
5820        } finally {
5821            Binder.restoreCallingIdentity(identity);
5822        }
5823
5824        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5825                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5826                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5827
5828        if ((flags & fixedFlags) != 0) {
5829            return false;
5830        }
5831
5832        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5833    }
5834
5835    @Override
5836    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5837        mContext.enforceCallingOrSelfPermission(
5838                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5839                "addOnPermissionsChangeListener");
5840
5841        synchronized (mPackages) {
5842            mOnPermissionChangeListeners.addListenerLocked(listener);
5843        }
5844    }
5845
5846    @Override
5847    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5848        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5849            throw new SecurityException("Instant applications don't have access to this method");
5850        }
5851        synchronized (mPackages) {
5852            mOnPermissionChangeListeners.removeListenerLocked(listener);
5853        }
5854    }
5855
5856    @Override
5857    public boolean isProtectedBroadcast(String actionName) {
5858        // allow instant applications
5859        synchronized (mPackages) {
5860            if (mProtectedBroadcasts.contains(actionName)) {
5861                return true;
5862            } else if (actionName != null) {
5863                // TODO: remove these terrible hacks
5864                if (actionName.startsWith("android.net.netmon.lingerExpired")
5865                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5866                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5867                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5868                    return true;
5869                }
5870            }
5871        }
5872        return false;
5873    }
5874
5875    @Override
5876    public int checkSignatures(String pkg1, String pkg2) {
5877        synchronized (mPackages) {
5878            final PackageParser.Package p1 = mPackages.get(pkg1);
5879            final PackageParser.Package p2 = mPackages.get(pkg2);
5880            if (p1 == null || p1.mExtras == null
5881                    || p2 == null || p2.mExtras == null) {
5882                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5883            }
5884            final int callingUid = Binder.getCallingUid();
5885            final int callingUserId = UserHandle.getUserId(callingUid);
5886            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5887            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5888            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5889                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5890                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5891            }
5892            return compareSignatures(p1.mSignatures, p2.mSignatures);
5893        }
5894    }
5895
5896    @Override
5897    public int checkUidSignatures(int uid1, int uid2) {
5898        final int callingUid = Binder.getCallingUid();
5899        final int callingUserId = UserHandle.getUserId(callingUid);
5900        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5901        // Map to base uids.
5902        uid1 = UserHandle.getAppId(uid1);
5903        uid2 = UserHandle.getAppId(uid2);
5904        // reader
5905        synchronized (mPackages) {
5906            Signature[] s1;
5907            Signature[] s2;
5908            Object obj = mSettings.getUserIdLPr(uid1);
5909            if (obj != null) {
5910                if (obj instanceof SharedUserSetting) {
5911                    if (isCallerInstantApp) {
5912                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5913                    }
5914                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5915                } else if (obj instanceof PackageSetting) {
5916                    final PackageSetting ps = (PackageSetting) obj;
5917                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5918                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5919                    }
5920                    s1 = ps.signatures.mSignatures;
5921                } else {
5922                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5923                }
5924            } else {
5925                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5926            }
5927            obj = mSettings.getUserIdLPr(uid2);
5928            if (obj != null) {
5929                if (obj instanceof SharedUserSetting) {
5930                    if (isCallerInstantApp) {
5931                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5932                    }
5933                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5934                } else if (obj instanceof PackageSetting) {
5935                    final PackageSetting ps = (PackageSetting) obj;
5936                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5937                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5938                    }
5939                    s2 = ps.signatures.mSignatures;
5940                } else {
5941                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5942                }
5943            } else {
5944                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5945            }
5946            return compareSignatures(s1, s2);
5947        }
5948    }
5949
5950    /**
5951     * This method should typically only be used when granting or revoking
5952     * permissions, since the app may immediately restart after this call.
5953     * <p>
5954     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5955     * guard your work against the app being relaunched.
5956     */
5957    private void killUid(int appId, int userId, String reason) {
5958        final long identity = Binder.clearCallingIdentity();
5959        try {
5960            IActivityManager am = ActivityManager.getService();
5961            if (am != null) {
5962                try {
5963                    am.killUid(appId, userId, reason);
5964                } catch (RemoteException e) {
5965                    /* ignore - same process */
5966                }
5967            }
5968        } finally {
5969            Binder.restoreCallingIdentity(identity);
5970        }
5971    }
5972
5973    /**
5974     * Compares two sets of signatures. Returns:
5975     * <br />
5976     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5977     * <br />
5978     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5979     * <br />
5980     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5981     * <br />
5982     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5983     * <br />
5984     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5985     */
5986    static int compareSignatures(Signature[] s1, Signature[] s2) {
5987        if (s1 == null) {
5988            return s2 == null
5989                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5990                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5991        }
5992
5993        if (s2 == null) {
5994            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5995        }
5996
5997        if (s1.length != s2.length) {
5998            return PackageManager.SIGNATURE_NO_MATCH;
5999        }
6000
6001        // Since both signature sets are of size 1, we can compare without HashSets.
6002        if (s1.length == 1) {
6003            return s1[0].equals(s2[0]) ?
6004                    PackageManager.SIGNATURE_MATCH :
6005                    PackageManager.SIGNATURE_NO_MATCH;
6006        }
6007
6008        ArraySet<Signature> set1 = new ArraySet<Signature>();
6009        for (Signature sig : s1) {
6010            set1.add(sig);
6011        }
6012        ArraySet<Signature> set2 = new ArraySet<Signature>();
6013        for (Signature sig : s2) {
6014            set2.add(sig);
6015        }
6016        // Make sure s2 contains all signatures in s1.
6017        if (set1.equals(set2)) {
6018            return PackageManager.SIGNATURE_MATCH;
6019        }
6020        return PackageManager.SIGNATURE_NO_MATCH;
6021    }
6022
6023    /**
6024     * If the database version for this type of package (internal storage or
6025     * external storage) is less than the version where package signatures
6026     * were updated, return true.
6027     */
6028    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6029        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6030        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6031    }
6032
6033    /**
6034     * Used for backward compatibility to make sure any packages with
6035     * certificate chains get upgraded to the new style. {@code existingSigs}
6036     * will be in the old format (since they were stored on disk from before the
6037     * system upgrade) and {@code scannedSigs} will be in the newer format.
6038     */
6039    private int compareSignaturesCompat(PackageSignatures existingSigs,
6040            PackageParser.Package scannedPkg) {
6041        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6042            return PackageManager.SIGNATURE_NO_MATCH;
6043        }
6044
6045        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6046        for (Signature sig : existingSigs.mSignatures) {
6047            existingSet.add(sig);
6048        }
6049        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6050        for (Signature sig : scannedPkg.mSignatures) {
6051            try {
6052                Signature[] chainSignatures = sig.getChainSignatures();
6053                for (Signature chainSig : chainSignatures) {
6054                    scannedCompatSet.add(chainSig);
6055                }
6056            } catch (CertificateEncodingException e) {
6057                scannedCompatSet.add(sig);
6058            }
6059        }
6060        /*
6061         * Make sure the expanded scanned set contains all signatures in the
6062         * existing one.
6063         */
6064        if (scannedCompatSet.equals(existingSet)) {
6065            // Migrate the old signatures to the new scheme.
6066            existingSigs.assignSignatures(scannedPkg.mSignatures);
6067            // The new KeySets will be re-added later in the scanning process.
6068            synchronized (mPackages) {
6069                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6070            }
6071            return PackageManager.SIGNATURE_MATCH;
6072        }
6073        return PackageManager.SIGNATURE_NO_MATCH;
6074    }
6075
6076    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6077        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6078        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6079    }
6080
6081    private int compareSignaturesRecover(PackageSignatures existingSigs,
6082            PackageParser.Package scannedPkg) {
6083        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6084            return PackageManager.SIGNATURE_NO_MATCH;
6085        }
6086
6087        String msg = null;
6088        try {
6089            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6090                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6091                        + scannedPkg.packageName);
6092                return PackageManager.SIGNATURE_MATCH;
6093            }
6094        } catch (CertificateException e) {
6095            msg = e.getMessage();
6096        }
6097
6098        logCriticalInfo(Log.INFO,
6099                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6100        return PackageManager.SIGNATURE_NO_MATCH;
6101    }
6102
6103    @Override
6104    public List<String> getAllPackages() {
6105        final int callingUid = Binder.getCallingUid();
6106        final int callingUserId = UserHandle.getUserId(callingUid);
6107        synchronized (mPackages) {
6108            if (canViewInstantApps(callingUid, callingUserId)) {
6109                return new ArrayList<String>(mPackages.keySet());
6110            }
6111            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6112            final List<String> result = new ArrayList<>();
6113            if (instantAppPkgName != null) {
6114                // caller is an instant application; filter unexposed applications
6115                for (PackageParser.Package pkg : mPackages.values()) {
6116                    if (!pkg.visibleToInstantApps) {
6117                        continue;
6118                    }
6119                    result.add(pkg.packageName);
6120                }
6121            } else {
6122                // caller is a normal application; filter instant applications
6123                for (PackageParser.Package pkg : mPackages.values()) {
6124                    final PackageSetting ps =
6125                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6126                    if (ps != null
6127                            && ps.getInstantApp(callingUserId)
6128                            && !mInstantAppRegistry.isInstantAccessGranted(
6129                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6130                        continue;
6131                    }
6132                    result.add(pkg.packageName);
6133                }
6134            }
6135            return result;
6136        }
6137    }
6138
6139    @Override
6140    public String[] getPackagesForUid(int uid) {
6141        final int callingUid = Binder.getCallingUid();
6142        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6143        final int userId = UserHandle.getUserId(uid);
6144        uid = UserHandle.getAppId(uid);
6145        // reader
6146        synchronized (mPackages) {
6147            Object obj = mSettings.getUserIdLPr(uid);
6148            if (obj instanceof SharedUserSetting) {
6149                if (isCallerInstantApp) {
6150                    return null;
6151                }
6152                final SharedUserSetting sus = (SharedUserSetting) obj;
6153                final int N = sus.packages.size();
6154                String[] res = new String[N];
6155                final Iterator<PackageSetting> it = sus.packages.iterator();
6156                int i = 0;
6157                while (it.hasNext()) {
6158                    PackageSetting ps = it.next();
6159                    if (ps.getInstalled(userId)) {
6160                        res[i++] = ps.name;
6161                    } else {
6162                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6163                    }
6164                }
6165                return res;
6166            } else if (obj instanceof PackageSetting) {
6167                final PackageSetting ps = (PackageSetting) obj;
6168                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6169                    return new String[]{ps.name};
6170                }
6171            }
6172        }
6173        return null;
6174    }
6175
6176    @Override
6177    public String getNameForUid(int uid) {
6178        final int callingUid = Binder.getCallingUid();
6179        if (getInstantAppPackageName(callingUid) != null) {
6180            return null;
6181        }
6182        synchronized (mPackages) {
6183            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6184            if (obj instanceof SharedUserSetting) {
6185                final SharedUserSetting sus = (SharedUserSetting) obj;
6186                return sus.name + ":" + sus.userId;
6187            } else if (obj instanceof PackageSetting) {
6188                final PackageSetting ps = (PackageSetting) obj;
6189                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6190                    return null;
6191                }
6192                return ps.name;
6193            }
6194        }
6195        return null;
6196    }
6197
6198    @Override
6199    public int getUidForSharedUser(String sharedUserName) {
6200        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6201            return -1;
6202        }
6203        if (sharedUserName == null) {
6204            return -1;
6205        }
6206        // reader
6207        synchronized (mPackages) {
6208            SharedUserSetting suid;
6209            try {
6210                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6211                if (suid != null) {
6212                    return suid.userId;
6213                }
6214            } catch (PackageManagerException ignore) {
6215                // can't happen, but, still need to catch it
6216            }
6217            return -1;
6218        }
6219    }
6220
6221    @Override
6222    public int getFlagsForUid(int uid) {
6223        final int callingUid = Binder.getCallingUid();
6224        if (getInstantAppPackageName(callingUid) != null) {
6225            return 0;
6226        }
6227        synchronized (mPackages) {
6228            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6229            if (obj instanceof SharedUserSetting) {
6230                final SharedUserSetting sus = (SharedUserSetting) obj;
6231                return sus.pkgFlags;
6232            } else if (obj instanceof PackageSetting) {
6233                final PackageSetting ps = (PackageSetting) obj;
6234                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6235                    return 0;
6236                }
6237                return ps.pkgFlags;
6238            }
6239        }
6240        return 0;
6241    }
6242
6243    @Override
6244    public int getPrivateFlagsForUid(int uid) {
6245        final int callingUid = Binder.getCallingUid();
6246        if (getInstantAppPackageName(callingUid) != null) {
6247            return 0;
6248        }
6249        synchronized (mPackages) {
6250            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6251            if (obj instanceof SharedUserSetting) {
6252                final SharedUserSetting sus = (SharedUserSetting) obj;
6253                return sus.pkgPrivateFlags;
6254            } else if (obj instanceof PackageSetting) {
6255                final PackageSetting ps = (PackageSetting) obj;
6256                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6257                    return 0;
6258                }
6259                return ps.pkgPrivateFlags;
6260            }
6261        }
6262        return 0;
6263    }
6264
6265    @Override
6266    public boolean isUidPrivileged(int uid) {
6267        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6268            return false;
6269        }
6270        uid = UserHandle.getAppId(uid);
6271        // reader
6272        synchronized (mPackages) {
6273            Object obj = mSettings.getUserIdLPr(uid);
6274            if (obj instanceof SharedUserSetting) {
6275                final SharedUserSetting sus = (SharedUserSetting) obj;
6276                final Iterator<PackageSetting> it = sus.packages.iterator();
6277                while (it.hasNext()) {
6278                    if (it.next().isPrivileged()) {
6279                        return true;
6280                    }
6281                }
6282            } else if (obj instanceof PackageSetting) {
6283                final PackageSetting ps = (PackageSetting) obj;
6284                return ps.isPrivileged();
6285            }
6286        }
6287        return false;
6288    }
6289
6290    @Override
6291    public String[] getAppOpPermissionPackages(String permissionName) {
6292        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6293            return null;
6294        }
6295        synchronized (mPackages) {
6296            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6297            if (pkgs == null) {
6298                return null;
6299            }
6300            return pkgs.toArray(new String[pkgs.size()]);
6301        }
6302    }
6303
6304    @Override
6305    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6306            int flags, int userId) {
6307        return resolveIntentInternal(
6308                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6309    }
6310
6311    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6312            int flags, int userId, boolean resolveForStart) {
6313        try {
6314            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6315
6316            if (!sUserManager.exists(userId)) return null;
6317            final int callingUid = Binder.getCallingUid();
6318            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6319            enforceCrossUserPermission(callingUid, userId,
6320                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6321
6322            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6323            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6324                    flags, callingUid, userId, resolveForStart);
6325            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6326
6327            final ResolveInfo bestChoice =
6328                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6329            return bestChoice;
6330        } finally {
6331            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6332        }
6333    }
6334
6335    @Override
6336    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6337        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6338            throw new SecurityException(
6339                    "findPersistentPreferredActivity can only be run by the system");
6340        }
6341        if (!sUserManager.exists(userId)) {
6342            return null;
6343        }
6344        final int callingUid = Binder.getCallingUid();
6345        intent = updateIntentForResolve(intent);
6346        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6347        final int flags = updateFlagsForResolve(
6348                0, userId, intent, callingUid, false /*includeInstantApps*/);
6349        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6350                userId);
6351        synchronized (mPackages) {
6352            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6353                    userId);
6354        }
6355    }
6356
6357    @Override
6358    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6359            IntentFilter filter, int match, ComponentName activity) {
6360        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6361            return;
6362        }
6363        final int userId = UserHandle.getCallingUserId();
6364        if (DEBUG_PREFERRED) {
6365            Log.v(TAG, "setLastChosenActivity intent=" + intent
6366                + " resolvedType=" + resolvedType
6367                + " flags=" + flags
6368                + " filter=" + filter
6369                + " match=" + match
6370                + " activity=" + activity);
6371            filter.dump(new PrintStreamPrinter(System.out), "    ");
6372        }
6373        intent.setComponent(null);
6374        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6375                userId);
6376        // Find any earlier preferred or last chosen entries and nuke them
6377        findPreferredActivity(intent, resolvedType,
6378                flags, query, 0, false, true, false, userId);
6379        // Add the new activity as the last chosen for this filter
6380        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6381                "Setting last chosen");
6382    }
6383
6384    @Override
6385    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6386        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6387            return null;
6388        }
6389        final int userId = UserHandle.getCallingUserId();
6390        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6391        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6392                userId);
6393        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6394                false, false, false, userId);
6395    }
6396
6397    /**
6398     * Returns whether or not instant apps have been disabled remotely.
6399     */
6400    private boolean isEphemeralDisabled() {
6401        return mEphemeralAppsDisabled;
6402    }
6403
6404    private boolean isInstantAppAllowed(
6405            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6406            boolean skipPackageCheck) {
6407        if (mInstantAppResolverConnection == null) {
6408            return false;
6409        }
6410        if (mInstantAppInstallerActivity == null) {
6411            return false;
6412        }
6413        if (intent.getComponent() != null) {
6414            return false;
6415        }
6416        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6417            return false;
6418        }
6419        if (!skipPackageCheck && intent.getPackage() != null) {
6420            return false;
6421        }
6422        final boolean isWebUri = hasWebURI(intent);
6423        if (!isWebUri || intent.getData().getHost() == null) {
6424            return false;
6425        }
6426        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6427        // Or if there's already an ephemeral app installed that handles the action
6428        synchronized (mPackages) {
6429            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6430            for (int n = 0; n < count; n++) {
6431                final ResolveInfo info = resolvedActivities.get(n);
6432                final String packageName = info.activityInfo.packageName;
6433                final PackageSetting ps = mSettings.mPackages.get(packageName);
6434                if (ps != null) {
6435                    // only check domain verification status if the app is not a browser
6436                    if (!info.handleAllWebDataURI) {
6437                        // Try to get the status from User settings first
6438                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6439                        final int status = (int) (packedStatus >> 32);
6440                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6441                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6442                            if (DEBUG_EPHEMERAL) {
6443                                Slog.v(TAG, "DENY instant app;"
6444                                    + " pkg: " + packageName + ", status: " + status);
6445                            }
6446                            return false;
6447                        }
6448                    }
6449                    if (ps.getInstantApp(userId)) {
6450                        if (DEBUG_EPHEMERAL) {
6451                            Slog.v(TAG, "DENY instant app installed;"
6452                                    + " pkg: " + packageName);
6453                        }
6454                        return false;
6455                    }
6456                }
6457            }
6458        }
6459        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6460        return true;
6461    }
6462
6463    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6464            Intent origIntent, String resolvedType, String callingPackage,
6465            Bundle verificationBundle, int userId) {
6466        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6467                new InstantAppRequest(responseObj, origIntent, resolvedType,
6468                        callingPackage, userId, verificationBundle));
6469        mHandler.sendMessage(msg);
6470    }
6471
6472    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6473            int flags, List<ResolveInfo> query, int userId) {
6474        if (query != null) {
6475            final int N = query.size();
6476            if (N == 1) {
6477                return query.get(0);
6478            } else if (N > 1) {
6479                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6480                // If there is more than one activity with the same priority,
6481                // then let the user decide between them.
6482                ResolveInfo r0 = query.get(0);
6483                ResolveInfo r1 = query.get(1);
6484                if (DEBUG_INTENT_MATCHING || debug) {
6485                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6486                            + r1.activityInfo.name + "=" + r1.priority);
6487                }
6488                // If the first activity has a higher priority, or a different
6489                // default, then it is always desirable to pick it.
6490                if (r0.priority != r1.priority
6491                        || r0.preferredOrder != r1.preferredOrder
6492                        || r0.isDefault != r1.isDefault) {
6493                    return query.get(0);
6494                }
6495                // If we have saved a preference for a preferred activity for
6496                // this Intent, use that.
6497                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6498                        flags, query, r0.priority, true, false, debug, userId);
6499                if (ri != null) {
6500                    return ri;
6501                }
6502                // If we have an ephemeral app, use it
6503                for (int i = 0; i < N; i++) {
6504                    ri = query.get(i);
6505                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6506                        final String packageName = ri.activityInfo.packageName;
6507                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6508                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6509                        final int status = (int)(packedStatus >> 32);
6510                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6511                            return ri;
6512                        }
6513                    }
6514                }
6515                ri = new ResolveInfo(mResolveInfo);
6516                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6517                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6518                // If all of the options come from the same package, show the application's
6519                // label and icon instead of the generic resolver's.
6520                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6521                // and then throw away the ResolveInfo itself, meaning that the caller loses
6522                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6523                // a fallback for this case; we only set the target package's resources on
6524                // the ResolveInfo, not the ActivityInfo.
6525                final String intentPackage = intent.getPackage();
6526                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6527                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6528                    ri.resolvePackageName = intentPackage;
6529                    if (userNeedsBadging(userId)) {
6530                        ri.noResourceId = true;
6531                    } else {
6532                        ri.icon = appi.icon;
6533                    }
6534                    ri.iconResourceId = appi.icon;
6535                    ri.labelRes = appi.labelRes;
6536                }
6537                ri.activityInfo.applicationInfo = new ApplicationInfo(
6538                        ri.activityInfo.applicationInfo);
6539                if (userId != 0) {
6540                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6541                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6542                }
6543                // Make sure that the resolver is displayable in car mode
6544                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6545                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6546                return ri;
6547            }
6548        }
6549        return null;
6550    }
6551
6552    /**
6553     * Return true if the given list is not empty and all of its contents have
6554     * an activityInfo with the given package name.
6555     */
6556    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6557        if (ArrayUtils.isEmpty(list)) {
6558            return false;
6559        }
6560        for (int i = 0, N = list.size(); i < N; i++) {
6561            final ResolveInfo ri = list.get(i);
6562            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6563            if (ai == null || !packageName.equals(ai.packageName)) {
6564                return false;
6565            }
6566        }
6567        return true;
6568    }
6569
6570    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6571            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6572        final int N = query.size();
6573        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6574                .get(userId);
6575        // Get the list of persistent preferred activities that handle the intent
6576        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6577        List<PersistentPreferredActivity> pprefs = ppir != null
6578                ? ppir.queryIntent(intent, resolvedType,
6579                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6580                        userId)
6581                : null;
6582        if (pprefs != null && pprefs.size() > 0) {
6583            final int M = pprefs.size();
6584            for (int i=0; i<M; i++) {
6585                final PersistentPreferredActivity ppa = pprefs.get(i);
6586                if (DEBUG_PREFERRED || debug) {
6587                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6588                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6589                            + "\n  component=" + ppa.mComponent);
6590                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6591                }
6592                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6593                        flags | MATCH_DISABLED_COMPONENTS, userId);
6594                if (DEBUG_PREFERRED || debug) {
6595                    Slog.v(TAG, "Found persistent preferred activity:");
6596                    if (ai != null) {
6597                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6598                    } else {
6599                        Slog.v(TAG, "  null");
6600                    }
6601                }
6602                if (ai == null) {
6603                    // This previously registered persistent preferred activity
6604                    // component is no longer known. Ignore it and do NOT remove it.
6605                    continue;
6606                }
6607                for (int j=0; j<N; j++) {
6608                    final ResolveInfo ri = query.get(j);
6609                    if (!ri.activityInfo.applicationInfo.packageName
6610                            .equals(ai.applicationInfo.packageName)) {
6611                        continue;
6612                    }
6613                    if (!ri.activityInfo.name.equals(ai.name)) {
6614                        continue;
6615                    }
6616                    //  Found a persistent preference that can handle the intent.
6617                    if (DEBUG_PREFERRED || debug) {
6618                        Slog.v(TAG, "Returning persistent preferred activity: " +
6619                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6620                    }
6621                    return ri;
6622                }
6623            }
6624        }
6625        return null;
6626    }
6627
6628    // TODO: handle preferred activities missing while user has amnesia
6629    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6630            List<ResolveInfo> query, int priority, boolean always,
6631            boolean removeMatches, boolean debug, int userId) {
6632        if (!sUserManager.exists(userId)) return null;
6633        final int callingUid = Binder.getCallingUid();
6634        flags = updateFlagsForResolve(
6635                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6636        intent = updateIntentForResolve(intent);
6637        // writer
6638        synchronized (mPackages) {
6639            // Try to find a matching persistent preferred activity.
6640            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6641                    debug, userId);
6642
6643            // If a persistent preferred activity matched, use it.
6644            if (pri != null) {
6645                return pri;
6646            }
6647
6648            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6649            // Get the list of preferred activities that handle the intent
6650            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6651            List<PreferredActivity> prefs = pir != null
6652                    ? pir.queryIntent(intent, resolvedType,
6653                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6654                            userId)
6655                    : null;
6656            if (prefs != null && prefs.size() > 0) {
6657                boolean changed = false;
6658                try {
6659                    // First figure out how good the original match set is.
6660                    // We will only allow preferred activities that came
6661                    // from the same match quality.
6662                    int match = 0;
6663
6664                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6665
6666                    final int N = query.size();
6667                    for (int j=0; j<N; j++) {
6668                        final ResolveInfo ri = query.get(j);
6669                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6670                                + ": 0x" + Integer.toHexString(match));
6671                        if (ri.match > match) {
6672                            match = ri.match;
6673                        }
6674                    }
6675
6676                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6677                            + Integer.toHexString(match));
6678
6679                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6680                    final int M = prefs.size();
6681                    for (int i=0; i<M; i++) {
6682                        final PreferredActivity pa = prefs.get(i);
6683                        if (DEBUG_PREFERRED || debug) {
6684                            Slog.v(TAG, "Checking PreferredActivity ds="
6685                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6686                                    + "\n  component=" + pa.mPref.mComponent);
6687                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6688                        }
6689                        if (pa.mPref.mMatch != match) {
6690                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6691                                    + Integer.toHexString(pa.mPref.mMatch));
6692                            continue;
6693                        }
6694                        // If it's not an "always" type preferred activity and that's what we're
6695                        // looking for, skip it.
6696                        if (always && !pa.mPref.mAlways) {
6697                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6698                            continue;
6699                        }
6700                        final ActivityInfo ai = getActivityInfo(
6701                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6702                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6703                                userId);
6704                        if (DEBUG_PREFERRED || debug) {
6705                            Slog.v(TAG, "Found preferred activity:");
6706                            if (ai != null) {
6707                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6708                            } else {
6709                                Slog.v(TAG, "  null");
6710                            }
6711                        }
6712                        if (ai == null) {
6713                            // This previously registered preferred activity
6714                            // component is no longer known.  Most likely an update
6715                            // to the app was installed and in the new version this
6716                            // component no longer exists.  Clean it up by removing
6717                            // it from the preferred activities list, and skip it.
6718                            Slog.w(TAG, "Removing dangling preferred activity: "
6719                                    + pa.mPref.mComponent);
6720                            pir.removeFilter(pa);
6721                            changed = true;
6722                            continue;
6723                        }
6724                        for (int j=0; j<N; j++) {
6725                            final ResolveInfo ri = query.get(j);
6726                            if (!ri.activityInfo.applicationInfo.packageName
6727                                    .equals(ai.applicationInfo.packageName)) {
6728                                continue;
6729                            }
6730                            if (!ri.activityInfo.name.equals(ai.name)) {
6731                                continue;
6732                            }
6733
6734                            if (removeMatches) {
6735                                pir.removeFilter(pa);
6736                                changed = true;
6737                                if (DEBUG_PREFERRED) {
6738                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6739                                }
6740                                break;
6741                            }
6742
6743                            // Okay we found a previously set preferred or last chosen app.
6744                            // If the result set is different from when this
6745                            // was created, we need to clear it and re-ask the
6746                            // user their preference, if we're looking for an "always" type entry.
6747                            if (always && !pa.mPref.sameSet(query)) {
6748                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6749                                        + intent + " type " + resolvedType);
6750                                if (DEBUG_PREFERRED) {
6751                                    Slog.v(TAG, "Removing preferred activity since set changed "
6752                                            + pa.mPref.mComponent);
6753                                }
6754                                pir.removeFilter(pa);
6755                                // Re-add the filter as a "last chosen" entry (!always)
6756                                PreferredActivity lastChosen = new PreferredActivity(
6757                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6758                                pir.addFilter(lastChosen);
6759                                changed = true;
6760                                return null;
6761                            }
6762
6763                            // Yay! Either the set matched or we're looking for the last chosen
6764                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6765                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6766                            return ri;
6767                        }
6768                    }
6769                } finally {
6770                    if (changed) {
6771                        if (DEBUG_PREFERRED) {
6772                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6773                        }
6774                        scheduleWritePackageRestrictionsLocked(userId);
6775                    }
6776                }
6777            }
6778        }
6779        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6780        return null;
6781    }
6782
6783    /*
6784     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6785     */
6786    @Override
6787    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6788            int targetUserId) {
6789        mContext.enforceCallingOrSelfPermission(
6790                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6791        List<CrossProfileIntentFilter> matches =
6792                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6793        if (matches != null) {
6794            int size = matches.size();
6795            for (int i = 0; i < size; i++) {
6796                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6797            }
6798        }
6799        if (hasWebURI(intent)) {
6800            // cross-profile app linking works only towards the parent.
6801            final int callingUid = Binder.getCallingUid();
6802            final UserInfo parent = getProfileParent(sourceUserId);
6803            synchronized(mPackages) {
6804                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6805                        false /*includeInstantApps*/);
6806                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6807                        intent, resolvedType, flags, sourceUserId, parent.id);
6808                return xpDomainInfo != null;
6809            }
6810        }
6811        return false;
6812    }
6813
6814    private UserInfo getProfileParent(int userId) {
6815        final long identity = Binder.clearCallingIdentity();
6816        try {
6817            return sUserManager.getProfileParent(userId);
6818        } finally {
6819            Binder.restoreCallingIdentity(identity);
6820        }
6821    }
6822
6823    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6824            String resolvedType, int userId) {
6825        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6826        if (resolver != null) {
6827            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6828        }
6829        return null;
6830    }
6831
6832    @Override
6833    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6834            String resolvedType, int flags, int userId) {
6835        try {
6836            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6837
6838            return new ParceledListSlice<>(
6839                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6840        } finally {
6841            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6842        }
6843    }
6844
6845    /**
6846     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6847     * instant, returns {@code null}.
6848     */
6849    private String getInstantAppPackageName(int callingUid) {
6850        synchronized (mPackages) {
6851            // If the caller is an isolated app use the owner's uid for the lookup.
6852            if (Process.isIsolated(callingUid)) {
6853                callingUid = mIsolatedOwners.get(callingUid);
6854            }
6855            final int appId = UserHandle.getAppId(callingUid);
6856            final Object obj = mSettings.getUserIdLPr(appId);
6857            if (obj instanceof PackageSetting) {
6858                final PackageSetting ps = (PackageSetting) obj;
6859                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6860                return isInstantApp ? ps.pkg.packageName : null;
6861            }
6862        }
6863        return null;
6864    }
6865
6866    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6867            String resolvedType, int flags, int userId) {
6868        return queryIntentActivitiesInternal(
6869                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6870    }
6871
6872    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6873            String resolvedType, int flags, int filterCallingUid, int userId,
6874            boolean resolveForStart) {
6875        if (!sUserManager.exists(userId)) return Collections.emptyList();
6876        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6877        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6878                false /* requireFullPermission */, false /* checkShell */,
6879                "query intent activities");
6880        final String pkgName = intent.getPackage();
6881        ComponentName comp = intent.getComponent();
6882        if (comp == null) {
6883            if (intent.getSelector() != null) {
6884                intent = intent.getSelector();
6885                comp = intent.getComponent();
6886            }
6887        }
6888
6889        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6890                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6891        if (comp != null) {
6892            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6893            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6894            if (ai != null) {
6895                // When specifying an explicit component, we prevent the activity from being
6896                // used when either 1) the calling package is normal and the activity is within
6897                // an ephemeral application or 2) the calling package is ephemeral and the
6898                // activity is not visible to ephemeral applications.
6899                final boolean matchInstantApp =
6900                        (flags & PackageManager.MATCH_INSTANT) != 0;
6901                final boolean matchVisibleToInstantAppOnly =
6902                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6903                final boolean matchExplicitlyVisibleOnly =
6904                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6905                final boolean isCallerInstantApp =
6906                        instantAppPkgName != null;
6907                final boolean isTargetSameInstantApp =
6908                        comp.getPackageName().equals(instantAppPkgName);
6909                final boolean isTargetInstantApp =
6910                        (ai.applicationInfo.privateFlags
6911                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6912                final boolean isTargetVisibleToInstantApp =
6913                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6914                final boolean isTargetExplicitlyVisibleToInstantApp =
6915                        isTargetVisibleToInstantApp
6916                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6917                final boolean isTargetHiddenFromInstantApp =
6918                        !isTargetVisibleToInstantApp
6919                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6920                final boolean blockResolution =
6921                        !isTargetSameInstantApp
6922                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6923                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6924                                        && isTargetHiddenFromInstantApp));
6925                if (!blockResolution) {
6926                    final ResolveInfo ri = new ResolveInfo();
6927                    ri.activityInfo = ai;
6928                    list.add(ri);
6929                }
6930            }
6931            return applyPostResolutionFilter(list, instantAppPkgName);
6932        }
6933
6934        // reader
6935        boolean sortResult = false;
6936        boolean addEphemeral = false;
6937        List<ResolveInfo> result;
6938        final boolean ephemeralDisabled = isEphemeralDisabled();
6939        synchronized (mPackages) {
6940            if (pkgName == null) {
6941                List<CrossProfileIntentFilter> matchingFilters =
6942                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6943                // Check for results that need to skip the current profile.
6944                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6945                        resolvedType, flags, userId);
6946                if (xpResolveInfo != null) {
6947                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6948                    xpResult.add(xpResolveInfo);
6949                    return applyPostResolutionFilter(
6950                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6951                }
6952
6953                // Check for results in the current profile.
6954                result = filterIfNotSystemUser(mActivities.queryIntent(
6955                        intent, resolvedType, flags, userId), userId);
6956                addEphemeral = !ephemeralDisabled
6957                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6958                // Check for cross profile results.
6959                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6960                xpResolveInfo = queryCrossProfileIntents(
6961                        matchingFilters, intent, resolvedType, flags, userId,
6962                        hasNonNegativePriorityResult);
6963                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6964                    boolean isVisibleToUser = filterIfNotSystemUser(
6965                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6966                    if (isVisibleToUser) {
6967                        result.add(xpResolveInfo);
6968                        sortResult = true;
6969                    }
6970                }
6971                if (hasWebURI(intent)) {
6972                    CrossProfileDomainInfo xpDomainInfo = null;
6973                    final UserInfo parent = getProfileParent(userId);
6974                    if (parent != null) {
6975                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6976                                flags, userId, parent.id);
6977                    }
6978                    if (xpDomainInfo != null) {
6979                        if (xpResolveInfo != null) {
6980                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6981                            // in the result.
6982                            result.remove(xpResolveInfo);
6983                        }
6984                        if (result.size() == 0 && !addEphemeral) {
6985                            // No result in current profile, but found candidate in parent user.
6986                            // And we are not going to add emphemeral app, so we can return the
6987                            // result straight away.
6988                            result.add(xpDomainInfo.resolveInfo);
6989                            return applyPostResolutionFilter(result, instantAppPkgName);
6990                        }
6991                    } else if (result.size() <= 1 && !addEphemeral) {
6992                        // No result in parent user and <= 1 result in current profile, and we
6993                        // are not going to add emphemeral app, so we can return the result without
6994                        // further processing.
6995                        return applyPostResolutionFilter(result, instantAppPkgName);
6996                    }
6997                    // We have more than one candidate (combining results from current and parent
6998                    // profile), so we need filtering and sorting.
6999                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7000                            intent, flags, result, xpDomainInfo, userId);
7001                    sortResult = true;
7002                }
7003            } else {
7004                final PackageParser.Package pkg = mPackages.get(pkgName);
7005                result = null;
7006                if (pkg != null) {
7007                    result = filterIfNotSystemUser(
7008                            mActivities.queryIntentForPackage(
7009                                    intent, resolvedType, flags, pkg.activities, userId),
7010                            userId);
7011                }
7012                if (result == null || result.size() == 0) {
7013                    // the caller wants to resolve for a particular package; however, there
7014                    // were no installed results, so, try to find an ephemeral result
7015                    addEphemeral = !ephemeralDisabled
7016                            && isInstantAppAllowed(
7017                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7018                    if (result == null) {
7019                        result = new ArrayList<>();
7020                    }
7021                }
7022            }
7023        }
7024        if (addEphemeral) {
7025            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7026        }
7027        if (sortResult) {
7028            Collections.sort(result, mResolvePrioritySorter);
7029        }
7030        return applyPostResolutionFilter(result, instantAppPkgName);
7031    }
7032
7033    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7034            String resolvedType, int flags, int userId) {
7035        // first, check to see if we've got an instant app already installed
7036        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7037        ResolveInfo localInstantApp = null;
7038        boolean blockResolution = false;
7039        if (!alreadyResolvedLocally) {
7040            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7041                    flags
7042                        | PackageManager.GET_RESOLVED_FILTER
7043                        | PackageManager.MATCH_INSTANT
7044                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7045                    userId);
7046            for (int i = instantApps.size() - 1; i >= 0; --i) {
7047                final ResolveInfo info = instantApps.get(i);
7048                final String packageName = info.activityInfo.packageName;
7049                final PackageSetting ps = mSettings.mPackages.get(packageName);
7050                if (ps.getInstantApp(userId)) {
7051                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7052                    final int status = (int)(packedStatus >> 32);
7053                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7054                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7055                        // there's a local instant application installed, but, the user has
7056                        // chosen to never use it; skip resolution and don't acknowledge
7057                        // an instant application is even available
7058                        if (DEBUG_EPHEMERAL) {
7059                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7060                        }
7061                        blockResolution = true;
7062                        break;
7063                    } else {
7064                        // we have a locally installed instant application; skip resolution
7065                        // but acknowledge there's an instant application available
7066                        if (DEBUG_EPHEMERAL) {
7067                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7068                        }
7069                        localInstantApp = info;
7070                        break;
7071                    }
7072                }
7073            }
7074        }
7075        // no app installed, let's see if one's available
7076        AuxiliaryResolveInfo auxiliaryResponse = null;
7077        if (!blockResolution) {
7078            if (localInstantApp == null) {
7079                // we don't have an instant app locally, resolve externally
7080                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7081                final InstantAppRequest requestObject = new InstantAppRequest(
7082                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7083                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7084                auxiliaryResponse =
7085                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7086                                mContext, mInstantAppResolverConnection, requestObject);
7087                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7088            } else {
7089                // we have an instant application locally, but, we can't admit that since
7090                // callers shouldn't be able to determine prior browsing. create a dummy
7091                // auxiliary response so the downstream code behaves as if there's an
7092                // instant application available externally. when it comes time to start
7093                // the instant application, we'll do the right thing.
7094                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7095                auxiliaryResponse = new AuxiliaryResolveInfo(
7096                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7097            }
7098        }
7099        if (auxiliaryResponse != null) {
7100            if (DEBUG_EPHEMERAL) {
7101                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7102            }
7103            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7104            final PackageSetting ps =
7105                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7106            if (ps != null) {
7107                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7108                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7109                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7110                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7111                // make sure this resolver is the default
7112                ephemeralInstaller.isDefault = true;
7113                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7114                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7115                // add a non-generic filter
7116                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7117                ephemeralInstaller.filter.addDataPath(
7118                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7119                ephemeralInstaller.isInstantAppAvailable = true;
7120                result.add(ephemeralInstaller);
7121            }
7122        }
7123        return result;
7124    }
7125
7126    private static class CrossProfileDomainInfo {
7127        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7128        ResolveInfo resolveInfo;
7129        /* Best domain verification status of the activities found in the other profile */
7130        int bestDomainVerificationStatus;
7131    }
7132
7133    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7134            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7135        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7136                sourceUserId)) {
7137            return null;
7138        }
7139        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7140                resolvedType, flags, parentUserId);
7141
7142        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7143            return null;
7144        }
7145        CrossProfileDomainInfo result = null;
7146        int size = resultTargetUser.size();
7147        for (int i = 0; i < size; i++) {
7148            ResolveInfo riTargetUser = resultTargetUser.get(i);
7149            // Intent filter verification is only for filters that specify a host. So don't return
7150            // those that handle all web uris.
7151            if (riTargetUser.handleAllWebDataURI) {
7152                continue;
7153            }
7154            String packageName = riTargetUser.activityInfo.packageName;
7155            PackageSetting ps = mSettings.mPackages.get(packageName);
7156            if (ps == null) {
7157                continue;
7158            }
7159            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7160            int status = (int)(verificationState >> 32);
7161            if (result == null) {
7162                result = new CrossProfileDomainInfo();
7163                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7164                        sourceUserId, parentUserId);
7165                result.bestDomainVerificationStatus = status;
7166            } else {
7167                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7168                        result.bestDomainVerificationStatus);
7169            }
7170        }
7171        // Don't consider matches with status NEVER across profiles.
7172        if (result != null && result.bestDomainVerificationStatus
7173                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7174            return null;
7175        }
7176        return result;
7177    }
7178
7179    /**
7180     * Verification statuses are ordered from the worse to the best, except for
7181     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7182     */
7183    private int bestDomainVerificationStatus(int status1, int status2) {
7184        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7185            return status2;
7186        }
7187        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7188            return status1;
7189        }
7190        return (int) MathUtils.max(status1, status2);
7191    }
7192
7193    private boolean isUserEnabled(int userId) {
7194        long callingId = Binder.clearCallingIdentity();
7195        try {
7196            UserInfo userInfo = sUserManager.getUserInfo(userId);
7197            return userInfo != null && userInfo.isEnabled();
7198        } finally {
7199            Binder.restoreCallingIdentity(callingId);
7200        }
7201    }
7202
7203    /**
7204     * Filter out activities with systemUserOnly flag set, when current user is not System.
7205     *
7206     * @return filtered list
7207     */
7208    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7209        if (userId == UserHandle.USER_SYSTEM) {
7210            return resolveInfos;
7211        }
7212        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7213            ResolveInfo info = resolveInfos.get(i);
7214            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7215                resolveInfos.remove(i);
7216            }
7217        }
7218        return resolveInfos;
7219    }
7220
7221    /**
7222     * Filters out ephemeral activities.
7223     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7224     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7225     *
7226     * @param resolveInfos The pre-filtered list of resolved activities
7227     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7228     *          is performed.
7229     * @return A filtered list of resolved activities.
7230     */
7231    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7232            String ephemeralPkgName) {
7233        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7234            final ResolveInfo info = resolveInfos.get(i);
7235            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7236            // TODO: When adding on-demand split support for non-instant apps, remove this check
7237            // and always apply post filtering
7238            // allow activities that are defined in the provided package
7239            if (isEphemeralApp) {
7240                if (info.activityInfo.splitName != null
7241                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7242                                info.activityInfo.splitName)) {
7243                    // requested activity is defined in a split that hasn't been installed yet.
7244                    // add the installer to the resolve list
7245                    if (DEBUG_EPHEMERAL) {
7246                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7247                    }
7248                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7249                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7250                            info.activityInfo.packageName, info.activityInfo.splitName,
7251                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7252                    // make sure this resolver is the default
7253                    installerInfo.isDefault = true;
7254                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7255                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7256                    // add a non-generic filter
7257                    installerInfo.filter = new IntentFilter();
7258                    // load resources from the correct package
7259                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7260                    resolveInfos.set(i, installerInfo);
7261                    continue;
7262                }
7263            }
7264            // caller is a full app, don't need to apply any other filtering
7265            if (ephemeralPkgName == null) {
7266                continue;
7267            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7268                // caller is same app; don't need to apply any other filtering
7269                continue;
7270            }
7271            // allow activities that have been explicitly exposed to ephemeral apps
7272            if (!isEphemeralApp
7273                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7274                continue;
7275            }
7276            resolveInfos.remove(i);
7277        }
7278        return resolveInfos;
7279    }
7280
7281    /**
7282     * @param resolveInfos list of resolve infos in descending priority order
7283     * @return if the list contains a resolve info with non-negative priority
7284     */
7285    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7286        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7287    }
7288
7289    private static boolean hasWebURI(Intent intent) {
7290        if (intent.getData() == null) {
7291            return false;
7292        }
7293        final String scheme = intent.getScheme();
7294        if (TextUtils.isEmpty(scheme)) {
7295            return false;
7296        }
7297        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7298    }
7299
7300    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7301            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7302            int userId) {
7303        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7304
7305        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7306            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7307                    candidates.size());
7308        }
7309
7310        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7311        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7312        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7313        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7314        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7315        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7316
7317        synchronized (mPackages) {
7318            final int count = candidates.size();
7319            // First, try to use linked apps. Partition the candidates into four lists:
7320            // one for the final results, one for the "do not use ever", one for "undefined status"
7321            // and finally one for "browser app type".
7322            for (int n=0; n<count; n++) {
7323                ResolveInfo info = candidates.get(n);
7324                String packageName = info.activityInfo.packageName;
7325                PackageSetting ps = mSettings.mPackages.get(packageName);
7326                if (ps != null) {
7327                    // Add to the special match all list (Browser use case)
7328                    if (info.handleAllWebDataURI) {
7329                        matchAllList.add(info);
7330                        continue;
7331                    }
7332                    // Try to get the status from User settings first
7333                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7334                    int status = (int)(packedStatus >> 32);
7335                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7336                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7337                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7338                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7339                                    + " : linkgen=" + linkGeneration);
7340                        }
7341                        // Use link-enabled generation as preferredOrder, i.e.
7342                        // prefer newly-enabled over earlier-enabled.
7343                        info.preferredOrder = linkGeneration;
7344                        alwaysList.add(info);
7345                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7346                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7347                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7348                        }
7349                        neverList.add(info);
7350                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7351                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7352                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7353                        }
7354                        alwaysAskList.add(info);
7355                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7356                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7357                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7358                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7359                        }
7360                        undefinedList.add(info);
7361                    }
7362                }
7363            }
7364
7365            // We'll want to include browser possibilities in a few cases
7366            boolean includeBrowser = false;
7367
7368            // First try to add the "always" resolution(s) for the current user, if any
7369            if (alwaysList.size() > 0) {
7370                result.addAll(alwaysList);
7371            } else {
7372                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7373                result.addAll(undefinedList);
7374                // Maybe add one for the other profile.
7375                if (xpDomainInfo != null && (
7376                        xpDomainInfo.bestDomainVerificationStatus
7377                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7378                    result.add(xpDomainInfo.resolveInfo);
7379                }
7380                includeBrowser = true;
7381            }
7382
7383            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7384            // If there were 'always' entries their preferred order has been set, so we also
7385            // back that off to make the alternatives equivalent
7386            if (alwaysAskList.size() > 0) {
7387                for (ResolveInfo i : result) {
7388                    i.preferredOrder = 0;
7389                }
7390                result.addAll(alwaysAskList);
7391                includeBrowser = true;
7392            }
7393
7394            if (includeBrowser) {
7395                // Also add browsers (all of them or only the default one)
7396                if (DEBUG_DOMAIN_VERIFICATION) {
7397                    Slog.v(TAG, "   ...including browsers in candidate set");
7398                }
7399                if ((matchFlags & MATCH_ALL) != 0) {
7400                    result.addAll(matchAllList);
7401                } else {
7402                    // Browser/generic handling case.  If there's a default browser, go straight
7403                    // to that (but only if there is no other higher-priority match).
7404                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7405                    int maxMatchPrio = 0;
7406                    ResolveInfo defaultBrowserMatch = null;
7407                    final int numCandidates = matchAllList.size();
7408                    for (int n = 0; n < numCandidates; n++) {
7409                        ResolveInfo info = matchAllList.get(n);
7410                        // track the highest overall match priority...
7411                        if (info.priority > maxMatchPrio) {
7412                            maxMatchPrio = info.priority;
7413                        }
7414                        // ...and the highest-priority default browser match
7415                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7416                            if (defaultBrowserMatch == null
7417                                    || (defaultBrowserMatch.priority < info.priority)) {
7418                                if (debug) {
7419                                    Slog.v(TAG, "Considering default browser match " + info);
7420                                }
7421                                defaultBrowserMatch = info;
7422                            }
7423                        }
7424                    }
7425                    if (defaultBrowserMatch != null
7426                            && defaultBrowserMatch.priority >= maxMatchPrio
7427                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7428                    {
7429                        if (debug) {
7430                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7431                        }
7432                        result.add(defaultBrowserMatch);
7433                    } else {
7434                        result.addAll(matchAllList);
7435                    }
7436                }
7437
7438                // If there is nothing selected, add all candidates and remove the ones that the user
7439                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7440                if (result.size() == 0) {
7441                    result.addAll(candidates);
7442                    result.removeAll(neverList);
7443                }
7444            }
7445        }
7446        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7447            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7448                    result.size());
7449            for (ResolveInfo info : result) {
7450                Slog.v(TAG, "  + " + info.activityInfo);
7451            }
7452        }
7453        return result;
7454    }
7455
7456    // Returns a packed value as a long:
7457    //
7458    // high 'int'-sized word: link status: undefined/ask/never/always.
7459    // low 'int'-sized word: relative priority among 'always' results.
7460    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7461        long result = ps.getDomainVerificationStatusForUser(userId);
7462        // if none available, get the master status
7463        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7464            if (ps.getIntentFilterVerificationInfo() != null) {
7465                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7466            }
7467        }
7468        return result;
7469    }
7470
7471    private ResolveInfo querySkipCurrentProfileIntents(
7472            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7473            int flags, int sourceUserId) {
7474        if (matchingFilters != null) {
7475            int size = matchingFilters.size();
7476            for (int i = 0; i < size; i ++) {
7477                CrossProfileIntentFilter filter = matchingFilters.get(i);
7478                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7479                    // Checking if there are activities in the target user that can handle the
7480                    // intent.
7481                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7482                            resolvedType, flags, sourceUserId);
7483                    if (resolveInfo != null) {
7484                        return resolveInfo;
7485                    }
7486                }
7487            }
7488        }
7489        return null;
7490    }
7491
7492    // Return matching ResolveInfo in target user if any.
7493    private ResolveInfo queryCrossProfileIntents(
7494            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7495            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7496        if (matchingFilters != null) {
7497            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7498            // match the same intent. For performance reasons, it is better not to
7499            // run queryIntent twice for the same userId
7500            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7501            int size = matchingFilters.size();
7502            for (int i = 0; i < size; i++) {
7503                CrossProfileIntentFilter filter = matchingFilters.get(i);
7504                int targetUserId = filter.getTargetUserId();
7505                boolean skipCurrentProfile =
7506                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7507                boolean skipCurrentProfileIfNoMatchFound =
7508                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7509                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7510                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7511                    // Checking if there are activities in the target user that can handle the
7512                    // intent.
7513                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7514                            resolvedType, flags, sourceUserId);
7515                    if (resolveInfo != null) return resolveInfo;
7516                    alreadyTriedUserIds.put(targetUserId, true);
7517                }
7518            }
7519        }
7520        return null;
7521    }
7522
7523    /**
7524     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7525     * will forward the intent to the filter's target user.
7526     * Otherwise, returns null.
7527     */
7528    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7529            String resolvedType, int flags, int sourceUserId) {
7530        int targetUserId = filter.getTargetUserId();
7531        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7532                resolvedType, flags, targetUserId);
7533        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7534            // If all the matches in the target profile are suspended, return null.
7535            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7536                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7537                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7538                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7539                            targetUserId);
7540                }
7541            }
7542        }
7543        return null;
7544    }
7545
7546    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7547            int sourceUserId, int targetUserId) {
7548        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7549        long ident = Binder.clearCallingIdentity();
7550        boolean targetIsProfile;
7551        try {
7552            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7553        } finally {
7554            Binder.restoreCallingIdentity(ident);
7555        }
7556        String className;
7557        if (targetIsProfile) {
7558            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7559        } else {
7560            className = FORWARD_INTENT_TO_PARENT;
7561        }
7562        ComponentName forwardingActivityComponentName = new ComponentName(
7563                mAndroidApplication.packageName, className);
7564        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7565                sourceUserId);
7566        if (!targetIsProfile) {
7567            forwardingActivityInfo.showUserIcon = targetUserId;
7568            forwardingResolveInfo.noResourceId = true;
7569        }
7570        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7571        forwardingResolveInfo.priority = 0;
7572        forwardingResolveInfo.preferredOrder = 0;
7573        forwardingResolveInfo.match = 0;
7574        forwardingResolveInfo.isDefault = true;
7575        forwardingResolveInfo.filter = filter;
7576        forwardingResolveInfo.targetUserId = targetUserId;
7577        return forwardingResolveInfo;
7578    }
7579
7580    @Override
7581    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7582            Intent[] specifics, String[] specificTypes, Intent intent,
7583            String resolvedType, int flags, int userId) {
7584        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7585                specificTypes, intent, resolvedType, flags, userId));
7586    }
7587
7588    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7589            Intent[] specifics, String[] specificTypes, Intent intent,
7590            String resolvedType, int flags, int userId) {
7591        if (!sUserManager.exists(userId)) return Collections.emptyList();
7592        final int callingUid = Binder.getCallingUid();
7593        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7594                false /*includeInstantApps*/);
7595        enforceCrossUserPermission(callingUid, userId,
7596                false /*requireFullPermission*/, false /*checkShell*/,
7597                "query intent activity options");
7598        final String resultsAction = intent.getAction();
7599
7600        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7601                | PackageManager.GET_RESOLVED_FILTER, userId);
7602
7603        if (DEBUG_INTENT_MATCHING) {
7604            Log.v(TAG, "Query " + intent + ": " + results);
7605        }
7606
7607        int specificsPos = 0;
7608        int N;
7609
7610        // todo: note that the algorithm used here is O(N^2).  This
7611        // isn't a problem in our current environment, but if we start running
7612        // into situations where we have more than 5 or 10 matches then this
7613        // should probably be changed to something smarter...
7614
7615        // First we go through and resolve each of the specific items
7616        // that were supplied, taking care of removing any corresponding
7617        // duplicate items in the generic resolve list.
7618        if (specifics != null) {
7619            for (int i=0; i<specifics.length; i++) {
7620                final Intent sintent = specifics[i];
7621                if (sintent == null) {
7622                    continue;
7623                }
7624
7625                if (DEBUG_INTENT_MATCHING) {
7626                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7627                }
7628
7629                String action = sintent.getAction();
7630                if (resultsAction != null && resultsAction.equals(action)) {
7631                    // If this action was explicitly requested, then don't
7632                    // remove things that have it.
7633                    action = null;
7634                }
7635
7636                ResolveInfo ri = null;
7637                ActivityInfo ai = null;
7638
7639                ComponentName comp = sintent.getComponent();
7640                if (comp == null) {
7641                    ri = resolveIntent(
7642                        sintent,
7643                        specificTypes != null ? specificTypes[i] : null,
7644                            flags, userId);
7645                    if (ri == null) {
7646                        continue;
7647                    }
7648                    if (ri == mResolveInfo) {
7649                        // ACK!  Must do something better with this.
7650                    }
7651                    ai = ri.activityInfo;
7652                    comp = new ComponentName(ai.applicationInfo.packageName,
7653                            ai.name);
7654                } else {
7655                    ai = getActivityInfo(comp, flags, userId);
7656                    if (ai == null) {
7657                        continue;
7658                    }
7659                }
7660
7661                // Look for any generic query activities that are duplicates
7662                // of this specific one, and remove them from the results.
7663                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7664                N = results.size();
7665                int j;
7666                for (j=specificsPos; j<N; j++) {
7667                    ResolveInfo sri = results.get(j);
7668                    if ((sri.activityInfo.name.equals(comp.getClassName())
7669                            && sri.activityInfo.applicationInfo.packageName.equals(
7670                                    comp.getPackageName()))
7671                        || (action != null && sri.filter.matchAction(action))) {
7672                        results.remove(j);
7673                        if (DEBUG_INTENT_MATCHING) Log.v(
7674                            TAG, "Removing duplicate item from " + j
7675                            + " due to specific " + specificsPos);
7676                        if (ri == null) {
7677                            ri = sri;
7678                        }
7679                        j--;
7680                        N--;
7681                    }
7682                }
7683
7684                // Add this specific item to its proper place.
7685                if (ri == null) {
7686                    ri = new ResolveInfo();
7687                    ri.activityInfo = ai;
7688                }
7689                results.add(specificsPos, ri);
7690                ri.specificIndex = i;
7691                specificsPos++;
7692            }
7693        }
7694
7695        // Now we go through the remaining generic results and remove any
7696        // duplicate actions that are found here.
7697        N = results.size();
7698        for (int i=specificsPos; i<N-1; i++) {
7699            final ResolveInfo rii = results.get(i);
7700            if (rii.filter == null) {
7701                continue;
7702            }
7703
7704            // Iterate over all of the actions of this result's intent
7705            // filter...  typically this should be just one.
7706            final Iterator<String> it = rii.filter.actionsIterator();
7707            if (it == null) {
7708                continue;
7709            }
7710            while (it.hasNext()) {
7711                final String action = it.next();
7712                if (resultsAction != null && resultsAction.equals(action)) {
7713                    // If this action was explicitly requested, then don't
7714                    // remove things that have it.
7715                    continue;
7716                }
7717                for (int j=i+1; j<N; j++) {
7718                    final ResolveInfo rij = results.get(j);
7719                    if (rij.filter != null && rij.filter.hasAction(action)) {
7720                        results.remove(j);
7721                        if (DEBUG_INTENT_MATCHING) Log.v(
7722                            TAG, "Removing duplicate item from " + j
7723                            + " due to action " + action + " at " + i);
7724                        j--;
7725                        N--;
7726                    }
7727                }
7728            }
7729
7730            // If the caller didn't request filter information, drop it now
7731            // so we don't have to marshall/unmarshall it.
7732            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7733                rii.filter = null;
7734            }
7735        }
7736
7737        // Filter out the caller activity if so requested.
7738        if (caller != null) {
7739            N = results.size();
7740            for (int i=0; i<N; i++) {
7741                ActivityInfo ainfo = results.get(i).activityInfo;
7742                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7743                        && caller.getClassName().equals(ainfo.name)) {
7744                    results.remove(i);
7745                    break;
7746                }
7747            }
7748        }
7749
7750        // If the caller didn't request filter information,
7751        // drop them now so we don't have to
7752        // marshall/unmarshall it.
7753        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7754            N = results.size();
7755            for (int i=0; i<N; i++) {
7756                results.get(i).filter = null;
7757            }
7758        }
7759
7760        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7761        return results;
7762    }
7763
7764    @Override
7765    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7766            String resolvedType, int flags, int userId) {
7767        return new ParceledListSlice<>(
7768                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7769    }
7770
7771    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7772            String resolvedType, int flags, int userId) {
7773        if (!sUserManager.exists(userId)) return Collections.emptyList();
7774        final int callingUid = Binder.getCallingUid();
7775        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7776        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7777                false /*includeInstantApps*/);
7778        ComponentName comp = intent.getComponent();
7779        if (comp == null) {
7780            if (intent.getSelector() != null) {
7781                intent = intent.getSelector();
7782                comp = intent.getComponent();
7783            }
7784        }
7785        if (comp != null) {
7786            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7787            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7788            if (ai != null) {
7789                // When specifying an explicit component, we prevent the activity from being
7790                // used when either 1) the calling package is normal and the activity is within
7791                // an instant application or 2) the calling package is ephemeral and the
7792                // activity is not visible to instant applications.
7793                final boolean matchInstantApp =
7794                        (flags & PackageManager.MATCH_INSTANT) != 0;
7795                final boolean matchVisibleToInstantAppOnly =
7796                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7797                final boolean matchExplicitlyVisibleOnly =
7798                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7799                final boolean isCallerInstantApp =
7800                        instantAppPkgName != null;
7801                final boolean isTargetSameInstantApp =
7802                        comp.getPackageName().equals(instantAppPkgName);
7803                final boolean isTargetInstantApp =
7804                        (ai.applicationInfo.privateFlags
7805                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7806                final boolean isTargetVisibleToInstantApp =
7807                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7808                final boolean isTargetExplicitlyVisibleToInstantApp =
7809                        isTargetVisibleToInstantApp
7810                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7811                final boolean isTargetHiddenFromInstantApp =
7812                        !isTargetVisibleToInstantApp
7813                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7814                final boolean blockResolution =
7815                        !isTargetSameInstantApp
7816                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7817                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7818                                        && isTargetHiddenFromInstantApp));
7819                if (!blockResolution) {
7820                    ResolveInfo ri = new ResolveInfo();
7821                    ri.activityInfo = ai;
7822                    list.add(ri);
7823                }
7824            }
7825            return applyPostResolutionFilter(list, instantAppPkgName);
7826        }
7827
7828        // reader
7829        synchronized (mPackages) {
7830            String pkgName = intent.getPackage();
7831            if (pkgName == null) {
7832                final List<ResolveInfo> result =
7833                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7834                return applyPostResolutionFilter(result, instantAppPkgName);
7835            }
7836            final PackageParser.Package pkg = mPackages.get(pkgName);
7837            if (pkg != null) {
7838                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7839                        intent, resolvedType, flags, pkg.receivers, userId);
7840                return applyPostResolutionFilter(result, instantAppPkgName);
7841            }
7842            return Collections.emptyList();
7843        }
7844    }
7845
7846    @Override
7847    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7848        final int callingUid = Binder.getCallingUid();
7849        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7850    }
7851
7852    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7853            int userId, int callingUid) {
7854        if (!sUserManager.exists(userId)) return null;
7855        flags = updateFlagsForResolve(
7856                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7857        List<ResolveInfo> query = queryIntentServicesInternal(
7858                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7859        if (query != null) {
7860            if (query.size() >= 1) {
7861                // If there is more than one service with the same priority,
7862                // just arbitrarily pick the first one.
7863                return query.get(0);
7864            }
7865        }
7866        return null;
7867    }
7868
7869    @Override
7870    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7871            String resolvedType, int flags, int userId) {
7872        final int callingUid = Binder.getCallingUid();
7873        return new ParceledListSlice<>(queryIntentServicesInternal(
7874                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7875    }
7876
7877    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7878            String resolvedType, int flags, int userId, int callingUid,
7879            boolean includeInstantApps) {
7880        if (!sUserManager.exists(userId)) return Collections.emptyList();
7881        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7882        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7883        ComponentName comp = intent.getComponent();
7884        if (comp == null) {
7885            if (intent.getSelector() != null) {
7886                intent = intent.getSelector();
7887                comp = intent.getComponent();
7888            }
7889        }
7890        if (comp != null) {
7891            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7892            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7893            if (si != null) {
7894                // When specifying an explicit component, we prevent the service from being
7895                // used when either 1) the service is in an instant application and the
7896                // caller is not the same instant application or 2) the calling package is
7897                // ephemeral and the activity is not visible to ephemeral applications.
7898                final boolean matchInstantApp =
7899                        (flags & PackageManager.MATCH_INSTANT) != 0;
7900                final boolean matchVisibleToInstantAppOnly =
7901                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7902                final boolean isCallerInstantApp =
7903                        instantAppPkgName != null;
7904                final boolean isTargetSameInstantApp =
7905                        comp.getPackageName().equals(instantAppPkgName);
7906                final boolean isTargetInstantApp =
7907                        (si.applicationInfo.privateFlags
7908                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7909                final boolean isTargetHiddenFromInstantApp =
7910                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7911                final boolean blockResolution =
7912                        !isTargetSameInstantApp
7913                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7914                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7915                                        && isTargetHiddenFromInstantApp));
7916                if (!blockResolution) {
7917                    final ResolveInfo ri = new ResolveInfo();
7918                    ri.serviceInfo = si;
7919                    list.add(ri);
7920                }
7921            }
7922            return list;
7923        }
7924
7925        // reader
7926        synchronized (mPackages) {
7927            String pkgName = intent.getPackage();
7928            if (pkgName == null) {
7929                return applyPostServiceResolutionFilter(
7930                        mServices.queryIntent(intent, resolvedType, flags, userId),
7931                        instantAppPkgName);
7932            }
7933            final PackageParser.Package pkg = mPackages.get(pkgName);
7934            if (pkg != null) {
7935                return applyPostServiceResolutionFilter(
7936                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7937                                userId),
7938                        instantAppPkgName);
7939            }
7940            return Collections.emptyList();
7941        }
7942    }
7943
7944    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7945            String instantAppPkgName) {
7946        // TODO: When adding on-demand split support for non-instant apps, remove this check
7947        // and always apply post filtering
7948        if (instantAppPkgName == null) {
7949            return resolveInfos;
7950        }
7951        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7952            final ResolveInfo info = resolveInfos.get(i);
7953            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7954            // allow services that are defined in the provided package
7955            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7956                if (info.serviceInfo.splitName != null
7957                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7958                                info.serviceInfo.splitName)) {
7959                    // requested service is defined in a split that hasn't been installed yet.
7960                    // add the installer to the resolve list
7961                    if (DEBUG_EPHEMERAL) {
7962                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7963                    }
7964                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7965                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7966                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7967                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7968                    // make sure this resolver is the default
7969                    installerInfo.isDefault = true;
7970                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7971                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7972                    // add a non-generic filter
7973                    installerInfo.filter = new IntentFilter();
7974                    // load resources from the correct package
7975                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7976                    resolveInfos.set(i, installerInfo);
7977                }
7978                continue;
7979            }
7980            // allow services that have been explicitly exposed to ephemeral apps
7981            if (!isEphemeralApp
7982                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7983                continue;
7984            }
7985            resolveInfos.remove(i);
7986        }
7987        return resolveInfos;
7988    }
7989
7990    @Override
7991    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7992            String resolvedType, int flags, int userId) {
7993        return new ParceledListSlice<>(
7994                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7995    }
7996
7997    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7998            Intent intent, String resolvedType, int flags, int userId) {
7999        if (!sUserManager.exists(userId)) return Collections.emptyList();
8000        final int callingUid = Binder.getCallingUid();
8001        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8002        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8003                false /*includeInstantApps*/);
8004        ComponentName comp = intent.getComponent();
8005        if (comp == null) {
8006            if (intent.getSelector() != null) {
8007                intent = intent.getSelector();
8008                comp = intent.getComponent();
8009            }
8010        }
8011        if (comp != null) {
8012            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8013            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8014            if (pi != null) {
8015                // When specifying an explicit component, we prevent the provider from being
8016                // used when either 1) the provider is in an instant application and the
8017                // caller is not the same instant application or 2) the calling package is an
8018                // instant application and the provider is not visible to instant applications.
8019                final boolean matchInstantApp =
8020                        (flags & PackageManager.MATCH_INSTANT) != 0;
8021                final boolean matchVisibleToInstantAppOnly =
8022                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8023                final boolean isCallerInstantApp =
8024                        instantAppPkgName != null;
8025                final boolean isTargetSameInstantApp =
8026                        comp.getPackageName().equals(instantAppPkgName);
8027                final boolean isTargetInstantApp =
8028                        (pi.applicationInfo.privateFlags
8029                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8030                final boolean isTargetHiddenFromInstantApp =
8031                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8032                final boolean blockResolution =
8033                        !isTargetSameInstantApp
8034                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8035                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8036                                        && isTargetHiddenFromInstantApp));
8037                if (!blockResolution) {
8038                    final ResolveInfo ri = new ResolveInfo();
8039                    ri.providerInfo = pi;
8040                    list.add(ri);
8041                }
8042            }
8043            return list;
8044        }
8045
8046        // reader
8047        synchronized (mPackages) {
8048            String pkgName = intent.getPackage();
8049            if (pkgName == null) {
8050                return applyPostContentProviderResolutionFilter(
8051                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8052                        instantAppPkgName);
8053            }
8054            final PackageParser.Package pkg = mPackages.get(pkgName);
8055            if (pkg != null) {
8056                return applyPostContentProviderResolutionFilter(
8057                        mProviders.queryIntentForPackage(
8058                        intent, resolvedType, flags, pkg.providers, userId),
8059                        instantAppPkgName);
8060            }
8061            return Collections.emptyList();
8062        }
8063    }
8064
8065    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8066            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8067        // TODO: When adding on-demand split support for non-instant applications, remove
8068        // this check and always apply post filtering
8069        if (instantAppPkgName == null) {
8070            return resolveInfos;
8071        }
8072        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8073            final ResolveInfo info = resolveInfos.get(i);
8074            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8075            // allow providers that are defined in the provided package
8076            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8077                if (info.providerInfo.splitName != null
8078                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8079                                info.providerInfo.splitName)) {
8080                    // requested provider is defined in a split that hasn't been installed yet.
8081                    // add the installer to the resolve list
8082                    if (DEBUG_EPHEMERAL) {
8083                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8084                    }
8085                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8086                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8087                            info.providerInfo.packageName, info.providerInfo.splitName,
8088                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8089                    // make sure this resolver is the default
8090                    installerInfo.isDefault = true;
8091                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8092                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8093                    // add a non-generic filter
8094                    installerInfo.filter = new IntentFilter();
8095                    // load resources from the correct package
8096                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8097                    resolveInfos.set(i, installerInfo);
8098                }
8099                continue;
8100            }
8101            // allow providers that have been explicitly exposed to instant applications
8102            if (!isEphemeralApp
8103                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8104                continue;
8105            }
8106            resolveInfos.remove(i);
8107        }
8108        return resolveInfos;
8109    }
8110
8111    @Override
8112    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8113        final int callingUid = Binder.getCallingUid();
8114        if (getInstantAppPackageName(callingUid) != null) {
8115            return ParceledListSlice.emptyList();
8116        }
8117        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8118        flags = updateFlagsForPackage(flags, userId, null);
8119        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8120        enforceCrossUserPermission(callingUid, userId,
8121                true /* requireFullPermission */, false /* checkShell */,
8122                "get installed packages");
8123
8124        // writer
8125        synchronized (mPackages) {
8126            ArrayList<PackageInfo> list;
8127            if (listUninstalled) {
8128                list = new ArrayList<>(mSettings.mPackages.size());
8129                for (PackageSetting ps : mSettings.mPackages.values()) {
8130                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8131                        continue;
8132                    }
8133                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8134                        return null;
8135                    }
8136                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8137                    if (pi != null) {
8138                        list.add(pi);
8139                    }
8140                }
8141            } else {
8142                list = new ArrayList<>(mPackages.size());
8143                for (PackageParser.Package p : mPackages.values()) {
8144                    final PackageSetting ps = (PackageSetting) p.mExtras;
8145                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8146                        continue;
8147                    }
8148                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8149                        return null;
8150                    }
8151                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8152                            p.mExtras, flags, userId);
8153                    if (pi != null) {
8154                        list.add(pi);
8155                    }
8156                }
8157            }
8158
8159            return new ParceledListSlice<>(list);
8160        }
8161    }
8162
8163    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8164            String[] permissions, boolean[] tmp, int flags, int userId) {
8165        int numMatch = 0;
8166        final PermissionsState permissionsState = ps.getPermissionsState();
8167        for (int i=0; i<permissions.length; i++) {
8168            final String permission = permissions[i];
8169            if (permissionsState.hasPermission(permission, userId)) {
8170                tmp[i] = true;
8171                numMatch++;
8172            } else {
8173                tmp[i] = false;
8174            }
8175        }
8176        if (numMatch == 0) {
8177            return;
8178        }
8179        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8180
8181        // The above might return null in cases of uninstalled apps or install-state
8182        // skew across users/profiles.
8183        if (pi != null) {
8184            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8185                if (numMatch == permissions.length) {
8186                    pi.requestedPermissions = permissions;
8187                } else {
8188                    pi.requestedPermissions = new String[numMatch];
8189                    numMatch = 0;
8190                    for (int i=0; i<permissions.length; i++) {
8191                        if (tmp[i]) {
8192                            pi.requestedPermissions[numMatch] = permissions[i];
8193                            numMatch++;
8194                        }
8195                    }
8196                }
8197            }
8198            list.add(pi);
8199        }
8200    }
8201
8202    @Override
8203    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8204            String[] permissions, int flags, int userId) {
8205        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8206        flags = updateFlagsForPackage(flags, userId, permissions);
8207        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8208                true /* requireFullPermission */, false /* checkShell */,
8209                "get packages holding permissions");
8210        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8211
8212        // writer
8213        synchronized (mPackages) {
8214            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8215            boolean[] tmpBools = new boolean[permissions.length];
8216            if (listUninstalled) {
8217                for (PackageSetting ps : mSettings.mPackages.values()) {
8218                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8219                            userId);
8220                }
8221            } else {
8222                for (PackageParser.Package pkg : mPackages.values()) {
8223                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8224                    if (ps != null) {
8225                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8226                                userId);
8227                    }
8228                }
8229            }
8230
8231            return new ParceledListSlice<PackageInfo>(list);
8232        }
8233    }
8234
8235    @Override
8236    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8237        final int callingUid = Binder.getCallingUid();
8238        if (getInstantAppPackageName(callingUid) != null) {
8239            return ParceledListSlice.emptyList();
8240        }
8241        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8242        flags = updateFlagsForApplication(flags, userId, null);
8243        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8244
8245        // writer
8246        synchronized (mPackages) {
8247            ArrayList<ApplicationInfo> list;
8248            if (listUninstalled) {
8249                list = new ArrayList<>(mSettings.mPackages.size());
8250                for (PackageSetting ps : mSettings.mPackages.values()) {
8251                    ApplicationInfo ai;
8252                    int effectiveFlags = flags;
8253                    if (ps.isSystem()) {
8254                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8255                    }
8256                    if (ps.pkg != null) {
8257                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8258                            continue;
8259                        }
8260                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8261                            return null;
8262                        }
8263                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8264                                ps.readUserState(userId), userId);
8265                        if (ai != null) {
8266                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8267                        }
8268                    } else {
8269                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8270                        // and already converts to externally visible package name
8271                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8272                                callingUid, effectiveFlags, userId);
8273                    }
8274                    if (ai != null) {
8275                        list.add(ai);
8276                    }
8277                }
8278            } else {
8279                list = new ArrayList<>(mPackages.size());
8280                for (PackageParser.Package p : mPackages.values()) {
8281                    if (p.mExtras != null) {
8282                        PackageSetting ps = (PackageSetting) p.mExtras;
8283                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8284                            continue;
8285                        }
8286                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8287                            return null;
8288                        }
8289                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8290                                ps.readUserState(userId), userId);
8291                        if (ai != null) {
8292                            ai.packageName = resolveExternalPackageNameLPr(p);
8293                            list.add(ai);
8294                        }
8295                    }
8296                }
8297            }
8298
8299            return new ParceledListSlice<>(list);
8300        }
8301    }
8302
8303    @Override
8304    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8305        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8306            return null;
8307        }
8308        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8309                "getEphemeralApplications");
8310        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8311                true /* requireFullPermission */, false /* checkShell */,
8312                "getEphemeralApplications");
8313        synchronized (mPackages) {
8314            List<InstantAppInfo> instantApps = mInstantAppRegistry
8315                    .getInstantAppsLPr(userId);
8316            if (instantApps != null) {
8317                return new ParceledListSlice<>(instantApps);
8318            }
8319        }
8320        return null;
8321    }
8322
8323    @Override
8324    public boolean isInstantApp(String packageName, int userId) {
8325        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8326                true /* requireFullPermission */, false /* checkShell */,
8327                "isInstantApp");
8328        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8329            return false;
8330        }
8331        int callingUid = Binder.getCallingUid();
8332        if (Process.isIsolated(callingUid)) {
8333            callingUid = mIsolatedOwners.get(callingUid);
8334        }
8335
8336        synchronized (mPackages) {
8337            final PackageSetting ps = mSettings.mPackages.get(packageName);
8338            PackageParser.Package pkg = mPackages.get(packageName);
8339            final boolean returnAllowed =
8340                    ps != null
8341                    && (isCallerSameApp(packageName, callingUid)
8342                            || canViewInstantApps(callingUid, userId)
8343                            || mInstantAppRegistry.isInstantAccessGranted(
8344                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8345            if (returnAllowed) {
8346                return ps.getInstantApp(userId);
8347            }
8348        }
8349        return false;
8350    }
8351
8352    @Override
8353    public byte[] getInstantAppCookie(String packageName, int userId) {
8354        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8355            return null;
8356        }
8357
8358        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8359                true /* requireFullPermission */, false /* checkShell */,
8360                "getInstantAppCookie");
8361        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8362            return null;
8363        }
8364        synchronized (mPackages) {
8365            return mInstantAppRegistry.getInstantAppCookieLPw(
8366                    packageName, userId);
8367        }
8368    }
8369
8370    @Override
8371    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8372        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8373            return true;
8374        }
8375
8376        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8377                true /* requireFullPermission */, true /* checkShell */,
8378                "setInstantAppCookie");
8379        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8380            return false;
8381        }
8382        synchronized (mPackages) {
8383            return mInstantAppRegistry.setInstantAppCookieLPw(
8384                    packageName, cookie, userId);
8385        }
8386    }
8387
8388    @Override
8389    public Bitmap getInstantAppIcon(String packageName, int userId) {
8390        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8391            return null;
8392        }
8393
8394        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8395                "getInstantAppIcon");
8396
8397        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8398                true /* requireFullPermission */, false /* checkShell */,
8399                "getInstantAppIcon");
8400
8401        synchronized (mPackages) {
8402            return mInstantAppRegistry.getInstantAppIconLPw(
8403                    packageName, userId);
8404        }
8405    }
8406
8407    private boolean isCallerSameApp(String packageName, int uid) {
8408        PackageParser.Package pkg = mPackages.get(packageName);
8409        return pkg != null
8410                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8411    }
8412
8413    @Override
8414    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8415        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8416            return ParceledListSlice.emptyList();
8417        }
8418        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8419    }
8420
8421    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8422        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8423
8424        // reader
8425        synchronized (mPackages) {
8426            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8427            final int userId = UserHandle.getCallingUserId();
8428            while (i.hasNext()) {
8429                final PackageParser.Package p = i.next();
8430                if (p.applicationInfo == null) continue;
8431
8432                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8433                        && !p.applicationInfo.isDirectBootAware();
8434                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8435                        && p.applicationInfo.isDirectBootAware();
8436
8437                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8438                        && (!mSafeMode || isSystemApp(p))
8439                        && (matchesUnaware || matchesAware)) {
8440                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8441                    if (ps != null) {
8442                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8443                                ps.readUserState(userId), userId);
8444                        if (ai != null) {
8445                            finalList.add(ai);
8446                        }
8447                    }
8448                }
8449            }
8450        }
8451
8452        return finalList;
8453    }
8454
8455    @Override
8456    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8457        if (!sUserManager.exists(userId)) return null;
8458        flags = updateFlagsForComponent(flags, userId, name);
8459        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8460        // reader
8461        synchronized (mPackages) {
8462            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8463            PackageSetting ps = provider != null
8464                    ? mSettings.mPackages.get(provider.owner.packageName)
8465                    : null;
8466            if (ps != null) {
8467                final boolean isInstantApp = ps.getInstantApp(userId);
8468                // normal application; filter out instant application provider
8469                if (instantAppPkgName == null && isInstantApp) {
8470                    return null;
8471                }
8472                // instant application; filter out other instant applications
8473                if (instantAppPkgName != null
8474                        && isInstantApp
8475                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8476                    return null;
8477                }
8478                // instant application; filter out non-exposed provider
8479                if (instantAppPkgName != null
8480                        && !isInstantApp
8481                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8482                    return null;
8483                }
8484                // provider not enabled
8485                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8486                    return null;
8487                }
8488                return PackageParser.generateProviderInfo(
8489                        provider, flags, ps.readUserState(userId), userId);
8490            }
8491            return null;
8492        }
8493    }
8494
8495    /**
8496     * @deprecated
8497     */
8498    @Deprecated
8499    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8500        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8501            return;
8502        }
8503        // reader
8504        synchronized (mPackages) {
8505            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8506                    .entrySet().iterator();
8507            final int userId = UserHandle.getCallingUserId();
8508            while (i.hasNext()) {
8509                Map.Entry<String, PackageParser.Provider> entry = i.next();
8510                PackageParser.Provider p = entry.getValue();
8511                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8512
8513                if (ps != null && p.syncable
8514                        && (!mSafeMode || (p.info.applicationInfo.flags
8515                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8516                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8517                            ps.readUserState(userId), userId);
8518                    if (info != null) {
8519                        outNames.add(entry.getKey());
8520                        outInfo.add(info);
8521                    }
8522                }
8523            }
8524        }
8525    }
8526
8527    @Override
8528    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8529            int uid, int flags, String metaDataKey) {
8530        final int callingUid = Binder.getCallingUid();
8531        final int userId = processName != null ? UserHandle.getUserId(uid)
8532                : UserHandle.getCallingUserId();
8533        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8534        flags = updateFlagsForComponent(flags, userId, processName);
8535        ArrayList<ProviderInfo> finalList = null;
8536        // reader
8537        synchronized (mPackages) {
8538            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8539            while (i.hasNext()) {
8540                final PackageParser.Provider p = i.next();
8541                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8542                if (ps != null && p.info.authority != null
8543                        && (processName == null
8544                                || (p.info.processName.equals(processName)
8545                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8546                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8547
8548                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8549                    // parameter.
8550                    if (metaDataKey != null
8551                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8552                        continue;
8553                    }
8554                    final ComponentName component =
8555                            new ComponentName(p.info.packageName, p.info.name);
8556                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8557                        continue;
8558                    }
8559                    if (finalList == null) {
8560                        finalList = new ArrayList<ProviderInfo>(3);
8561                    }
8562                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8563                            ps.readUserState(userId), userId);
8564                    if (info != null) {
8565                        finalList.add(info);
8566                    }
8567                }
8568            }
8569        }
8570
8571        if (finalList != null) {
8572            Collections.sort(finalList, mProviderInitOrderSorter);
8573            return new ParceledListSlice<ProviderInfo>(finalList);
8574        }
8575
8576        return ParceledListSlice.emptyList();
8577    }
8578
8579    @Override
8580    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8581        // reader
8582        synchronized (mPackages) {
8583            final int callingUid = Binder.getCallingUid();
8584            final int callingUserId = UserHandle.getUserId(callingUid);
8585            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8586            if (ps == null) return null;
8587            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8588                return null;
8589            }
8590            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8591            return PackageParser.generateInstrumentationInfo(i, flags);
8592        }
8593    }
8594
8595    @Override
8596    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8597            String targetPackage, int flags) {
8598        final int callingUid = Binder.getCallingUid();
8599        final int callingUserId = UserHandle.getUserId(callingUid);
8600        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8601        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8602            return ParceledListSlice.emptyList();
8603        }
8604        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8605    }
8606
8607    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8608            int flags) {
8609        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8610
8611        // reader
8612        synchronized (mPackages) {
8613            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8614            while (i.hasNext()) {
8615                final PackageParser.Instrumentation p = i.next();
8616                if (targetPackage == null
8617                        || targetPackage.equals(p.info.targetPackage)) {
8618                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8619                            flags);
8620                    if (ii != null) {
8621                        finalList.add(ii);
8622                    }
8623                }
8624            }
8625        }
8626
8627        return finalList;
8628    }
8629
8630    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8631        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8632        try {
8633            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8634        } finally {
8635            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8636        }
8637    }
8638
8639    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8640        final File[] files = dir.listFiles();
8641        if (ArrayUtils.isEmpty(files)) {
8642            Log.d(TAG, "No files in app dir " + dir);
8643            return;
8644        }
8645
8646        if (DEBUG_PACKAGE_SCANNING) {
8647            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8648                    + " flags=0x" + Integer.toHexString(parseFlags));
8649        }
8650        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8651                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8652                mParallelPackageParserCallback);
8653
8654        // Submit files for parsing in parallel
8655        int fileCount = 0;
8656        for (File file : files) {
8657            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8658                    && !PackageInstallerService.isStageName(file.getName());
8659            if (!isPackage) {
8660                // Ignore entries which are not packages
8661                continue;
8662            }
8663            parallelPackageParser.submit(file, parseFlags);
8664            fileCount++;
8665        }
8666
8667        // Process results one by one
8668        for (; fileCount > 0; fileCount--) {
8669            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8670            Throwable throwable = parseResult.throwable;
8671            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8672
8673            if (throwable == null) {
8674                // Static shared libraries have synthetic package names
8675                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8676                    renameStaticSharedLibraryPackage(parseResult.pkg);
8677                }
8678                try {
8679                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8680                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8681                                currentTime, null);
8682                    }
8683                } catch (PackageManagerException e) {
8684                    errorCode = e.error;
8685                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8686                }
8687            } else if (throwable instanceof PackageParser.PackageParserException) {
8688                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8689                        throwable;
8690                errorCode = e.error;
8691                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8692            } else {
8693                throw new IllegalStateException("Unexpected exception occurred while parsing "
8694                        + parseResult.scanFile, throwable);
8695            }
8696
8697            // Delete invalid userdata apps
8698            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8699                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8700                logCriticalInfo(Log.WARN,
8701                        "Deleting invalid package at " + parseResult.scanFile);
8702                removeCodePathLI(parseResult.scanFile);
8703            }
8704        }
8705        parallelPackageParser.close();
8706    }
8707
8708    private static File getSettingsProblemFile() {
8709        File dataDir = Environment.getDataDirectory();
8710        File systemDir = new File(dataDir, "system");
8711        File fname = new File(systemDir, "uiderrors.txt");
8712        return fname;
8713    }
8714
8715    static void reportSettingsProblem(int priority, String msg) {
8716        logCriticalInfo(priority, msg);
8717    }
8718
8719    public static void logCriticalInfo(int priority, String msg) {
8720        Slog.println(priority, TAG, msg);
8721        EventLogTags.writePmCriticalInfo(msg);
8722        try {
8723            File fname = getSettingsProblemFile();
8724            FileOutputStream out = new FileOutputStream(fname, true);
8725            PrintWriter pw = new FastPrintWriter(out);
8726            SimpleDateFormat formatter = new SimpleDateFormat();
8727            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8728            pw.println(dateString + ": " + msg);
8729            pw.close();
8730            FileUtils.setPermissions(
8731                    fname.toString(),
8732                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8733                    -1, -1);
8734        } catch (java.io.IOException e) {
8735        }
8736    }
8737
8738    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8739        if (srcFile.isDirectory()) {
8740            final File baseFile = new File(pkg.baseCodePath);
8741            long maxModifiedTime = baseFile.lastModified();
8742            if (pkg.splitCodePaths != null) {
8743                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8744                    final File splitFile = new File(pkg.splitCodePaths[i]);
8745                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8746                }
8747            }
8748            return maxModifiedTime;
8749        }
8750        return srcFile.lastModified();
8751    }
8752
8753    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8754            final int policyFlags) throws PackageManagerException {
8755        // When upgrading from pre-N MR1, verify the package time stamp using the package
8756        // directory and not the APK file.
8757        final long lastModifiedTime = mIsPreNMR1Upgrade
8758                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8759        if (ps != null
8760                && ps.codePath.equals(srcFile)
8761                && ps.timeStamp == lastModifiedTime
8762                && !isCompatSignatureUpdateNeeded(pkg)
8763                && !isRecoverSignatureUpdateNeeded(pkg)) {
8764            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8765            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8766            ArraySet<PublicKey> signingKs;
8767            synchronized (mPackages) {
8768                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8769            }
8770            if (ps.signatures.mSignatures != null
8771                    && ps.signatures.mSignatures.length != 0
8772                    && signingKs != null) {
8773                // Optimization: reuse the existing cached certificates
8774                // if the package appears to be unchanged.
8775                pkg.mSignatures = ps.signatures.mSignatures;
8776                pkg.mSigningKeys = signingKs;
8777                return;
8778            }
8779
8780            Slog.w(TAG, "PackageSetting for " + ps.name
8781                    + " is missing signatures.  Collecting certs again to recover them.");
8782        } else {
8783            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8784        }
8785
8786        try {
8787            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8788            PackageParser.collectCertificates(pkg, policyFlags);
8789        } catch (PackageParserException e) {
8790            throw PackageManagerException.from(e);
8791        } finally {
8792            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8793        }
8794    }
8795
8796    /**
8797     *  Traces a package scan.
8798     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8799     */
8800    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8801            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8802        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8803        try {
8804            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8805        } finally {
8806            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8807        }
8808    }
8809
8810    /**
8811     *  Scans a package and returns the newly parsed package.
8812     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8813     */
8814    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8815            long currentTime, UserHandle user) throws PackageManagerException {
8816        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8817        PackageParser pp = new PackageParser();
8818        pp.setSeparateProcesses(mSeparateProcesses);
8819        pp.setOnlyCoreApps(mOnlyCore);
8820        pp.setDisplayMetrics(mMetrics);
8821        pp.setCallback(mPackageParserCallback);
8822
8823        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8824            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8825        }
8826
8827        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8828        final PackageParser.Package pkg;
8829        try {
8830            pkg = pp.parsePackage(scanFile, parseFlags);
8831        } catch (PackageParserException e) {
8832            throw PackageManagerException.from(e);
8833        } finally {
8834            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8835        }
8836
8837        // Static shared libraries have synthetic package names
8838        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8839            renameStaticSharedLibraryPackage(pkg);
8840        }
8841
8842        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8843    }
8844
8845    /**
8846     *  Scans a package and returns the newly parsed package.
8847     *  @throws PackageManagerException on a parse error.
8848     */
8849    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8850            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8851            throws PackageManagerException {
8852        // If the package has children and this is the first dive in the function
8853        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8854        // packages (parent and children) would be successfully scanned before the
8855        // actual scan since scanning mutates internal state and we want to atomically
8856        // install the package and its children.
8857        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8858            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8859                scanFlags |= SCAN_CHECK_ONLY;
8860            }
8861        } else {
8862            scanFlags &= ~SCAN_CHECK_ONLY;
8863        }
8864
8865        // Scan the parent
8866        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8867                scanFlags, currentTime, user);
8868
8869        // Scan the children
8870        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8871        for (int i = 0; i < childCount; i++) {
8872            PackageParser.Package childPackage = pkg.childPackages.get(i);
8873            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8874                    currentTime, user);
8875        }
8876
8877
8878        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8879            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8880        }
8881
8882        return scannedPkg;
8883    }
8884
8885    /**
8886     *  Scans a package and returns the newly parsed package.
8887     *  @throws PackageManagerException on a parse error.
8888     */
8889    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8890            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8891            throws PackageManagerException {
8892        PackageSetting ps = null;
8893        PackageSetting updatedPkg;
8894        // reader
8895        synchronized (mPackages) {
8896            // Look to see if we already know about this package.
8897            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8898            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8899                // This package has been renamed to its original name.  Let's
8900                // use that.
8901                ps = mSettings.getPackageLPr(oldName);
8902            }
8903            // If there was no original package, see one for the real package name.
8904            if (ps == null) {
8905                ps = mSettings.getPackageLPr(pkg.packageName);
8906            }
8907            // Check to see if this package could be hiding/updating a system
8908            // package.  Must look for it either under the original or real
8909            // package name depending on our state.
8910            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8911            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8912
8913            // If this is a package we don't know about on the system partition, we
8914            // may need to remove disabled child packages on the system partition
8915            // or may need to not add child packages if the parent apk is updated
8916            // on the data partition and no longer defines this child package.
8917            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8918                // If this is a parent package for an updated system app and this system
8919                // app got an OTA update which no longer defines some of the child packages
8920                // we have to prune them from the disabled system packages.
8921                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8922                if (disabledPs != null) {
8923                    final int scannedChildCount = (pkg.childPackages != null)
8924                            ? pkg.childPackages.size() : 0;
8925                    final int disabledChildCount = disabledPs.childPackageNames != null
8926                            ? disabledPs.childPackageNames.size() : 0;
8927                    for (int i = 0; i < disabledChildCount; i++) {
8928                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8929                        boolean disabledPackageAvailable = false;
8930                        for (int j = 0; j < scannedChildCount; j++) {
8931                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8932                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8933                                disabledPackageAvailable = true;
8934                                break;
8935                            }
8936                         }
8937                         if (!disabledPackageAvailable) {
8938                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8939                         }
8940                    }
8941                }
8942            }
8943        }
8944
8945        final boolean isUpdatedPkg = updatedPkg != null;
8946        final boolean isUpdatedSystemPkg = isUpdatedPkg
8947                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
8948        boolean isUpdatedPkgBetter = false;
8949        // First check if this is a system package that may involve an update
8950        if (isUpdatedSystemPkg) {
8951            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8952            // it needs to drop FLAG_PRIVILEGED.
8953            if (locationIsPrivileged(scanFile)) {
8954                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8955            } else {
8956                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8957            }
8958
8959            if (ps != null && !ps.codePath.equals(scanFile)) {
8960                // The path has changed from what was last scanned...  check the
8961                // version of the new path against what we have stored to determine
8962                // what to do.
8963                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8964                if (pkg.mVersionCode <= ps.versionCode) {
8965                    // The system package has been updated and the code path does not match
8966                    // Ignore entry. Skip it.
8967                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8968                            + " ignored: updated version " + ps.versionCode
8969                            + " better than this " + pkg.mVersionCode);
8970                    if (!updatedPkg.codePath.equals(scanFile)) {
8971                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8972                                + ps.name + " changing from " + updatedPkg.codePathString
8973                                + " to " + scanFile);
8974                        updatedPkg.codePath = scanFile;
8975                        updatedPkg.codePathString = scanFile.toString();
8976                        updatedPkg.resourcePath = scanFile;
8977                        updatedPkg.resourcePathString = scanFile.toString();
8978                    }
8979                    updatedPkg.pkg = pkg;
8980                    updatedPkg.versionCode = pkg.mVersionCode;
8981
8982                    // Update the disabled system child packages to point to the package too.
8983                    final int childCount = updatedPkg.childPackageNames != null
8984                            ? updatedPkg.childPackageNames.size() : 0;
8985                    for (int i = 0; i < childCount; i++) {
8986                        String childPackageName = updatedPkg.childPackageNames.get(i);
8987                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8988                                childPackageName);
8989                        if (updatedChildPkg != null) {
8990                            updatedChildPkg.pkg = pkg;
8991                            updatedChildPkg.versionCode = pkg.mVersionCode;
8992                        }
8993                    }
8994                } else {
8995                    // The current app on the system partition is better than
8996                    // what we have updated to on the data partition; switch
8997                    // back to the system partition version.
8998                    // At this point, its safely assumed that package installation for
8999                    // apps in system partition will go through. If not there won't be a working
9000                    // version of the app
9001                    // writer
9002                    synchronized (mPackages) {
9003                        // Just remove the loaded entries from package lists.
9004                        mPackages.remove(ps.name);
9005                    }
9006
9007                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9008                            + " reverting from " + ps.codePathString
9009                            + ": new version " + pkg.mVersionCode
9010                            + " better than installed " + ps.versionCode);
9011
9012                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9013                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9014                    synchronized (mInstallLock) {
9015                        args.cleanUpResourcesLI();
9016                    }
9017                    synchronized (mPackages) {
9018                        mSettings.enableSystemPackageLPw(ps.name);
9019                    }
9020                    isUpdatedPkgBetter = true;
9021                }
9022            }
9023        }
9024
9025        String resourcePath = null;
9026        String baseResourcePath = null;
9027        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9028            if (ps != null && ps.resourcePathString != null) {
9029                resourcePath = ps.resourcePathString;
9030                baseResourcePath = ps.resourcePathString;
9031            } else {
9032                // Should not happen at all. Just log an error.
9033                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9034            }
9035        } else {
9036            resourcePath = pkg.codePath;
9037            baseResourcePath = pkg.baseCodePath;
9038        }
9039
9040        // Set application objects path explicitly.
9041        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9042        pkg.setApplicationInfoCodePath(pkg.codePath);
9043        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9044        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9045        pkg.setApplicationInfoResourcePath(resourcePath);
9046        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9047        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9048
9049        // throw an exception if we have an update to a system application, but, it's not more
9050        // recent than the package we've already scanned
9051        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9052            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9053                    + scanFile + " ignored: updated version " + ps.versionCode
9054                    + " better than this " + pkg.mVersionCode);
9055        }
9056
9057        if (isUpdatedPkg) {
9058            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9059            // initially
9060            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9061
9062            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9063            // flag set initially
9064            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9065                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9066            }
9067        }
9068
9069        // Verify certificates against what was last scanned
9070        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9071
9072        /*
9073         * A new system app appeared, but we already had a non-system one of the
9074         * same name installed earlier.
9075         */
9076        boolean shouldHideSystemApp = false;
9077        if (!isUpdatedPkg && ps != null
9078                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9079            /*
9080             * Check to make sure the signatures match first. If they don't,
9081             * wipe the installed application and its data.
9082             */
9083            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9084                    != PackageManager.SIGNATURE_MATCH) {
9085                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9086                        + " signatures don't match existing userdata copy; removing");
9087                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9088                        "scanPackageInternalLI")) {
9089                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9090                }
9091                ps = null;
9092            } else {
9093                /*
9094                 * If the newly-added system app is an older version than the
9095                 * already installed version, hide it. It will be scanned later
9096                 * and re-added like an update.
9097                 */
9098                if (pkg.mVersionCode <= ps.versionCode) {
9099                    shouldHideSystemApp = true;
9100                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9101                            + " but new version " + pkg.mVersionCode + " better than installed "
9102                            + ps.versionCode + "; hiding system");
9103                } else {
9104                    /*
9105                     * The newly found system app is a newer version that the
9106                     * one previously installed. Simply remove the
9107                     * already-installed application and replace it with our own
9108                     * while keeping the application data.
9109                     */
9110                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9111                            + " reverting from " + ps.codePathString + ": new version "
9112                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9113                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9114                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9115                    synchronized (mInstallLock) {
9116                        args.cleanUpResourcesLI();
9117                    }
9118                }
9119            }
9120        }
9121
9122        // The apk is forward locked (not public) if its code and resources
9123        // are kept in different files. (except for app in either system or
9124        // vendor path).
9125        // TODO grab this value from PackageSettings
9126        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9127            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9128                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9129            }
9130        }
9131
9132        final int userId = ((user == null) ? 0 : user.getIdentifier());
9133        if (ps != null && ps.getInstantApp(userId)) {
9134            scanFlags |= SCAN_AS_INSTANT_APP;
9135        }
9136
9137        // Note that we invoke the following method only if we are about to unpack an application
9138        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9139                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9140
9141        /*
9142         * If the system app should be overridden by a previously installed
9143         * data, hide the system app now and let the /data/app scan pick it up
9144         * again.
9145         */
9146        if (shouldHideSystemApp) {
9147            synchronized (mPackages) {
9148                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9149            }
9150        }
9151
9152        return scannedPkg;
9153    }
9154
9155    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9156        // Derive the new package synthetic package name
9157        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9158                + pkg.staticSharedLibVersion);
9159    }
9160
9161    private static String fixProcessName(String defProcessName,
9162            String processName) {
9163        if (processName == null) {
9164            return defProcessName;
9165        }
9166        return processName;
9167    }
9168
9169    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9170            throws PackageManagerException {
9171        if (pkgSetting.signatures.mSignatures != null) {
9172            // Already existing package. Make sure signatures match
9173            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9174                    == PackageManager.SIGNATURE_MATCH;
9175            if (!match) {
9176                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9177                        == PackageManager.SIGNATURE_MATCH;
9178            }
9179            if (!match) {
9180                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9181                        == PackageManager.SIGNATURE_MATCH;
9182            }
9183            if (!match) {
9184                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9185                        + pkg.packageName + " signatures do not match the "
9186                        + "previously installed version; ignoring!");
9187            }
9188        }
9189
9190        // Check for shared user signatures
9191        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9192            // Already existing package. Make sure signatures match
9193            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9194                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9195            if (!match) {
9196                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9197                        == PackageManager.SIGNATURE_MATCH;
9198            }
9199            if (!match) {
9200                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9201                        == PackageManager.SIGNATURE_MATCH;
9202            }
9203            if (!match) {
9204                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9205                        "Package " + pkg.packageName
9206                        + " has no signatures that match those in shared user "
9207                        + pkgSetting.sharedUser.name + "; ignoring!");
9208            }
9209        }
9210    }
9211
9212    /**
9213     * Enforces that only the system UID or root's UID can call a method exposed
9214     * via Binder.
9215     *
9216     * @param message used as message if SecurityException is thrown
9217     * @throws SecurityException if the caller is not system or root
9218     */
9219    private static final void enforceSystemOrRoot(String message) {
9220        final int uid = Binder.getCallingUid();
9221        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9222            throw new SecurityException(message);
9223        }
9224    }
9225
9226    @Override
9227    public void performFstrimIfNeeded() {
9228        enforceSystemOrRoot("Only the system can request fstrim");
9229
9230        // Before everything else, see whether we need to fstrim.
9231        try {
9232            IStorageManager sm = PackageHelper.getStorageManager();
9233            if (sm != null) {
9234                boolean doTrim = false;
9235                final long interval = android.provider.Settings.Global.getLong(
9236                        mContext.getContentResolver(),
9237                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9238                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9239                if (interval > 0) {
9240                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9241                    if (timeSinceLast > interval) {
9242                        doTrim = true;
9243                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9244                                + "; running immediately");
9245                    }
9246                }
9247                if (doTrim) {
9248                    final boolean dexOptDialogShown;
9249                    synchronized (mPackages) {
9250                        dexOptDialogShown = mDexOptDialogShown;
9251                    }
9252                    if (!isFirstBoot() && dexOptDialogShown) {
9253                        try {
9254                            ActivityManager.getService().showBootMessage(
9255                                    mContext.getResources().getString(
9256                                            R.string.android_upgrading_fstrim), true);
9257                        } catch (RemoteException e) {
9258                        }
9259                    }
9260                    sm.runMaintenance();
9261                }
9262            } else {
9263                Slog.e(TAG, "storageManager service unavailable!");
9264            }
9265        } catch (RemoteException e) {
9266            // Can't happen; StorageManagerService is local
9267        }
9268    }
9269
9270    @Override
9271    public void updatePackagesIfNeeded() {
9272        enforceSystemOrRoot("Only the system can request package update");
9273
9274        // We need to re-extract after an OTA.
9275        boolean causeUpgrade = isUpgrade();
9276
9277        // First boot or factory reset.
9278        // Note: we also handle devices that are upgrading to N right now as if it is their
9279        //       first boot, as they do not have profile data.
9280        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9281
9282        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9283        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9284
9285        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9286            return;
9287        }
9288
9289        List<PackageParser.Package> pkgs;
9290        synchronized (mPackages) {
9291            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9292        }
9293
9294        final long startTime = System.nanoTime();
9295        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9296                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9297                    false /* bootComplete */);
9298
9299        final int elapsedTimeSeconds =
9300                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9301
9302        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9303        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9304        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9305        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9306        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9307    }
9308
9309    /*
9310     * Return the prebuilt profile path given a package base code path.
9311     */
9312    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9313        return pkg.baseCodePath + ".prof";
9314    }
9315
9316    /**
9317     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9318     * containing statistics about the invocation. The array consists of three elements,
9319     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9320     * and {@code numberOfPackagesFailed}.
9321     */
9322    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9323            String compilerFilter, boolean bootComplete) {
9324
9325        int numberOfPackagesVisited = 0;
9326        int numberOfPackagesOptimized = 0;
9327        int numberOfPackagesSkipped = 0;
9328        int numberOfPackagesFailed = 0;
9329        final int numberOfPackagesToDexopt = pkgs.size();
9330
9331        for (PackageParser.Package pkg : pkgs) {
9332            numberOfPackagesVisited++;
9333
9334            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9335                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9336                // that are already compiled.
9337                File profileFile = new File(getPrebuildProfilePath(pkg));
9338                // Copy profile if it exists.
9339                if (profileFile.exists()) {
9340                    try {
9341                        // We could also do this lazily before calling dexopt in
9342                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9343                        // is that we don't have a good way to say "do this only once".
9344                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9345                                pkg.applicationInfo.uid, pkg.packageName)) {
9346                            Log.e(TAG, "Installer failed to copy system profile!");
9347                        }
9348                    } catch (Exception e) {
9349                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9350                                e);
9351                    }
9352                }
9353            }
9354
9355            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9356                if (DEBUG_DEXOPT) {
9357                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9358                }
9359                numberOfPackagesSkipped++;
9360                continue;
9361            }
9362
9363            if (DEBUG_DEXOPT) {
9364                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9365                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9366            }
9367
9368            if (showDialog) {
9369                try {
9370                    ActivityManager.getService().showBootMessage(
9371                            mContext.getResources().getString(R.string.android_upgrading_apk,
9372                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9373                } catch (RemoteException e) {
9374                }
9375                synchronized (mPackages) {
9376                    mDexOptDialogShown = true;
9377                }
9378            }
9379
9380            // If the OTA updates a system app which was previously preopted to a non-preopted state
9381            // the app might end up being verified at runtime. That's because by default the apps
9382            // are verify-profile but for preopted apps there's no profile.
9383            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9384            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9385            // filter (by default 'quicken').
9386            // Note that at this stage unused apps are already filtered.
9387            if (isSystemApp(pkg) &&
9388                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9389                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9390                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9391            }
9392
9393            // checkProfiles is false to avoid merging profiles during boot which
9394            // might interfere with background compilation (b/28612421).
9395            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9396            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9397            // trade-off worth doing to save boot time work.
9398            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9399            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9400                    pkg.packageName,
9401                    compilerFilter,
9402                    dexoptFlags));
9403
9404            boolean secondaryDexOptStatus = true;
9405            if (pkg.isSystemApp()) {
9406                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9407                // too much boot after an OTA.
9408                int secondaryDexoptFlags = dexoptFlags |
9409                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9410                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9411                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9412                        pkg.packageName,
9413                        compilerFilter,
9414                        secondaryDexoptFlags));
9415            }
9416
9417            if (secondaryDexOptStatus) {
9418                switch (primaryDexOptStaus) {
9419                    case PackageDexOptimizer.DEX_OPT_PERFORMED:
9420                        numberOfPackagesOptimized++;
9421                        break;
9422                    case PackageDexOptimizer.DEX_OPT_SKIPPED:
9423                        numberOfPackagesSkipped++;
9424                        break;
9425                    case PackageDexOptimizer.DEX_OPT_FAILED:
9426                        numberOfPackagesFailed++;
9427                        break;
9428                    default:
9429                        Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9430                        break;
9431                }
9432            } else {
9433                numberOfPackagesFailed++;
9434            }
9435        }
9436
9437        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9438                numberOfPackagesFailed };
9439    }
9440
9441    @Override
9442    public void notifyPackageUse(String packageName, int reason) {
9443        synchronized (mPackages) {
9444            final int callingUid = Binder.getCallingUid();
9445            final int callingUserId = UserHandle.getUserId(callingUid);
9446            if (getInstantAppPackageName(callingUid) != null) {
9447                if (!isCallerSameApp(packageName, callingUid)) {
9448                    return;
9449                }
9450            } else {
9451                if (isInstantApp(packageName, callingUserId)) {
9452                    return;
9453                }
9454            }
9455            final PackageParser.Package p = mPackages.get(packageName);
9456            if (p == null) {
9457                return;
9458            }
9459            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9460        }
9461    }
9462
9463    @Override
9464    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9465            List<String> classPaths, String loaderIsa) {
9466        int userId = UserHandle.getCallingUserId();
9467        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9468        if (ai == null) {
9469            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9470                + loadingPackageName + ", user=" + userId);
9471            return;
9472        }
9473        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9474    }
9475
9476    @Override
9477    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9478            IDexModuleRegisterCallback callback) {
9479        int userId = UserHandle.getCallingUserId();
9480        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9481        DexManager.RegisterDexModuleResult result;
9482        if (ai == null) {
9483            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9484                     " calling user. package=" + packageName + ", user=" + userId);
9485            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9486        } else {
9487            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9488        }
9489
9490        if (callback != null) {
9491            mHandler.post(() -> {
9492                try {
9493                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9494                } catch (RemoteException e) {
9495                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9496                }
9497            });
9498        }
9499    }
9500
9501    /**
9502     * Ask the package manager to perform a dex-opt with the given compiler filter.
9503     *
9504     * Note: exposed only for the shell command to allow moving packages explicitly to a
9505     *       definite state.
9506     */
9507    @Override
9508    public boolean performDexOptMode(String packageName,
9509            boolean checkProfiles, String targetCompilerFilter, boolean force,
9510            boolean bootComplete, String splitName) {
9511        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9512                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9513                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9514        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9515                splitName, flags));
9516    }
9517
9518    /**
9519     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9520     * secondary dex files belonging to the given package.
9521     *
9522     * Note: exposed only for the shell command to allow moving packages explicitly to a
9523     *       definite state.
9524     */
9525    @Override
9526    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9527            boolean force) {
9528        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9529                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9530                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9531                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9532        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9533    }
9534
9535    /*package*/ boolean performDexOpt(DexoptOptions options) {
9536        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9537            return false;
9538        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9539            return false;
9540        }
9541
9542        if (options.isDexoptOnlySecondaryDex()) {
9543            return mDexManager.dexoptSecondaryDex(options);
9544        } else {
9545            int dexoptStatus = performDexOptWithStatus(options);
9546            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9547        }
9548    }
9549
9550    /**
9551     * Perform dexopt on the given package and return one of following result:
9552     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9553     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9554     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9555     */
9556    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9557        return performDexOptTraced(options);
9558    }
9559
9560    private int performDexOptTraced(DexoptOptions options) {
9561        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9562        try {
9563            return performDexOptInternal(options);
9564        } finally {
9565            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9566        }
9567    }
9568
9569    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9570    // if the package can now be considered up to date for the given filter.
9571    private int performDexOptInternal(DexoptOptions options) {
9572        PackageParser.Package p;
9573        synchronized (mPackages) {
9574            p = mPackages.get(options.getPackageName());
9575            if (p == null) {
9576                // Package could not be found. Report failure.
9577                return PackageDexOptimizer.DEX_OPT_FAILED;
9578            }
9579            mPackageUsage.maybeWriteAsync(mPackages);
9580            mCompilerStats.maybeWriteAsync();
9581        }
9582        long callingId = Binder.clearCallingIdentity();
9583        try {
9584            synchronized (mInstallLock) {
9585                return performDexOptInternalWithDependenciesLI(p, options);
9586            }
9587        } finally {
9588            Binder.restoreCallingIdentity(callingId);
9589        }
9590    }
9591
9592    public ArraySet<String> getOptimizablePackages() {
9593        ArraySet<String> pkgs = new ArraySet<String>();
9594        synchronized (mPackages) {
9595            for (PackageParser.Package p : mPackages.values()) {
9596                if (PackageDexOptimizer.canOptimizePackage(p)) {
9597                    pkgs.add(p.packageName);
9598                }
9599            }
9600        }
9601        return pkgs;
9602    }
9603
9604    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9605            DexoptOptions options) {
9606        // Select the dex optimizer based on the force parameter.
9607        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9608        //       allocate an object here.
9609        PackageDexOptimizer pdo = options.isForce()
9610                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9611                : mPackageDexOptimizer;
9612
9613        // Dexopt all dependencies first. Note: we ignore the return value and march on
9614        // on errors.
9615        // Note that we are going to call performDexOpt on those libraries as many times as
9616        // they are referenced in packages. When we do a batch of performDexOpt (for example
9617        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9618        // and the first package that uses the library will dexopt it. The
9619        // others will see that the compiled code for the library is up to date.
9620        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9621        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9622        if (!deps.isEmpty()) {
9623            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9624                    options.getCompilerFilter(), options.getSplitName(),
9625                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9626            for (PackageParser.Package depPackage : deps) {
9627                // TODO: Analyze and investigate if we (should) profile libraries.
9628                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9629                        getOrCreateCompilerPackageStats(depPackage),
9630                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9631            }
9632        }
9633        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9634                getOrCreateCompilerPackageStats(p),
9635                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9636    }
9637
9638    /**
9639     * Reconcile the information we have about the secondary dex files belonging to
9640     * {@code packagName} and the actual dex files. For all dex files that were
9641     * deleted, update the internal records and delete the generated oat files.
9642     */
9643    @Override
9644    public void reconcileSecondaryDexFiles(String packageName) {
9645        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9646            return;
9647        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9648            return;
9649        }
9650        mDexManager.reconcileSecondaryDexFiles(packageName);
9651    }
9652
9653    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9654    // a reference there.
9655    /*package*/ DexManager getDexManager() {
9656        return mDexManager;
9657    }
9658
9659    /**
9660     * Execute the background dexopt job immediately.
9661     */
9662    @Override
9663    public boolean runBackgroundDexoptJob() {
9664        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9665            return false;
9666        }
9667        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9668    }
9669
9670    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9671        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9672                || p.usesStaticLibraries != null) {
9673            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9674            Set<String> collectedNames = new HashSet<>();
9675            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9676
9677            retValue.remove(p);
9678
9679            return retValue;
9680        } else {
9681            return Collections.emptyList();
9682        }
9683    }
9684
9685    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9686            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9687        if (!collectedNames.contains(p.packageName)) {
9688            collectedNames.add(p.packageName);
9689            collected.add(p);
9690
9691            if (p.usesLibraries != null) {
9692                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9693                        null, collected, collectedNames);
9694            }
9695            if (p.usesOptionalLibraries != null) {
9696                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9697                        null, collected, collectedNames);
9698            }
9699            if (p.usesStaticLibraries != null) {
9700                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9701                        p.usesStaticLibrariesVersions, collected, collectedNames);
9702            }
9703        }
9704    }
9705
9706    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9707            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9708        final int libNameCount = libs.size();
9709        for (int i = 0; i < libNameCount; i++) {
9710            String libName = libs.get(i);
9711            int version = (versions != null && versions.length == libNameCount)
9712                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9713            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9714            if (libPkg != null) {
9715                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9716            }
9717        }
9718    }
9719
9720    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9721        synchronized (mPackages) {
9722            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9723            if (libEntry != null) {
9724                return mPackages.get(libEntry.apk);
9725            }
9726            return null;
9727        }
9728    }
9729
9730    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9731        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9732        if (versionedLib == null) {
9733            return null;
9734        }
9735        return versionedLib.get(version);
9736    }
9737
9738    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9739        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9740                pkg.staticSharedLibName);
9741        if (versionedLib == null) {
9742            return null;
9743        }
9744        int previousLibVersion = -1;
9745        final int versionCount = versionedLib.size();
9746        for (int i = 0; i < versionCount; i++) {
9747            final int libVersion = versionedLib.keyAt(i);
9748            if (libVersion < pkg.staticSharedLibVersion) {
9749                previousLibVersion = Math.max(previousLibVersion, libVersion);
9750            }
9751        }
9752        if (previousLibVersion >= 0) {
9753            return versionedLib.get(previousLibVersion);
9754        }
9755        return null;
9756    }
9757
9758    public void shutdown() {
9759        mPackageUsage.writeNow(mPackages);
9760        mCompilerStats.writeNow();
9761        mDexManager.writePackageDexUsageNow();
9762    }
9763
9764    @Override
9765    public void dumpProfiles(String packageName) {
9766        PackageParser.Package pkg;
9767        synchronized (mPackages) {
9768            pkg = mPackages.get(packageName);
9769            if (pkg == null) {
9770                throw new IllegalArgumentException("Unknown package: " + packageName);
9771            }
9772        }
9773        /* Only the shell, root, or the app user should be able to dump profiles. */
9774        int callingUid = Binder.getCallingUid();
9775        if (callingUid != Process.SHELL_UID &&
9776            callingUid != Process.ROOT_UID &&
9777            callingUid != pkg.applicationInfo.uid) {
9778            throw new SecurityException("dumpProfiles");
9779        }
9780
9781        synchronized (mInstallLock) {
9782            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9783            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9784            try {
9785                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9786                String codePaths = TextUtils.join(";", allCodePaths);
9787                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9788            } catch (InstallerException e) {
9789                Slog.w(TAG, "Failed to dump profiles", e);
9790            }
9791            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9792        }
9793    }
9794
9795    @Override
9796    public void forceDexOpt(String packageName) {
9797        enforceSystemOrRoot("forceDexOpt");
9798
9799        PackageParser.Package pkg;
9800        synchronized (mPackages) {
9801            pkg = mPackages.get(packageName);
9802            if (pkg == null) {
9803                throw new IllegalArgumentException("Unknown package: " + packageName);
9804            }
9805        }
9806
9807        synchronized (mInstallLock) {
9808            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9809
9810            // Whoever is calling forceDexOpt wants a compiled package.
9811            // Don't use profiles since that may cause compilation to be skipped.
9812            final int res = performDexOptInternalWithDependenciesLI(
9813                    pkg,
9814                    new DexoptOptions(packageName,
9815                            getDefaultCompilerFilter(),
9816                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9817
9818            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9819            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9820                throw new IllegalStateException("Failed to dexopt: " + res);
9821            }
9822        }
9823    }
9824
9825    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9826        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9827            Slog.w(TAG, "Unable to update from " + oldPkg.name
9828                    + " to " + newPkg.packageName
9829                    + ": old package not in system partition");
9830            return false;
9831        } else if (mPackages.get(oldPkg.name) != null) {
9832            Slog.w(TAG, "Unable to update from " + oldPkg.name
9833                    + " to " + newPkg.packageName
9834                    + ": old package still exists");
9835            return false;
9836        }
9837        return true;
9838    }
9839
9840    void removeCodePathLI(File codePath) {
9841        if (codePath.isDirectory()) {
9842            try {
9843                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9844            } catch (InstallerException e) {
9845                Slog.w(TAG, "Failed to remove code path", e);
9846            }
9847        } else {
9848            codePath.delete();
9849        }
9850    }
9851
9852    private int[] resolveUserIds(int userId) {
9853        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9854    }
9855
9856    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9857        if (pkg == null) {
9858            Slog.wtf(TAG, "Package was null!", new Throwable());
9859            return;
9860        }
9861        clearAppDataLeafLIF(pkg, userId, flags);
9862        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9863        for (int i = 0; i < childCount; i++) {
9864            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9865        }
9866    }
9867
9868    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9869        final PackageSetting ps;
9870        synchronized (mPackages) {
9871            ps = mSettings.mPackages.get(pkg.packageName);
9872        }
9873        for (int realUserId : resolveUserIds(userId)) {
9874            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9875            try {
9876                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9877                        ceDataInode);
9878            } catch (InstallerException e) {
9879                Slog.w(TAG, String.valueOf(e));
9880            }
9881        }
9882    }
9883
9884    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9885        if (pkg == null) {
9886            Slog.wtf(TAG, "Package was null!", new Throwable());
9887            return;
9888        }
9889        destroyAppDataLeafLIF(pkg, userId, flags);
9890        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9891        for (int i = 0; i < childCount; i++) {
9892            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9893        }
9894    }
9895
9896    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9897        final PackageSetting ps;
9898        synchronized (mPackages) {
9899            ps = mSettings.mPackages.get(pkg.packageName);
9900        }
9901        for (int realUserId : resolveUserIds(userId)) {
9902            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9903            try {
9904                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9905                        ceDataInode);
9906            } catch (InstallerException e) {
9907                Slog.w(TAG, String.valueOf(e));
9908            }
9909            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9910        }
9911    }
9912
9913    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9914        if (pkg == null) {
9915            Slog.wtf(TAG, "Package was null!", new Throwable());
9916            return;
9917        }
9918        destroyAppProfilesLeafLIF(pkg);
9919        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9920        for (int i = 0; i < childCount; i++) {
9921            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9922        }
9923    }
9924
9925    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9926        try {
9927            mInstaller.destroyAppProfiles(pkg.packageName);
9928        } catch (InstallerException e) {
9929            Slog.w(TAG, String.valueOf(e));
9930        }
9931    }
9932
9933    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9934        if (pkg == null) {
9935            Slog.wtf(TAG, "Package was null!", new Throwable());
9936            return;
9937        }
9938        clearAppProfilesLeafLIF(pkg);
9939        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9940        for (int i = 0; i < childCount; i++) {
9941            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9942        }
9943    }
9944
9945    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9946        try {
9947            mInstaller.clearAppProfiles(pkg.packageName);
9948        } catch (InstallerException e) {
9949            Slog.w(TAG, String.valueOf(e));
9950        }
9951    }
9952
9953    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9954            long lastUpdateTime) {
9955        // Set parent install/update time
9956        PackageSetting ps = (PackageSetting) pkg.mExtras;
9957        if (ps != null) {
9958            ps.firstInstallTime = firstInstallTime;
9959            ps.lastUpdateTime = lastUpdateTime;
9960        }
9961        // Set children install/update time
9962        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9963        for (int i = 0; i < childCount; i++) {
9964            PackageParser.Package childPkg = pkg.childPackages.get(i);
9965            ps = (PackageSetting) childPkg.mExtras;
9966            if (ps != null) {
9967                ps.firstInstallTime = firstInstallTime;
9968                ps.lastUpdateTime = lastUpdateTime;
9969            }
9970        }
9971    }
9972
9973    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9974            SharedLibraryEntry file,
9975            PackageParser.Package changingLib) {
9976        if (file.path != null) {
9977            usesLibraryFiles.add(file.path);
9978            return;
9979        }
9980        PackageParser.Package p = mPackages.get(file.apk);
9981        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9982            // If we are doing this while in the middle of updating a library apk,
9983            // then we need to make sure to use that new apk for determining the
9984            // dependencies here.  (We haven't yet finished committing the new apk
9985            // to the package manager state.)
9986            if (p == null || p.packageName.equals(changingLib.packageName)) {
9987                p = changingLib;
9988            }
9989        }
9990        if (p != null) {
9991            usesLibraryFiles.addAll(p.getAllCodePaths());
9992            if (p.usesLibraryFiles != null) {
9993                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9994            }
9995        }
9996    }
9997
9998    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9999            PackageParser.Package changingLib) throws PackageManagerException {
10000        if (pkg == null) {
10001            return;
10002        }
10003        // The collection used here must maintain the order of addition (so
10004        // that libraries are searched in the correct order) and must have no
10005        // duplicates.
10006        Set<String> usesLibraryFiles = null;
10007        if (pkg.usesLibraries != null) {
10008            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10009                    null, null, pkg.packageName, changingLib, true, null);
10010        }
10011        if (pkg.usesStaticLibraries != null) {
10012            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10013                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10014                    pkg.packageName, changingLib, true, usesLibraryFiles);
10015        }
10016        if (pkg.usesOptionalLibraries != null) {
10017            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10018                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10019        }
10020        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10021            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10022        } else {
10023            pkg.usesLibraryFiles = null;
10024        }
10025    }
10026
10027    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10028            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10029            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10030            boolean required, @Nullable Set<String> outUsedLibraries)
10031            throws PackageManagerException {
10032        final int libCount = requestedLibraries.size();
10033        for (int i = 0; i < libCount; i++) {
10034            final String libName = requestedLibraries.get(i);
10035            final int libVersion = requiredVersions != null ? requiredVersions[i]
10036                    : SharedLibraryInfo.VERSION_UNDEFINED;
10037            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10038            if (libEntry == null) {
10039                if (required) {
10040                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10041                            "Package " + packageName + " requires unavailable shared library "
10042                                    + libName + "; failing!");
10043                } else if (DEBUG_SHARED_LIBRARIES) {
10044                    Slog.i(TAG, "Package " + packageName
10045                            + " desires unavailable shared library "
10046                            + libName + "; ignoring!");
10047                }
10048            } else {
10049                if (requiredVersions != null && requiredCertDigests != null) {
10050                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10051                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10052                            "Package " + packageName + " requires unavailable static shared"
10053                                    + " library " + libName + " version "
10054                                    + libEntry.info.getVersion() + "; failing!");
10055                    }
10056
10057                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10058                    if (libPkg == null) {
10059                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10060                                "Package " + packageName + " requires unavailable static shared"
10061                                        + " library; failing!");
10062                    }
10063
10064                    String expectedCertDigest = requiredCertDigests[i];
10065                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10066                                libPkg.mSignatures[0]);
10067                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10068                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10069                                "Package " + packageName + " requires differently signed" +
10070                                        " static shared library; failing!");
10071                    }
10072                }
10073
10074                if (outUsedLibraries == null) {
10075                    // Use LinkedHashSet to preserve the order of files added to
10076                    // usesLibraryFiles while eliminating duplicates.
10077                    outUsedLibraries = new LinkedHashSet<>();
10078                }
10079                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10080            }
10081        }
10082        return outUsedLibraries;
10083    }
10084
10085    private static boolean hasString(List<String> list, List<String> which) {
10086        if (list == null) {
10087            return false;
10088        }
10089        for (int i=list.size()-1; i>=0; i--) {
10090            for (int j=which.size()-1; j>=0; j--) {
10091                if (which.get(j).equals(list.get(i))) {
10092                    return true;
10093                }
10094            }
10095        }
10096        return false;
10097    }
10098
10099    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10100            PackageParser.Package changingPkg) {
10101        ArrayList<PackageParser.Package> res = null;
10102        for (PackageParser.Package pkg : mPackages.values()) {
10103            if (changingPkg != null
10104                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10105                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10106                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10107                            changingPkg.staticSharedLibName)) {
10108                return null;
10109            }
10110            if (res == null) {
10111                res = new ArrayList<>();
10112            }
10113            res.add(pkg);
10114            try {
10115                updateSharedLibrariesLPr(pkg, changingPkg);
10116            } catch (PackageManagerException e) {
10117                // If a system app update or an app and a required lib missing we
10118                // delete the package and for updated system apps keep the data as
10119                // it is better for the user to reinstall than to be in an limbo
10120                // state. Also libs disappearing under an app should never happen
10121                // - just in case.
10122                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10123                    final int flags = pkg.isUpdatedSystemApp()
10124                            ? PackageManager.DELETE_KEEP_DATA : 0;
10125                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10126                            flags , null, true, null);
10127                }
10128                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10129            }
10130        }
10131        return res;
10132    }
10133
10134    /**
10135     * Derive the value of the {@code cpuAbiOverride} based on the provided
10136     * value and an optional stored value from the package settings.
10137     */
10138    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10139        String cpuAbiOverride = null;
10140
10141        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10142            cpuAbiOverride = null;
10143        } else if (abiOverride != null) {
10144            cpuAbiOverride = abiOverride;
10145        } else if (settings != null) {
10146            cpuAbiOverride = settings.cpuAbiOverrideString;
10147        }
10148
10149        return cpuAbiOverride;
10150    }
10151
10152    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10153            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10154                    throws PackageManagerException {
10155        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10156        // If the package has children and this is the first dive in the function
10157        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10158        // whether all packages (parent and children) would be successfully scanned
10159        // before the actual scan since scanning mutates internal state and we want
10160        // to atomically install the package and its children.
10161        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10162            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10163                scanFlags |= SCAN_CHECK_ONLY;
10164            }
10165        } else {
10166            scanFlags &= ~SCAN_CHECK_ONLY;
10167        }
10168
10169        final PackageParser.Package scannedPkg;
10170        try {
10171            // Scan the parent
10172            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10173            // Scan the children
10174            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10175            for (int i = 0; i < childCount; i++) {
10176                PackageParser.Package childPkg = pkg.childPackages.get(i);
10177                scanPackageLI(childPkg, policyFlags,
10178                        scanFlags, currentTime, user);
10179            }
10180        } finally {
10181            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10182        }
10183
10184        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10185            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10186        }
10187
10188        return scannedPkg;
10189    }
10190
10191    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10192            int scanFlags, long currentTime, @Nullable UserHandle user)
10193                    throws PackageManagerException {
10194        boolean success = false;
10195        try {
10196            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10197                    currentTime, user);
10198            success = true;
10199            return res;
10200        } finally {
10201            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10202                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10203                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10204                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10205                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10206            }
10207        }
10208    }
10209
10210    /**
10211     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10212     */
10213    private static boolean apkHasCode(String fileName) {
10214        StrictJarFile jarFile = null;
10215        try {
10216            jarFile = new StrictJarFile(fileName,
10217                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10218            return jarFile.findEntry("classes.dex") != null;
10219        } catch (IOException ignore) {
10220        } finally {
10221            try {
10222                if (jarFile != null) {
10223                    jarFile.close();
10224                }
10225            } catch (IOException ignore) {}
10226        }
10227        return false;
10228    }
10229
10230    /**
10231     * Enforces code policy for the package. This ensures that if an APK has
10232     * declared hasCode="true" in its manifest that the APK actually contains
10233     * code.
10234     *
10235     * @throws PackageManagerException If bytecode could not be found when it should exist
10236     */
10237    private static void assertCodePolicy(PackageParser.Package pkg)
10238            throws PackageManagerException {
10239        final boolean shouldHaveCode =
10240                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10241        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10242            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10243                    "Package " + pkg.baseCodePath + " code is missing");
10244        }
10245
10246        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10247            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10248                final boolean splitShouldHaveCode =
10249                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10250                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10251                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10252                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10253                }
10254            }
10255        }
10256    }
10257
10258    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10259            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10260                    throws PackageManagerException {
10261        if (DEBUG_PACKAGE_SCANNING) {
10262            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10263                Log.d(TAG, "Scanning package " + pkg.packageName);
10264        }
10265
10266        applyPolicy(pkg, policyFlags);
10267
10268        assertPackageIsValid(pkg, policyFlags, scanFlags);
10269
10270        if (Build.IS_DEBUGGABLE &&
10271                pkg.isPrivilegedApp() &&
10272                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10273            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10274        }
10275
10276        // Initialize package source and resource directories
10277        final File scanFile = new File(pkg.codePath);
10278        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10279        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10280
10281        SharedUserSetting suid = null;
10282        PackageSetting pkgSetting = null;
10283
10284        // Getting the package setting may have a side-effect, so if we
10285        // are only checking if scan would succeed, stash a copy of the
10286        // old setting to restore at the end.
10287        PackageSetting nonMutatedPs = null;
10288
10289        // We keep references to the derived CPU Abis from settings in oder to reuse
10290        // them in the case where we're not upgrading or booting for the first time.
10291        String primaryCpuAbiFromSettings = null;
10292        String secondaryCpuAbiFromSettings = null;
10293
10294        // writer
10295        synchronized (mPackages) {
10296            if (pkg.mSharedUserId != null) {
10297                // SIDE EFFECTS; may potentially allocate a new shared user
10298                suid = mSettings.getSharedUserLPw(
10299                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10300                if (DEBUG_PACKAGE_SCANNING) {
10301                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10302                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10303                                + "): packages=" + suid.packages);
10304                }
10305            }
10306
10307            // Check if we are renaming from an original package name.
10308            PackageSetting origPackage = null;
10309            String realName = null;
10310            if (pkg.mOriginalPackages != null) {
10311                // This package may need to be renamed to a previously
10312                // installed name.  Let's check on that...
10313                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10314                if (pkg.mOriginalPackages.contains(renamed)) {
10315                    // This package had originally been installed as the
10316                    // original name, and we have already taken care of
10317                    // transitioning to the new one.  Just update the new
10318                    // one to continue using the old name.
10319                    realName = pkg.mRealPackage;
10320                    if (!pkg.packageName.equals(renamed)) {
10321                        // Callers into this function may have already taken
10322                        // care of renaming the package; only do it here if
10323                        // it is not already done.
10324                        pkg.setPackageName(renamed);
10325                    }
10326                } else {
10327                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10328                        if ((origPackage = mSettings.getPackageLPr(
10329                                pkg.mOriginalPackages.get(i))) != null) {
10330                            // We do have the package already installed under its
10331                            // original name...  should we use it?
10332                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10333                                // New package is not compatible with original.
10334                                origPackage = null;
10335                                continue;
10336                            } else if (origPackage.sharedUser != null) {
10337                                // Make sure uid is compatible between packages.
10338                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10339                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10340                                            + " to " + pkg.packageName + ": old uid "
10341                                            + origPackage.sharedUser.name
10342                                            + " differs from " + pkg.mSharedUserId);
10343                                    origPackage = null;
10344                                    continue;
10345                                }
10346                                // TODO: Add case when shared user id is added [b/28144775]
10347                            } else {
10348                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10349                                        + pkg.packageName + " to old name " + origPackage.name);
10350                            }
10351                            break;
10352                        }
10353                    }
10354                }
10355            }
10356
10357            if (mTransferedPackages.contains(pkg.packageName)) {
10358                Slog.w(TAG, "Package " + pkg.packageName
10359                        + " was transferred to another, but its .apk remains");
10360            }
10361
10362            // See comments in nonMutatedPs declaration
10363            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10364                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10365                if (foundPs != null) {
10366                    nonMutatedPs = new PackageSetting(foundPs);
10367                }
10368            }
10369
10370            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10371                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10372                if (foundPs != null) {
10373                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10374                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10375                }
10376            }
10377
10378            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10379            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10380                PackageManagerService.reportSettingsProblem(Log.WARN,
10381                        "Package " + pkg.packageName + " shared user changed from "
10382                                + (pkgSetting.sharedUser != null
10383                                        ? pkgSetting.sharedUser.name : "<nothing>")
10384                                + " to "
10385                                + (suid != null ? suid.name : "<nothing>")
10386                                + "; replacing with new");
10387                pkgSetting = null;
10388            }
10389            final PackageSetting oldPkgSetting =
10390                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10391            final PackageSetting disabledPkgSetting =
10392                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10393
10394            String[] usesStaticLibraries = null;
10395            if (pkg.usesStaticLibraries != null) {
10396                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10397                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10398            }
10399
10400            if (pkgSetting == null) {
10401                final String parentPackageName = (pkg.parentPackage != null)
10402                        ? pkg.parentPackage.packageName : null;
10403                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10404                // REMOVE SharedUserSetting from method; update in a separate call
10405                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10406                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10407                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10408                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10409                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10410                        true /*allowInstall*/, instantApp, parentPackageName,
10411                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10412                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10413                // SIDE EFFECTS; updates system state; move elsewhere
10414                if (origPackage != null) {
10415                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10416                }
10417                mSettings.addUserToSettingLPw(pkgSetting);
10418            } else {
10419                // REMOVE SharedUserSetting from method; update in a separate call.
10420                //
10421                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10422                // secondaryCpuAbi are not known at this point so we always update them
10423                // to null here, only to reset them at a later point.
10424                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10425                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10426                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10427                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10428                        UserManagerService.getInstance(), usesStaticLibraries,
10429                        pkg.usesStaticLibrariesVersions);
10430            }
10431            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10432            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10433
10434            // SIDE EFFECTS; modifies system state; move elsewhere
10435            if (pkgSetting.origPackage != null) {
10436                // If we are first transitioning from an original package,
10437                // fix up the new package's name now.  We need to do this after
10438                // looking up the package under its new name, so getPackageLP
10439                // can take care of fiddling things correctly.
10440                pkg.setPackageName(origPackage.name);
10441
10442                // File a report about this.
10443                String msg = "New package " + pkgSetting.realName
10444                        + " renamed to replace old package " + pkgSetting.name;
10445                reportSettingsProblem(Log.WARN, msg);
10446
10447                // Make a note of it.
10448                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10449                    mTransferedPackages.add(origPackage.name);
10450                }
10451
10452                // No longer need to retain this.
10453                pkgSetting.origPackage = null;
10454            }
10455
10456            // SIDE EFFECTS; modifies system state; move elsewhere
10457            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10458                // Make a note of it.
10459                mTransferedPackages.add(pkg.packageName);
10460            }
10461
10462            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10463                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10464            }
10465
10466            if ((scanFlags & SCAN_BOOTING) == 0
10467                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10468                // Check all shared libraries and map to their actual file path.
10469                // We only do this here for apps not on a system dir, because those
10470                // are the only ones that can fail an install due to this.  We
10471                // will take care of the system apps by updating all of their
10472                // library paths after the scan is done. Also during the initial
10473                // scan don't update any libs as we do this wholesale after all
10474                // apps are scanned to avoid dependency based scanning.
10475                updateSharedLibrariesLPr(pkg, null);
10476            }
10477
10478            if (mFoundPolicyFile) {
10479                SELinuxMMAC.assignSeInfoValue(pkg);
10480            }
10481            pkg.applicationInfo.uid = pkgSetting.appId;
10482            pkg.mExtras = pkgSetting;
10483
10484
10485            // Static shared libs have same package with different versions where
10486            // we internally use a synthetic package name to allow multiple versions
10487            // of the same package, therefore we need to compare signatures against
10488            // the package setting for the latest library version.
10489            PackageSetting signatureCheckPs = pkgSetting;
10490            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10491                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10492                if (libraryEntry != null) {
10493                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10494                }
10495            }
10496
10497            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10498                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10499                    // We just determined the app is signed correctly, so bring
10500                    // over the latest parsed certs.
10501                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10502                } else {
10503                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10504                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10505                                "Package " + pkg.packageName + " upgrade keys do not match the "
10506                                + "previously installed version");
10507                    } else {
10508                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10509                        String msg = "System package " + pkg.packageName
10510                                + " signature changed; retaining data.";
10511                        reportSettingsProblem(Log.WARN, msg);
10512                    }
10513                }
10514            } else {
10515                try {
10516                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10517                    verifySignaturesLP(signatureCheckPs, pkg);
10518                    // We just determined the app is signed correctly, so bring
10519                    // over the latest parsed certs.
10520                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10521                } catch (PackageManagerException e) {
10522                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10523                        throw e;
10524                    }
10525                    // The signature has changed, but this package is in the system
10526                    // image...  let's recover!
10527                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10528                    // However...  if this package is part of a shared user, but it
10529                    // doesn't match the signature of the shared user, let's fail.
10530                    // What this means is that you can't change the signatures
10531                    // associated with an overall shared user, which doesn't seem all
10532                    // that unreasonable.
10533                    if (signatureCheckPs.sharedUser != null) {
10534                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10535                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10536                            throw new PackageManagerException(
10537                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10538                                    "Signature mismatch for shared user: "
10539                                            + pkgSetting.sharedUser);
10540                        }
10541                    }
10542                    // File a report about this.
10543                    String msg = "System package " + pkg.packageName
10544                            + " signature changed; retaining data.";
10545                    reportSettingsProblem(Log.WARN, msg);
10546                }
10547            }
10548
10549            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10550                // This package wants to adopt ownership of permissions from
10551                // another package.
10552                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10553                    final String origName = pkg.mAdoptPermissions.get(i);
10554                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10555                    if (orig != null) {
10556                        if (verifyPackageUpdateLPr(orig, pkg)) {
10557                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10558                                    + pkg.packageName);
10559                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10560                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10561                        }
10562                    }
10563                }
10564            }
10565        }
10566
10567        pkg.applicationInfo.processName = fixProcessName(
10568                pkg.applicationInfo.packageName,
10569                pkg.applicationInfo.processName);
10570
10571        if (pkg != mPlatformPackage) {
10572            // Get all of our default paths setup
10573            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10574        }
10575
10576        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10577
10578        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10579            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10580                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10581                final boolean extractNativeLibs = !pkg.isLibrary();
10582                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10583                        mAppLib32InstallDir);
10584                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10585
10586                // Some system apps still use directory structure for native libraries
10587                // in which case we might end up not detecting abi solely based on apk
10588                // structure. Try to detect abi based on directory structure.
10589                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10590                        pkg.applicationInfo.primaryCpuAbi == null) {
10591                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10592                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10593                }
10594            } else {
10595                // This is not a first boot or an upgrade, don't bother deriving the
10596                // ABI during the scan. Instead, trust the value that was stored in the
10597                // package setting.
10598                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10599                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10600
10601                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10602
10603                if (DEBUG_ABI_SELECTION) {
10604                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10605                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10606                        pkg.applicationInfo.secondaryCpuAbi);
10607                }
10608            }
10609        } else {
10610            if ((scanFlags & SCAN_MOVE) != 0) {
10611                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10612                // but we already have this packages package info in the PackageSetting. We just
10613                // use that and derive the native library path based on the new codepath.
10614                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10615                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10616            }
10617
10618            // Set native library paths again. For moves, the path will be updated based on the
10619            // ABIs we've determined above. For non-moves, the path will be updated based on the
10620            // ABIs we determined during compilation, but the path will depend on the final
10621            // package path (after the rename away from the stage path).
10622            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10623        }
10624
10625        // This is a special case for the "system" package, where the ABI is
10626        // dictated by the zygote configuration (and init.rc). We should keep track
10627        // of this ABI so that we can deal with "normal" applications that run under
10628        // the same UID correctly.
10629        if (mPlatformPackage == pkg) {
10630            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10631                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10632        }
10633
10634        // If there's a mismatch between the abi-override in the package setting
10635        // and the abiOverride specified for the install. Warn about this because we
10636        // would've already compiled the app without taking the package setting into
10637        // account.
10638        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10639            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10640                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10641                        " for package " + pkg.packageName);
10642            }
10643        }
10644
10645        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10646        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10647        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10648
10649        // Copy the derived override back to the parsed package, so that we can
10650        // update the package settings accordingly.
10651        pkg.cpuAbiOverride = cpuAbiOverride;
10652
10653        if (DEBUG_ABI_SELECTION) {
10654            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10655                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10656                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10657        }
10658
10659        // Push the derived path down into PackageSettings so we know what to
10660        // clean up at uninstall time.
10661        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10662
10663        if (DEBUG_ABI_SELECTION) {
10664            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10665                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10666                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10667        }
10668
10669        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10670        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10671            // We don't do this here during boot because we can do it all
10672            // at once after scanning all existing packages.
10673            //
10674            // We also do this *before* we perform dexopt on this package, so that
10675            // we can avoid redundant dexopts, and also to make sure we've got the
10676            // code and package path correct.
10677            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10678        }
10679
10680        if (mFactoryTest && pkg.requestedPermissions.contains(
10681                android.Manifest.permission.FACTORY_TEST)) {
10682            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10683        }
10684
10685        if (isSystemApp(pkg)) {
10686            pkgSetting.isOrphaned = true;
10687        }
10688
10689        // Take care of first install / last update times.
10690        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10691        if (currentTime != 0) {
10692            if (pkgSetting.firstInstallTime == 0) {
10693                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10694            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10695                pkgSetting.lastUpdateTime = currentTime;
10696            }
10697        } else if (pkgSetting.firstInstallTime == 0) {
10698            // We need *something*.  Take time time stamp of the file.
10699            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10700        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10701            if (scanFileTime != pkgSetting.timeStamp) {
10702                // A package on the system image has changed; consider this
10703                // to be an update.
10704                pkgSetting.lastUpdateTime = scanFileTime;
10705            }
10706        }
10707        pkgSetting.setTimeStamp(scanFileTime);
10708
10709        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10710            if (nonMutatedPs != null) {
10711                synchronized (mPackages) {
10712                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10713                }
10714            }
10715        } else {
10716            final int userId = user == null ? 0 : user.getIdentifier();
10717            // Modify state for the given package setting
10718            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10719                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10720            if (pkgSetting.getInstantApp(userId)) {
10721                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10722            }
10723        }
10724        return pkg;
10725    }
10726
10727    /**
10728     * Applies policy to the parsed package based upon the given policy flags.
10729     * Ensures the package is in a good state.
10730     * <p>
10731     * Implementation detail: This method must NOT have any side effect. It would
10732     * ideally be static, but, it requires locks to read system state.
10733     */
10734    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10735        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10736            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10737            if (pkg.applicationInfo.isDirectBootAware()) {
10738                // we're direct boot aware; set for all components
10739                for (PackageParser.Service s : pkg.services) {
10740                    s.info.encryptionAware = s.info.directBootAware = true;
10741                }
10742                for (PackageParser.Provider p : pkg.providers) {
10743                    p.info.encryptionAware = p.info.directBootAware = true;
10744                }
10745                for (PackageParser.Activity a : pkg.activities) {
10746                    a.info.encryptionAware = a.info.directBootAware = true;
10747                }
10748                for (PackageParser.Activity r : pkg.receivers) {
10749                    r.info.encryptionAware = r.info.directBootAware = true;
10750                }
10751            }
10752        } else {
10753            // Only allow system apps to be flagged as core apps.
10754            pkg.coreApp = false;
10755            // clear flags not applicable to regular apps
10756            pkg.applicationInfo.privateFlags &=
10757                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10758            pkg.applicationInfo.privateFlags &=
10759                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10760        }
10761        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10762
10763        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10764            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10765        }
10766
10767        if (!isSystemApp(pkg)) {
10768            // Only system apps can use these features.
10769            pkg.mOriginalPackages = null;
10770            pkg.mRealPackage = null;
10771            pkg.mAdoptPermissions = null;
10772        }
10773    }
10774
10775    /**
10776     * Asserts the parsed package is valid according to the given policy. If the
10777     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10778     * <p>
10779     * Implementation detail: This method must NOT have any side effects. It would
10780     * ideally be static, but, it requires locks to read system state.
10781     *
10782     * @throws PackageManagerException If the package fails any of the validation checks
10783     */
10784    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10785            throws PackageManagerException {
10786        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10787            assertCodePolicy(pkg);
10788        }
10789
10790        if (pkg.applicationInfo.getCodePath() == null ||
10791                pkg.applicationInfo.getResourcePath() == null) {
10792            // Bail out. The resource and code paths haven't been set.
10793            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10794                    "Code and resource paths haven't been set correctly");
10795        }
10796
10797        // Make sure we're not adding any bogus keyset info
10798        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10799        ksms.assertScannedPackageValid(pkg);
10800
10801        synchronized (mPackages) {
10802            // The special "android" package can only be defined once
10803            if (pkg.packageName.equals("android")) {
10804                if (mAndroidApplication != null) {
10805                    Slog.w(TAG, "*************************************************");
10806                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10807                    Slog.w(TAG, " codePath=" + pkg.codePath);
10808                    Slog.w(TAG, "*************************************************");
10809                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10810                            "Core android package being redefined.  Skipping.");
10811                }
10812            }
10813
10814            // A package name must be unique; don't allow duplicates
10815            if (mPackages.containsKey(pkg.packageName)) {
10816                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10817                        "Application package " + pkg.packageName
10818                        + " already installed.  Skipping duplicate.");
10819            }
10820
10821            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10822                // Static libs have a synthetic package name containing the version
10823                // but we still want the base name to be unique.
10824                if (mPackages.containsKey(pkg.manifestPackageName)) {
10825                    throw new PackageManagerException(
10826                            "Duplicate static shared lib provider package");
10827                }
10828
10829                // Static shared libraries should have at least O target SDK
10830                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10831                    throw new PackageManagerException(
10832                            "Packages declaring static-shared libs must target O SDK or higher");
10833                }
10834
10835                // Package declaring static a shared lib cannot be instant apps
10836                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10837                    throw new PackageManagerException(
10838                            "Packages declaring static-shared libs cannot be instant apps");
10839                }
10840
10841                // Package declaring static a shared lib cannot be renamed since the package
10842                // name is synthetic and apps can't code around package manager internals.
10843                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10844                    throw new PackageManagerException(
10845                            "Packages declaring static-shared libs cannot be renamed");
10846                }
10847
10848                // Package declaring static a shared lib cannot declare child packages
10849                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10850                    throw new PackageManagerException(
10851                            "Packages declaring static-shared libs cannot have child packages");
10852                }
10853
10854                // Package declaring static a shared lib cannot declare dynamic libs
10855                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10856                    throw new PackageManagerException(
10857                            "Packages declaring static-shared libs cannot declare dynamic libs");
10858                }
10859
10860                // Package declaring static a shared lib cannot declare shared users
10861                if (pkg.mSharedUserId != null) {
10862                    throw new PackageManagerException(
10863                            "Packages declaring static-shared libs cannot declare shared users");
10864                }
10865
10866                // Static shared libs cannot declare activities
10867                if (!pkg.activities.isEmpty()) {
10868                    throw new PackageManagerException(
10869                            "Static shared libs cannot declare activities");
10870                }
10871
10872                // Static shared libs cannot declare services
10873                if (!pkg.services.isEmpty()) {
10874                    throw new PackageManagerException(
10875                            "Static shared libs cannot declare services");
10876                }
10877
10878                // Static shared libs cannot declare providers
10879                if (!pkg.providers.isEmpty()) {
10880                    throw new PackageManagerException(
10881                            "Static shared libs cannot declare content providers");
10882                }
10883
10884                // Static shared libs cannot declare receivers
10885                if (!pkg.receivers.isEmpty()) {
10886                    throw new PackageManagerException(
10887                            "Static shared libs cannot declare broadcast receivers");
10888                }
10889
10890                // Static shared libs cannot declare permission groups
10891                if (!pkg.permissionGroups.isEmpty()) {
10892                    throw new PackageManagerException(
10893                            "Static shared libs cannot declare permission groups");
10894                }
10895
10896                // Static shared libs cannot declare permissions
10897                if (!pkg.permissions.isEmpty()) {
10898                    throw new PackageManagerException(
10899                            "Static shared libs cannot declare permissions");
10900                }
10901
10902                // Static shared libs cannot declare protected broadcasts
10903                if (pkg.protectedBroadcasts != null) {
10904                    throw new PackageManagerException(
10905                            "Static shared libs cannot declare protected broadcasts");
10906                }
10907
10908                // Static shared libs cannot be overlay targets
10909                if (pkg.mOverlayTarget != null) {
10910                    throw new PackageManagerException(
10911                            "Static shared libs cannot be overlay targets");
10912                }
10913
10914                // The version codes must be ordered as lib versions
10915                int minVersionCode = Integer.MIN_VALUE;
10916                int maxVersionCode = Integer.MAX_VALUE;
10917
10918                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10919                        pkg.staticSharedLibName);
10920                if (versionedLib != null) {
10921                    final int versionCount = versionedLib.size();
10922                    for (int i = 0; i < versionCount; i++) {
10923                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10924                        final int libVersionCode = libInfo.getDeclaringPackage()
10925                                .getVersionCode();
10926                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10927                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10928                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10929                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10930                        } else {
10931                            minVersionCode = maxVersionCode = libVersionCode;
10932                            break;
10933                        }
10934                    }
10935                }
10936                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10937                    throw new PackageManagerException("Static shared"
10938                            + " lib version codes must be ordered as lib versions");
10939                }
10940            }
10941
10942            // Only privileged apps and updated privileged apps can add child packages.
10943            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10944                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10945                    throw new PackageManagerException("Only privileged apps can add child "
10946                            + "packages. Ignoring package " + pkg.packageName);
10947                }
10948                final int childCount = pkg.childPackages.size();
10949                for (int i = 0; i < childCount; i++) {
10950                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10951                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10952                            childPkg.packageName)) {
10953                        throw new PackageManagerException("Can't override child of "
10954                                + "another disabled app. Ignoring package " + pkg.packageName);
10955                    }
10956                }
10957            }
10958
10959            // If we're only installing presumed-existing packages, require that the
10960            // scanned APK is both already known and at the path previously established
10961            // for it.  Previously unknown packages we pick up normally, but if we have an
10962            // a priori expectation about this package's install presence, enforce it.
10963            // With a singular exception for new system packages. When an OTA contains
10964            // a new system package, we allow the codepath to change from a system location
10965            // to the user-installed location. If we don't allow this change, any newer,
10966            // user-installed version of the application will be ignored.
10967            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10968                if (mExpectingBetter.containsKey(pkg.packageName)) {
10969                    logCriticalInfo(Log.WARN,
10970                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10971                } else {
10972                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10973                    if (known != null) {
10974                        if (DEBUG_PACKAGE_SCANNING) {
10975                            Log.d(TAG, "Examining " + pkg.codePath
10976                                    + " and requiring known paths " + known.codePathString
10977                                    + " & " + known.resourcePathString);
10978                        }
10979                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10980                                || !pkg.applicationInfo.getResourcePath().equals(
10981                                        known.resourcePathString)) {
10982                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10983                                    "Application package " + pkg.packageName
10984                                    + " found at " + pkg.applicationInfo.getCodePath()
10985                                    + " but expected at " + known.codePathString
10986                                    + "; ignoring.");
10987                        }
10988                    }
10989                }
10990            }
10991
10992            // Verify that this new package doesn't have any content providers
10993            // that conflict with existing packages.  Only do this if the
10994            // package isn't already installed, since we don't want to break
10995            // things that are installed.
10996            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10997                final int N = pkg.providers.size();
10998                int i;
10999                for (i=0; i<N; i++) {
11000                    PackageParser.Provider p = pkg.providers.get(i);
11001                    if (p.info.authority != null) {
11002                        String names[] = p.info.authority.split(";");
11003                        for (int j = 0; j < names.length; j++) {
11004                            if (mProvidersByAuthority.containsKey(names[j])) {
11005                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11006                                final String otherPackageName =
11007                                        ((other != null && other.getComponentName() != null) ?
11008                                                other.getComponentName().getPackageName() : "?");
11009                                throw new PackageManagerException(
11010                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11011                                        "Can't install because provider name " + names[j]
11012                                                + " (in package " + pkg.applicationInfo.packageName
11013                                                + ") is already used by " + otherPackageName);
11014                            }
11015                        }
11016                    }
11017                }
11018            }
11019        }
11020    }
11021
11022    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11023            int type, String declaringPackageName, int declaringVersionCode) {
11024        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11025        if (versionedLib == null) {
11026            versionedLib = new SparseArray<>();
11027            mSharedLibraries.put(name, versionedLib);
11028            if (type == SharedLibraryInfo.TYPE_STATIC) {
11029                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11030            }
11031        } else if (versionedLib.indexOfKey(version) >= 0) {
11032            return false;
11033        }
11034        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11035                version, type, declaringPackageName, declaringVersionCode);
11036        versionedLib.put(version, libEntry);
11037        return true;
11038    }
11039
11040    private boolean removeSharedLibraryLPw(String name, int version) {
11041        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11042        if (versionedLib == null) {
11043            return false;
11044        }
11045        final int libIdx = versionedLib.indexOfKey(version);
11046        if (libIdx < 0) {
11047            return false;
11048        }
11049        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11050        versionedLib.remove(version);
11051        if (versionedLib.size() <= 0) {
11052            mSharedLibraries.remove(name);
11053            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11054                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11055                        .getPackageName());
11056            }
11057        }
11058        return true;
11059    }
11060
11061    /**
11062     * Adds a scanned package to the system. When this method is finished, the package will
11063     * be available for query, resolution, etc...
11064     */
11065    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11066            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11067        final String pkgName = pkg.packageName;
11068        if (mCustomResolverComponentName != null &&
11069                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11070            setUpCustomResolverActivity(pkg);
11071        }
11072
11073        if (pkg.packageName.equals("android")) {
11074            synchronized (mPackages) {
11075                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11076                    // Set up information for our fall-back user intent resolution activity.
11077                    mPlatformPackage = pkg;
11078                    pkg.mVersionCode = mSdkVersion;
11079                    mAndroidApplication = pkg.applicationInfo;
11080                    if (!mResolverReplaced) {
11081                        mResolveActivity.applicationInfo = mAndroidApplication;
11082                        mResolveActivity.name = ResolverActivity.class.getName();
11083                        mResolveActivity.packageName = mAndroidApplication.packageName;
11084                        mResolveActivity.processName = "system:ui";
11085                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11086                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11087                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11088                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11089                        mResolveActivity.exported = true;
11090                        mResolveActivity.enabled = true;
11091                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11092                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11093                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11094                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11095                                | ActivityInfo.CONFIG_ORIENTATION
11096                                | ActivityInfo.CONFIG_KEYBOARD
11097                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11098                        mResolveInfo.activityInfo = mResolveActivity;
11099                        mResolveInfo.priority = 0;
11100                        mResolveInfo.preferredOrder = 0;
11101                        mResolveInfo.match = 0;
11102                        mResolveComponentName = new ComponentName(
11103                                mAndroidApplication.packageName, mResolveActivity.name);
11104                    }
11105                }
11106            }
11107        }
11108
11109        ArrayList<PackageParser.Package> clientLibPkgs = null;
11110        // writer
11111        synchronized (mPackages) {
11112            boolean hasStaticSharedLibs = false;
11113
11114            // Any app can add new static shared libraries
11115            if (pkg.staticSharedLibName != null) {
11116                // Static shared libs don't allow renaming as they have synthetic package
11117                // names to allow install of multiple versions, so use name from manifest.
11118                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11119                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11120                        pkg.manifestPackageName, pkg.mVersionCode)) {
11121                    hasStaticSharedLibs = true;
11122                } else {
11123                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11124                                + pkg.staticSharedLibName + " already exists; skipping");
11125                }
11126                // Static shared libs cannot be updated once installed since they
11127                // use synthetic package name which includes the version code, so
11128                // not need to update other packages's shared lib dependencies.
11129            }
11130
11131            if (!hasStaticSharedLibs
11132                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11133                // Only system apps can add new dynamic shared libraries.
11134                if (pkg.libraryNames != null) {
11135                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11136                        String name = pkg.libraryNames.get(i);
11137                        boolean allowed = false;
11138                        if (pkg.isUpdatedSystemApp()) {
11139                            // New library entries can only be added through the
11140                            // system image.  This is important to get rid of a lot
11141                            // of nasty edge cases: for example if we allowed a non-
11142                            // system update of the app to add a library, then uninstalling
11143                            // the update would make the library go away, and assumptions
11144                            // we made such as through app install filtering would now
11145                            // have allowed apps on the device which aren't compatible
11146                            // with it.  Better to just have the restriction here, be
11147                            // conservative, and create many fewer cases that can negatively
11148                            // impact the user experience.
11149                            final PackageSetting sysPs = mSettings
11150                                    .getDisabledSystemPkgLPr(pkg.packageName);
11151                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11152                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11153                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11154                                        allowed = true;
11155                                        break;
11156                                    }
11157                                }
11158                            }
11159                        } else {
11160                            allowed = true;
11161                        }
11162                        if (allowed) {
11163                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11164                                    SharedLibraryInfo.VERSION_UNDEFINED,
11165                                    SharedLibraryInfo.TYPE_DYNAMIC,
11166                                    pkg.packageName, pkg.mVersionCode)) {
11167                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11168                                        + name + " already exists; skipping");
11169                            }
11170                        } else {
11171                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11172                                    + name + " that is not declared on system image; skipping");
11173                        }
11174                    }
11175
11176                    if ((scanFlags & SCAN_BOOTING) == 0) {
11177                        // If we are not booting, we need to update any applications
11178                        // that are clients of our shared library.  If we are booting,
11179                        // this will all be done once the scan is complete.
11180                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11181                    }
11182                }
11183            }
11184        }
11185
11186        if ((scanFlags & SCAN_BOOTING) != 0) {
11187            // No apps can run during boot scan, so they don't need to be frozen
11188        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11189            // Caller asked to not kill app, so it's probably not frozen
11190        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11191            // Caller asked us to ignore frozen check for some reason; they
11192            // probably didn't know the package name
11193        } else {
11194            // We're doing major surgery on this package, so it better be frozen
11195            // right now to keep it from launching
11196            checkPackageFrozen(pkgName);
11197        }
11198
11199        // Also need to kill any apps that are dependent on the library.
11200        if (clientLibPkgs != null) {
11201            for (int i=0; i<clientLibPkgs.size(); i++) {
11202                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11203                killApplication(clientPkg.applicationInfo.packageName,
11204                        clientPkg.applicationInfo.uid, "update lib");
11205            }
11206        }
11207
11208        // writer
11209        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11210
11211        synchronized (mPackages) {
11212            // We don't expect installation to fail beyond this point
11213
11214            // Add the new setting to mSettings
11215            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11216            // Add the new setting to mPackages
11217            mPackages.put(pkg.applicationInfo.packageName, pkg);
11218            // Make sure we don't accidentally delete its data.
11219            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11220            while (iter.hasNext()) {
11221                PackageCleanItem item = iter.next();
11222                if (pkgName.equals(item.packageName)) {
11223                    iter.remove();
11224                }
11225            }
11226
11227            // Add the package's KeySets to the global KeySetManagerService
11228            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11229            ksms.addScannedPackageLPw(pkg);
11230
11231            int N = pkg.providers.size();
11232            StringBuilder r = null;
11233            int i;
11234            for (i=0; i<N; i++) {
11235                PackageParser.Provider p = pkg.providers.get(i);
11236                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11237                        p.info.processName);
11238                mProviders.addProvider(p);
11239                p.syncable = p.info.isSyncable;
11240                if (p.info.authority != null) {
11241                    String names[] = p.info.authority.split(";");
11242                    p.info.authority = null;
11243                    for (int j = 0; j < names.length; j++) {
11244                        if (j == 1 && p.syncable) {
11245                            // We only want the first authority for a provider to possibly be
11246                            // syncable, so if we already added this provider using a different
11247                            // authority clear the syncable flag. We copy the provider before
11248                            // changing it because the mProviders object contains a reference
11249                            // to a provider that we don't want to change.
11250                            // Only do this for the second authority since the resulting provider
11251                            // object can be the same for all future authorities for this provider.
11252                            p = new PackageParser.Provider(p);
11253                            p.syncable = false;
11254                        }
11255                        if (!mProvidersByAuthority.containsKey(names[j])) {
11256                            mProvidersByAuthority.put(names[j], p);
11257                            if (p.info.authority == null) {
11258                                p.info.authority = names[j];
11259                            } else {
11260                                p.info.authority = p.info.authority + ";" + names[j];
11261                            }
11262                            if (DEBUG_PACKAGE_SCANNING) {
11263                                if (chatty)
11264                                    Log.d(TAG, "Registered content provider: " + names[j]
11265                                            + ", className = " + p.info.name + ", isSyncable = "
11266                                            + p.info.isSyncable);
11267                            }
11268                        } else {
11269                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11270                            Slog.w(TAG, "Skipping provider name " + names[j] +
11271                                    " (in package " + pkg.applicationInfo.packageName +
11272                                    "): name already used by "
11273                                    + ((other != null && other.getComponentName() != null)
11274                                            ? other.getComponentName().getPackageName() : "?"));
11275                        }
11276                    }
11277                }
11278                if (chatty) {
11279                    if (r == null) {
11280                        r = new StringBuilder(256);
11281                    } else {
11282                        r.append(' ');
11283                    }
11284                    r.append(p.info.name);
11285                }
11286            }
11287            if (r != null) {
11288                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11289            }
11290
11291            N = pkg.services.size();
11292            r = null;
11293            for (i=0; i<N; i++) {
11294                PackageParser.Service s = pkg.services.get(i);
11295                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11296                        s.info.processName);
11297                mServices.addService(s);
11298                if (chatty) {
11299                    if (r == null) {
11300                        r = new StringBuilder(256);
11301                    } else {
11302                        r.append(' ');
11303                    }
11304                    r.append(s.info.name);
11305                }
11306            }
11307            if (r != null) {
11308                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11309            }
11310
11311            N = pkg.receivers.size();
11312            r = null;
11313            for (i=0; i<N; i++) {
11314                PackageParser.Activity a = pkg.receivers.get(i);
11315                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11316                        a.info.processName);
11317                mReceivers.addActivity(a, "receiver");
11318                if (chatty) {
11319                    if (r == null) {
11320                        r = new StringBuilder(256);
11321                    } else {
11322                        r.append(' ');
11323                    }
11324                    r.append(a.info.name);
11325                }
11326            }
11327            if (r != null) {
11328                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11329            }
11330
11331            N = pkg.activities.size();
11332            r = null;
11333            for (i=0; i<N; i++) {
11334                PackageParser.Activity a = pkg.activities.get(i);
11335                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11336                        a.info.processName);
11337                mActivities.addActivity(a, "activity");
11338                if (chatty) {
11339                    if (r == null) {
11340                        r = new StringBuilder(256);
11341                    } else {
11342                        r.append(' ');
11343                    }
11344                    r.append(a.info.name);
11345                }
11346            }
11347            if (r != null) {
11348                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11349            }
11350
11351            N = pkg.permissionGroups.size();
11352            r = null;
11353            for (i=0; i<N; i++) {
11354                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11355                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11356                final String curPackageName = cur == null ? null : cur.info.packageName;
11357                // Dont allow ephemeral apps to define new permission groups.
11358                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11359                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11360                            + pg.info.packageName
11361                            + " ignored: instant apps cannot define new permission groups.");
11362                    continue;
11363                }
11364                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11365                if (cur == null || isPackageUpdate) {
11366                    mPermissionGroups.put(pg.info.name, pg);
11367                    if (chatty) {
11368                        if (r == null) {
11369                            r = new StringBuilder(256);
11370                        } else {
11371                            r.append(' ');
11372                        }
11373                        if (isPackageUpdate) {
11374                            r.append("UPD:");
11375                        }
11376                        r.append(pg.info.name);
11377                    }
11378                } else {
11379                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11380                            + pg.info.packageName + " ignored: original from "
11381                            + cur.info.packageName);
11382                    if (chatty) {
11383                        if (r == null) {
11384                            r = new StringBuilder(256);
11385                        } else {
11386                            r.append(' ');
11387                        }
11388                        r.append("DUP:");
11389                        r.append(pg.info.name);
11390                    }
11391                }
11392            }
11393            if (r != null) {
11394                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11395            }
11396
11397            N = pkg.permissions.size();
11398            r = null;
11399            for (i=0; i<N; i++) {
11400                PackageParser.Permission p = pkg.permissions.get(i);
11401
11402                // Dont allow ephemeral apps to define new permissions.
11403                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11404                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11405                            + p.info.packageName
11406                            + " ignored: instant apps cannot define new permissions.");
11407                    continue;
11408                }
11409
11410                // Assume by default that we did not install this permission into the system.
11411                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11412
11413                // Now that permission groups have a special meaning, we ignore permission
11414                // groups for legacy apps to prevent unexpected behavior. In particular,
11415                // permissions for one app being granted to someone just because they happen
11416                // to be in a group defined by another app (before this had no implications).
11417                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11418                    p.group = mPermissionGroups.get(p.info.group);
11419                    // Warn for a permission in an unknown group.
11420                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11421                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11422                                + p.info.packageName + " in an unknown group " + p.info.group);
11423                    }
11424                }
11425
11426                ArrayMap<String, BasePermission> permissionMap =
11427                        p.tree ? mSettings.mPermissionTrees
11428                                : mSettings.mPermissions;
11429                BasePermission bp = permissionMap.get(p.info.name);
11430
11431                // Allow system apps to redefine non-system permissions
11432                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11433                    final boolean currentOwnerIsSystem = (bp.perm != null
11434                            && isSystemApp(bp.perm.owner));
11435                    if (isSystemApp(p.owner)) {
11436                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11437                            // It's a built-in permission and no owner, take ownership now
11438                            bp.packageSetting = pkgSetting;
11439                            bp.perm = p;
11440                            bp.uid = pkg.applicationInfo.uid;
11441                            bp.sourcePackage = p.info.packageName;
11442                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11443                        } else if (!currentOwnerIsSystem) {
11444                            String msg = "New decl " + p.owner + " of permission  "
11445                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11446                            reportSettingsProblem(Log.WARN, msg);
11447                            bp = null;
11448                        }
11449                    }
11450                }
11451
11452                if (bp == null) {
11453                    bp = new BasePermission(p.info.name, p.info.packageName,
11454                            BasePermission.TYPE_NORMAL);
11455                    permissionMap.put(p.info.name, bp);
11456                }
11457
11458                if (bp.perm == null) {
11459                    if (bp.sourcePackage == null
11460                            || bp.sourcePackage.equals(p.info.packageName)) {
11461                        BasePermission tree = findPermissionTreeLP(p.info.name);
11462                        if (tree == null
11463                                || tree.sourcePackage.equals(p.info.packageName)) {
11464                            bp.packageSetting = pkgSetting;
11465                            bp.perm = p;
11466                            bp.uid = pkg.applicationInfo.uid;
11467                            bp.sourcePackage = p.info.packageName;
11468                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11469                            if (chatty) {
11470                                if (r == null) {
11471                                    r = new StringBuilder(256);
11472                                } else {
11473                                    r.append(' ');
11474                                }
11475                                r.append(p.info.name);
11476                            }
11477                        } else {
11478                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11479                                    + p.info.packageName + " ignored: base tree "
11480                                    + tree.name + " is from package "
11481                                    + tree.sourcePackage);
11482                        }
11483                    } else {
11484                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11485                                + p.info.packageName + " ignored: original from "
11486                                + bp.sourcePackage);
11487                    }
11488                } else if (chatty) {
11489                    if (r == null) {
11490                        r = new StringBuilder(256);
11491                    } else {
11492                        r.append(' ');
11493                    }
11494                    r.append("DUP:");
11495                    r.append(p.info.name);
11496                }
11497                if (bp.perm == p) {
11498                    bp.protectionLevel = p.info.protectionLevel;
11499                }
11500            }
11501
11502            if (r != null) {
11503                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11504            }
11505
11506            N = pkg.instrumentation.size();
11507            r = null;
11508            for (i=0; i<N; i++) {
11509                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11510                a.info.packageName = pkg.applicationInfo.packageName;
11511                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11512                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11513                a.info.splitNames = pkg.splitNames;
11514                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11515                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11516                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11517                a.info.dataDir = pkg.applicationInfo.dataDir;
11518                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11519                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11520                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11521                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11522                mInstrumentation.put(a.getComponentName(), a);
11523                if (chatty) {
11524                    if (r == null) {
11525                        r = new StringBuilder(256);
11526                    } else {
11527                        r.append(' ');
11528                    }
11529                    r.append(a.info.name);
11530                }
11531            }
11532            if (r != null) {
11533                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11534            }
11535
11536            if (pkg.protectedBroadcasts != null) {
11537                N = pkg.protectedBroadcasts.size();
11538                for (i=0; i<N; i++) {
11539                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11540                }
11541            }
11542        }
11543
11544        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11545    }
11546
11547    /**
11548     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11549     * is derived purely on the basis of the contents of {@code scanFile} and
11550     * {@code cpuAbiOverride}.
11551     *
11552     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11553     */
11554    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11555                                 String cpuAbiOverride, boolean extractLibs,
11556                                 File appLib32InstallDir)
11557            throws PackageManagerException {
11558        // Give ourselves some initial paths; we'll come back for another
11559        // pass once we've determined ABI below.
11560        setNativeLibraryPaths(pkg, appLib32InstallDir);
11561
11562        // We would never need to extract libs for forward-locked and external packages,
11563        // since the container service will do it for us. We shouldn't attempt to
11564        // extract libs from system app when it was not updated.
11565        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11566                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11567            extractLibs = false;
11568        }
11569
11570        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11571        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11572
11573        NativeLibraryHelper.Handle handle = null;
11574        try {
11575            handle = NativeLibraryHelper.Handle.create(pkg);
11576            // TODO(multiArch): This can be null for apps that didn't go through the
11577            // usual installation process. We can calculate it again, like we
11578            // do during install time.
11579            //
11580            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11581            // unnecessary.
11582            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11583
11584            // Null out the abis so that they can be recalculated.
11585            pkg.applicationInfo.primaryCpuAbi = null;
11586            pkg.applicationInfo.secondaryCpuAbi = null;
11587            if (isMultiArch(pkg.applicationInfo)) {
11588                // Warn if we've set an abiOverride for multi-lib packages..
11589                // By definition, we need to copy both 32 and 64 bit libraries for
11590                // such packages.
11591                if (pkg.cpuAbiOverride != null
11592                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11593                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11594                }
11595
11596                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11597                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11598                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11599                    if (extractLibs) {
11600                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11601                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11602                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11603                                useIsaSpecificSubdirs);
11604                    } else {
11605                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11606                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11607                    }
11608                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11609                }
11610
11611                // Shared library native code should be in the APK zip aligned
11612                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11613                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11614                            "Shared library native lib extraction not supported");
11615                }
11616
11617                maybeThrowExceptionForMultiArchCopy(
11618                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11619
11620                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11621                    if (extractLibs) {
11622                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11623                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11624                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11625                                useIsaSpecificSubdirs);
11626                    } else {
11627                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11628                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11629                    }
11630                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11631                }
11632
11633                maybeThrowExceptionForMultiArchCopy(
11634                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11635
11636                if (abi64 >= 0) {
11637                    // Shared library native libs should be in the APK zip aligned
11638                    if (extractLibs && pkg.isLibrary()) {
11639                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11640                                "Shared library native lib extraction not supported");
11641                    }
11642                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11643                }
11644
11645                if (abi32 >= 0) {
11646                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11647                    if (abi64 >= 0) {
11648                        if (pkg.use32bitAbi) {
11649                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11650                            pkg.applicationInfo.primaryCpuAbi = abi;
11651                        } else {
11652                            pkg.applicationInfo.secondaryCpuAbi = abi;
11653                        }
11654                    } else {
11655                        pkg.applicationInfo.primaryCpuAbi = abi;
11656                    }
11657                }
11658            } else {
11659                String[] abiList = (cpuAbiOverride != null) ?
11660                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11661
11662                // Enable gross and lame hacks for apps that are built with old
11663                // SDK tools. We must scan their APKs for renderscript bitcode and
11664                // not launch them if it's present. Don't bother checking on devices
11665                // that don't have 64 bit support.
11666                boolean needsRenderScriptOverride = false;
11667                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11668                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11669                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11670                    needsRenderScriptOverride = true;
11671                }
11672
11673                final int copyRet;
11674                if (extractLibs) {
11675                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11676                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11677                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11678                } else {
11679                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11680                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11681                }
11682                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11683
11684                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11685                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11686                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11687                }
11688
11689                if (copyRet >= 0) {
11690                    // Shared libraries that have native libs must be multi-architecture
11691                    if (pkg.isLibrary()) {
11692                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11693                                "Shared library with native libs must be multiarch");
11694                    }
11695                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11696                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11697                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11698                } else if (needsRenderScriptOverride) {
11699                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11700                }
11701            }
11702        } catch (IOException ioe) {
11703            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11704        } finally {
11705            IoUtils.closeQuietly(handle);
11706        }
11707
11708        // Now that we've calculated the ABIs and determined if it's an internal app,
11709        // we will go ahead and populate the nativeLibraryPath.
11710        setNativeLibraryPaths(pkg, appLib32InstallDir);
11711    }
11712
11713    /**
11714     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11715     * i.e, so that all packages can be run inside a single process if required.
11716     *
11717     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11718     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11719     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11720     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11721     * updating a package that belongs to a shared user.
11722     *
11723     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11724     * adds unnecessary complexity.
11725     */
11726    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11727            PackageParser.Package scannedPackage) {
11728        String requiredInstructionSet = null;
11729        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11730            requiredInstructionSet = VMRuntime.getInstructionSet(
11731                     scannedPackage.applicationInfo.primaryCpuAbi);
11732        }
11733
11734        PackageSetting requirer = null;
11735        for (PackageSetting ps : packagesForUser) {
11736            // If packagesForUser contains scannedPackage, we skip it. This will happen
11737            // when scannedPackage is an update of an existing package. Without this check,
11738            // we will never be able to change the ABI of any package belonging to a shared
11739            // user, even if it's compatible with other packages.
11740            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11741                if (ps.primaryCpuAbiString == null) {
11742                    continue;
11743                }
11744
11745                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11746                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11747                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11748                    // this but there's not much we can do.
11749                    String errorMessage = "Instruction set mismatch, "
11750                            + ((requirer == null) ? "[caller]" : requirer)
11751                            + " requires " + requiredInstructionSet + " whereas " + ps
11752                            + " requires " + instructionSet;
11753                    Slog.w(TAG, errorMessage);
11754                }
11755
11756                if (requiredInstructionSet == null) {
11757                    requiredInstructionSet = instructionSet;
11758                    requirer = ps;
11759                }
11760            }
11761        }
11762
11763        if (requiredInstructionSet != null) {
11764            String adjustedAbi;
11765            if (requirer != null) {
11766                // requirer != null implies that either scannedPackage was null or that scannedPackage
11767                // did not require an ABI, in which case we have to adjust scannedPackage to match
11768                // the ABI of the set (which is the same as requirer's ABI)
11769                adjustedAbi = requirer.primaryCpuAbiString;
11770                if (scannedPackage != null) {
11771                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11772                }
11773            } else {
11774                // requirer == null implies that we're updating all ABIs in the set to
11775                // match scannedPackage.
11776                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11777            }
11778
11779            for (PackageSetting ps : packagesForUser) {
11780                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11781                    if (ps.primaryCpuAbiString != null) {
11782                        continue;
11783                    }
11784
11785                    ps.primaryCpuAbiString = adjustedAbi;
11786                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11787                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11788                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11789                        if (DEBUG_ABI_SELECTION) {
11790                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11791                                    + " (requirer="
11792                                    + (requirer != null ? requirer.pkg : "null")
11793                                    + ", scannedPackage="
11794                                    + (scannedPackage != null ? scannedPackage : "null")
11795                                    + ")");
11796                        }
11797                        try {
11798                            mInstaller.rmdex(ps.codePathString,
11799                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11800                        } catch (InstallerException ignored) {
11801                        }
11802                    }
11803                }
11804            }
11805        }
11806    }
11807
11808    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11809        synchronized (mPackages) {
11810            mResolverReplaced = true;
11811            // Set up information for custom user intent resolution activity.
11812            mResolveActivity.applicationInfo = pkg.applicationInfo;
11813            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11814            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11815            mResolveActivity.processName = pkg.applicationInfo.packageName;
11816            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11817            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11818                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11819            mResolveActivity.theme = 0;
11820            mResolveActivity.exported = true;
11821            mResolveActivity.enabled = true;
11822            mResolveInfo.activityInfo = mResolveActivity;
11823            mResolveInfo.priority = 0;
11824            mResolveInfo.preferredOrder = 0;
11825            mResolveInfo.match = 0;
11826            mResolveComponentName = mCustomResolverComponentName;
11827            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11828                    mResolveComponentName);
11829        }
11830    }
11831
11832    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11833        if (installerActivity == null) {
11834            if (DEBUG_EPHEMERAL) {
11835                Slog.d(TAG, "Clear ephemeral installer activity");
11836            }
11837            mInstantAppInstallerActivity = null;
11838            return;
11839        }
11840
11841        if (DEBUG_EPHEMERAL) {
11842            Slog.d(TAG, "Set ephemeral installer activity: "
11843                    + installerActivity.getComponentName());
11844        }
11845        // Set up information for ephemeral installer activity
11846        mInstantAppInstallerActivity = installerActivity;
11847        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11848                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11849        mInstantAppInstallerActivity.exported = true;
11850        mInstantAppInstallerActivity.enabled = true;
11851        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11852        mInstantAppInstallerInfo.priority = 0;
11853        mInstantAppInstallerInfo.preferredOrder = 1;
11854        mInstantAppInstallerInfo.isDefault = true;
11855        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11856                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11857    }
11858
11859    private static String calculateBundledApkRoot(final String codePathString) {
11860        final File codePath = new File(codePathString);
11861        final File codeRoot;
11862        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11863            codeRoot = Environment.getRootDirectory();
11864        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11865            codeRoot = Environment.getOemDirectory();
11866        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11867            codeRoot = Environment.getVendorDirectory();
11868        } else {
11869            // Unrecognized code path; take its top real segment as the apk root:
11870            // e.g. /something/app/blah.apk => /something
11871            try {
11872                File f = codePath.getCanonicalFile();
11873                File parent = f.getParentFile();    // non-null because codePath is a file
11874                File tmp;
11875                while ((tmp = parent.getParentFile()) != null) {
11876                    f = parent;
11877                    parent = tmp;
11878                }
11879                codeRoot = f;
11880                Slog.w(TAG, "Unrecognized code path "
11881                        + codePath + " - using " + codeRoot);
11882            } catch (IOException e) {
11883                // Can't canonicalize the code path -- shenanigans?
11884                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11885                return Environment.getRootDirectory().getPath();
11886            }
11887        }
11888        return codeRoot.getPath();
11889    }
11890
11891    /**
11892     * Derive and set the location of native libraries for the given package,
11893     * which varies depending on where and how the package was installed.
11894     */
11895    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11896        final ApplicationInfo info = pkg.applicationInfo;
11897        final String codePath = pkg.codePath;
11898        final File codeFile = new File(codePath);
11899        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11900        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11901
11902        info.nativeLibraryRootDir = null;
11903        info.nativeLibraryRootRequiresIsa = false;
11904        info.nativeLibraryDir = null;
11905        info.secondaryNativeLibraryDir = null;
11906
11907        if (isApkFile(codeFile)) {
11908            // Monolithic install
11909            if (bundledApp) {
11910                // If "/system/lib64/apkname" exists, assume that is the per-package
11911                // native library directory to use; otherwise use "/system/lib/apkname".
11912                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11913                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11914                        getPrimaryInstructionSet(info));
11915
11916                // This is a bundled system app so choose the path based on the ABI.
11917                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11918                // is just the default path.
11919                final String apkName = deriveCodePathName(codePath);
11920                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11921                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11922                        apkName).getAbsolutePath();
11923
11924                if (info.secondaryCpuAbi != null) {
11925                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11926                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11927                            secondaryLibDir, apkName).getAbsolutePath();
11928                }
11929            } else if (asecApp) {
11930                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11931                        .getAbsolutePath();
11932            } else {
11933                final String apkName = deriveCodePathName(codePath);
11934                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11935                        .getAbsolutePath();
11936            }
11937
11938            info.nativeLibraryRootRequiresIsa = false;
11939            info.nativeLibraryDir = info.nativeLibraryRootDir;
11940        } else {
11941            // Cluster install
11942            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11943            info.nativeLibraryRootRequiresIsa = true;
11944
11945            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11946                    getPrimaryInstructionSet(info)).getAbsolutePath();
11947
11948            if (info.secondaryCpuAbi != null) {
11949                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11950                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11951            }
11952        }
11953    }
11954
11955    /**
11956     * Calculate the abis and roots for a bundled app. These can uniquely
11957     * be determined from the contents of the system partition, i.e whether
11958     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11959     * of this information, and instead assume that the system was built
11960     * sensibly.
11961     */
11962    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11963                                           PackageSetting pkgSetting) {
11964        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11965
11966        // If "/system/lib64/apkname" exists, assume that is the per-package
11967        // native library directory to use; otherwise use "/system/lib/apkname".
11968        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11969        setBundledAppAbi(pkg, apkRoot, apkName);
11970        // pkgSetting might be null during rescan following uninstall of updates
11971        // to a bundled app, so accommodate that possibility.  The settings in
11972        // that case will be established later from the parsed package.
11973        //
11974        // If the settings aren't null, sync them up with what we've just derived.
11975        // note that apkRoot isn't stored in the package settings.
11976        if (pkgSetting != null) {
11977            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11978            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11979        }
11980    }
11981
11982    /**
11983     * Deduces the ABI of a bundled app and sets the relevant fields on the
11984     * parsed pkg object.
11985     *
11986     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11987     *        under which system libraries are installed.
11988     * @param apkName the name of the installed package.
11989     */
11990    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11991        final File codeFile = new File(pkg.codePath);
11992
11993        final boolean has64BitLibs;
11994        final boolean has32BitLibs;
11995        if (isApkFile(codeFile)) {
11996            // Monolithic install
11997            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11998            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11999        } else {
12000            // Cluster install
12001            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12002            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12003                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12004                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12005                has64BitLibs = (new File(rootDir, isa)).exists();
12006            } else {
12007                has64BitLibs = false;
12008            }
12009            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12010                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12011                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12012                has32BitLibs = (new File(rootDir, isa)).exists();
12013            } else {
12014                has32BitLibs = false;
12015            }
12016        }
12017
12018        if (has64BitLibs && !has32BitLibs) {
12019            // The package has 64 bit libs, but not 32 bit libs. Its primary
12020            // ABI should be 64 bit. We can safely assume here that the bundled
12021            // native libraries correspond to the most preferred ABI in the list.
12022
12023            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12024            pkg.applicationInfo.secondaryCpuAbi = null;
12025        } else if (has32BitLibs && !has64BitLibs) {
12026            // The package has 32 bit libs but not 64 bit libs. Its primary
12027            // ABI should be 32 bit.
12028
12029            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12030            pkg.applicationInfo.secondaryCpuAbi = null;
12031        } else if (has32BitLibs && has64BitLibs) {
12032            // The application has both 64 and 32 bit bundled libraries. We check
12033            // here that the app declares multiArch support, and warn if it doesn't.
12034            //
12035            // We will be lenient here and record both ABIs. The primary will be the
12036            // ABI that's higher on the list, i.e, a device that's configured to prefer
12037            // 64 bit apps will see a 64 bit primary ABI,
12038
12039            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12040                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12041            }
12042
12043            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12044                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12045                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12046            } else {
12047                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12048                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12049            }
12050        } else {
12051            pkg.applicationInfo.primaryCpuAbi = null;
12052            pkg.applicationInfo.secondaryCpuAbi = null;
12053        }
12054    }
12055
12056    private void killApplication(String pkgName, int appId, String reason) {
12057        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12058    }
12059
12060    private void killApplication(String pkgName, int appId, int userId, String reason) {
12061        // Request the ActivityManager to kill the process(only for existing packages)
12062        // so that we do not end up in a confused state while the user is still using the older
12063        // version of the application while the new one gets installed.
12064        final long token = Binder.clearCallingIdentity();
12065        try {
12066            IActivityManager am = ActivityManager.getService();
12067            if (am != null) {
12068                try {
12069                    am.killApplication(pkgName, appId, userId, reason);
12070                } catch (RemoteException e) {
12071                }
12072            }
12073        } finally {
12074            Binder.restoreCallingIdentity(token);
12075        }
12076    }
12077
12078    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12079        // Remove the parent package setting
12080        PackageSetting ps = (PackageSetting) pkg.mExtras;
12081        if (ps != null) {
12082            removePackageLI(ps, chatty);
12083        }
12084        // Remove the child package setting
12085        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12086        for (int i = 0; i < childCount; i++) {
12087            PackageParser.Package childPkg = pkg.childPackages.get(i);
12088            ps = (PackageSetting) childPkg.mExtras;
12089            if (ps != null) {
12090                removePackageLI(ps, chatty);
12091            }
12092        }
12093    }
12094
12095    void removePackageLI(PackageSetting ps, boolean chatty) {
12096        if (DEBUG_INSTALL) {
12097            if (chatty)
12098                Log.d(TAG, "Removing package " + ps.name);
12099        }
12100
12101        // writer
12102        synchronized (mPackages) {
12103            mPackages.remove(ps.name);
12104            final PackageParser.Package pkg = ps.pkg;
12105            if (pkg != null) {
12106                cleanPackageDataStructuresLILPw(pkg, chatty);
12107            }
12108        }
12109    }
12110
12111    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12112        if (DEBUG_INSTALL) {
12113            if (chatty)
12114                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12115        }
12116
12117        // writer
12118        synchronized (mPackages) {
12119            // Remove the parent package
12120            mPackages.remove(pkg.applicationInfo.packageName);
12121            cleanPackageDataStructuresLILPw(pkg, chatty);
12122
12123            // Remove the child packages
12124            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12125            for (int i = 0; i < childCount; i++) {
12126                PackageParser.Package childPkg = pkg.childPackages.get(i);
12127                mPackages.remove(childPkg.applicationInfo.packageName);
12128                cleanPackageDataStructuresLILPw(childPkg, chatty);
12129            }
12130        }
12131    }
12132
12133    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12134        int N = pkg.providers.size();
12135        StringBuilder r = null;
12136        int i;
12137        for (i=0; i<N; i++) {
12138            PackageParser.Provider p = pkg.providers.get(i);
12139            mProviders.removeProvider(p);
12140            if (p.info.authority == null) {
12141
12142                /* There was another ContentProvider with this authority when
12143                 * this app was installed so this authority is null,
12144                 * Ignore it as we don't have to unregister the provider.
12145                 */
12146                continue;
12147            }
12148            String names[] = p.info.authority.split(";");
12149            for (int j = 0; j < names.length; j++) {
12150                if (mProvidersByAuthority.get(names[j]) == p) {
12151                    mProvidersByAuthority.remove(names[j]);
12152                    if (DEBUG_REMOVE) {
12153                        if (chatty)
12154                            Log.d(TAG, "Unregistered content provider: " + names[j]
12155                                    + ", className = " + p.info.name + ", isSyncable = "
12156                                    + p.info.isSyncable);
12157                    }
12158                }
12159            }
12160            if (DEBUG_REMOVE && chatty) {
12161                if (r == null) {
12162                    r = new StringBuilder(256);
12163                } else {
12164                    r.append(' ');
12165                }
12166                r.append(p.info.name);
12167            }
12168        }
12169        if (r != null) {
12170            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12171        }
12172
12173        N = pkg.services.size();
12174        r = null;
12175        for (i=0; i<N; i++) {
12176            PackageParser.Service s = pkg.services.get(i);
12177            mServices.removeService(s);
12178            if (chatty) {
12179                if (r == null) {
12180                    r = new StringBuilder(256);
12181                } else {
12182                    r.append(' ');
12183                }
12184                r.append(s.info.name);
12185            }
12186        }
12187        if (r != null) {
12188            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12189        }
12190
12191        N = pkg.receivers.size();
12192        r = null;
12193        for (i=0; i<N; i++) {
12194            PackageParser.Activity a = pkg.receivers.get(i);
12195            mReceivers.removeActivity(a, "receiver");
12196            if (DEBUG_REMOVE && chatty) {
12197                if (r == null) {
12198                    r = new StringBuilder(256);
12199                } else {
12200                    r.append(' ');
12201                }
12202                r.append(a.info.name);
12203            }
12204        }
12205        if (r != null) {
12206            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12207        }
12208
12209        N = pkg.activities.size();
12210        r = null;
12211        for (i=0; i<N; i++) {
12212            PackageParser.Activity a = pkg.activities.get(i);
12213            mActivities.removeActivity(a, "activity");
12214            if (DEBUG_REMOVE && chatty) {
12215                if (r == null) {
12216                    r = new StringBuilder(256);
12217                } else {
12218                    r.append(' ');
12219                }
12220                r.append(a.info.name);
12221            }
12222        }
12223        if (r != null) {
12224            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12225        }
12226
12227        N = pkg.permissions.size();
12228        r = null;
12229        for (i=0; i<N; i++) {
12230            PackageParser.Permission p = pkg.permissions.get(i);
12231            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12232            if (bp == null) {
12233                bp = mSettings.mPermissionTrees.get(p.info.name);
12234            }
12235            if (bp != null && bp.perm == p) {
12236                bp.perm = null;
12237                if (DEBUG_REMOVE && chatty) {
12238                    if (r == null) {
12239                        r = new StringBuilder(256);
12240                    } else {
12241                        r.append(' ');
12242                    }
12243                    r.append(p.info.name);
12244                }
12245            }
12246            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12247                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12248                if (appOpPkgs != null) {
12249                    appOpPkgs.remove(pkg.packageName);
12250                }
12251            }
12252        }
12253        if (r != null) {
12254            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12255        }
12256
12257        N = pkg.requestedPermissions.size();
12258        r = null;
12259        for (i=0; i<N; i++) {
12260            String perm = pkg.requestedPermissions.get(i);
12261            BasePermission bp = mSettings.mPermissions.get(perm);
12262            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12263                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12264                if (appOpPkgs != null) {
12265                    appOpPkgs.remove(pkg.packageName);
12266                    if (appOpPkgs.isEmpty()) {
12267                        mAppOpPermissionPackages.remove(perm);
12268                    }
12269                }
12270            }
12271        }
12272        if (r != null) {
12273            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12274        }
12275
12276        N = pkg.instrumentation.size();
12277        r = null;
12278        for (i=0; i<N; i++) {
12279            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12280            mInstrumentation.remove(a.getComponentName());
12281            if (DEBUG_REMOVE && chatty) {
12282                if (r == null) {
12283                    r = new StringBuilder(256);
12284                } else {
12285                    r.append(' ');
12286                }
12287                r.append(a.info.name);
12288            }
12289        }
12290        if (r != null) {
12291            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12292        }
12293
12294        r = null;
12295        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12296            // Only system apps can hold shared libraries.
12297            if (pkg.libraryNames != null) {
12298                for (i = 0; i < pkg.libraryNames.size(); i++) {
12299                    String name = pkg.libraryNames.get(i);
12300                    if (removeSharedLibraryLPw(name, 0)) {
12301                        if (DEBUG_REMOVE && chatty) {
12302                            if (r == null) {
12303                                r = new StringBuilder(256);
12304                            } else {
12305                                r.append(' ');
12306                            }
12307                            r.append(name);
12308                        }
12309                    }
12310                }
12311            }
12312        }
12313
12314        r = null;
12315
12316        // Any package can hold static shared libraries.
12317        if (pkg.staticSharedLibName != null) {
12318            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12319                if (DEBUG_REMOVE && chatty) {
12320                    if (r == null) {
12321                        r = new StringBuilder(256);
12322                    } else {
12323                        r.append(' ');
12324                    }
12325                    r.append(pkg.staticSharedLibName);
12326                }
12327            }
12328        }
12329
12330        if (r != null) {
12331            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12332        }
12333    }
12334
12335    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12336        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12337            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12338                return true;
12339            }
12340        }
12341        return false;
12342    }
12343
12344    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12345    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12346    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12347
12348    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12349        // Update the parent permissions
12350        updatePermissionsLPw(pkg.packageName, pkg, flags);
12351        // Update the child permissions
12352        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12353        for (int i = 0; i < childCount; i++) {
12354            PackageParser.Package childPkg = pkg.childPackages.get(i);
12355            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12356        }
12357    }
12358
12359    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12360            int flags) {
12361        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12362        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12363    }
12364
12365    private void updatePermissionsLPw(String changingPkg,
12366            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12367        // Make sure there are no dangling permission trees.
12368        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12369        while (it.hasNext()) {
12370            final BasePermission bp = it.next();
12371            if (bp.packageSetting == null) {
12372                // We may not yet have parsed the package, so just see if
12373                // we still know about its settings.
12374                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12375            }
12376            if (bp.packageSetting == null) {
12377                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12378                        + " from package " + bp.sourcePackage);
12379                it.remove();
12380            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12381                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12382                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12383                            + " from package " + bp.sourcePackage);
12384                    flags |= UPDATE_PERMISSIONS_ALL;
12385                    it.remove();
12386                }
12387            }
12388        }
12389
12390        // Make sure all dynamic permissions have been assigned to a package,
12391        // and make sure there are no dangling permissions.
12392        it = mSettings.mPermissions.values().iterator();
12393        while (it.hasNext()) {
12394            final BasePermission bp = it.next();
12395            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12396                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12397                        + bp.name + " pkg=" + bp.sourcePackage
12398                        + " info=" + bp.pendingInfo);
12399                if (bp.packageSetting == null && bp.pendingInfo != null) {
12400                    final BasePermission tree = findPermissionTreeLP(bp.name);
12401                    if (tree != null && tree.perm != null) {
12402                        bp.packageSetting = tree.packageSetting;
12403                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12404                                new PermissionInfo(bp.pendingInfo));
12405                        bp.perm.info.packageName = tree.perm.info.packageName;
12406                        bp.perm.info.name = bp.name;
12407                        bp.uid = tree.uid;
12408                    }
12409                }
12410            }
12411            if (bp.packageSetting == null) {
12412                // We may not yet have parsed the package, so just see if
12413                // we still know about its settings.
12414                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12415            }
12416            if (bp.packageSetting == null) {
12417                Slog.w(TAG, "Removing dangling permission: " + bp.name
12418                        + " from package " + bp.sourcePackage);
12419                it.remove();
12420            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12421                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12422                    Slog.i(TAG, "Removing old permission: " + bp.name
12423                            + " from package " + bp.sourcePackage);
12424                    flags |= UPDATE_PERMISSIONS_ALL;
12425                    it.remove();
12426                }
12427            }
12428        }
12429
12430        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12431        // Now update the permissions for all packages, in particular
12432        // replace the granted permissions of the system packages.
12433        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12434            for (PackageParser.Package pkg : mPackages.values()) {
12435                if (pkg != pkgInfo) {
12436                    // Only replace for packages on requested volume
12437                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12438                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12439                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12440                    grantPermissionsLPw(pkg, replace, changingPkg);
12441                }
12442            }
12443        }
12444
12445        if (pkgInfo != null) {
12446            // Only replace for packages on requested volume
12447            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12448            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12449                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12450            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12451        }
12452        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12453    }
12454
12455    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12456            String packageOfInterest) {
12457        // IMPORTANT: There are two types of permissions: install and runtime.
12458        // Install time permissions are granted when the app is installed to
12459        // all device users and users added in the future. Runtime permissions
12460        // are granted at runtime explicitly to specific users. Normal and signature
12461        // protected permissions are install time permissions. Dangerous permissions
12462        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12463        // otherwise they are runtime permissions. This function does not manage
12464        // runtime permissions except for the case an app targeting Lollipop MR1
12465        // being upgraded to target a newer SDK, in which case dangerous permissions
12466        // are transformed from install time to runtime ones.
12467
12468        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12469        if (ps == null) {
12470            return;
12471        }
12472
12473        PermissionsState permissionsState = ps.getPermissionsState();
12474        PermissionsState origPermissions = permissionsState;
12475
12476        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12477
12478        boolean runtimePermissionsRevoked = false;
12479        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12480
12481        boolean changedInstallPermission = false;
12482
12483        if (replace) {
12484            ps.installPermissionsFixed = false;
12485            if (!ps.isSharedUser()) {
12486                origPermissions = new PermissionsState(permissionsState);
12487                permissionsState.reset();
12488            } else {
12489                // We need to know only about runtime permission changes since the
12490                // calling code always writes the install permissions state but
12491                // the runtime ones are written only if changed. The only cases of
12492                // changed runtime permissions here are promotion of an install to
12493                // runtime and revocation of a runtime from a shared user.
12494                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12495                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12496                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12497                    runtimePermissionsRevoked = true;
12498                }
12499            }
12500        }
12501
12502        permissionsState.setGlobalGids(mGlobalGids);
12503
12504        final int N = pkg.requestedPermissions.size();
12505        for (int i=0; i<N; i++) {
12506            final String name = pkg.requestedPermissions.get(i);
12507            final BasePermission bp = mSettings.mPermissions.get(name);
12508            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12509                    >= Build.VERSION_CODES.M;
12510
12511            if (DEBUG_INSTALL) {
12512                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12513            }
12514
12515            if (bp == null || bp.packageSetting == null) {
12516                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12517                    if (DEBUG_PERMISSIONS) {
12518                        Slog.i(TAG, "Unknown permission " + name
12519                                + " in package " + pkg.packageName);
12520                    }
12521                }
12522                continue;
12523            }
12524
12525
12526            // Limit ephemeral apps to ephemeral allowed permissions.
12527            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12528                if (DEBUG_PERMISSIONS) {
12529                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12530                            + pkg.packageName);
12531                }
12532                continue;
12533            }
12534
12535            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12536                if (DEBUG_PERMISSIONS) {
12537                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12538                            + pkg.packageName);
12539                }
12540                continue;
12541            }
12542
12543            final String perm = bp.name;
12544            boolean allowedSig = false;
12545            int grant = GRANT_DENIED;
12546
12547            // Keep track of app op permissions.
12548            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12549                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12550                if (pkgs == null) {
12551                    pkgs = new ArraySet<>();
12552                    mAppOpPermissionPackages.put(bp.name, pkgs);
12553                }
12554                pkgs.add(pkg.packageName);
12555            }
12556
12557            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12558            switch (level) {
12559                case PermissionInfo.PROTECTION_NORMAL: {
12560                    // For all apps normal permissions are install time ones.
12561                    grant = GRANT_INSTALL;
12562                } break;
12563
12564                case PermissionInfo.PROTECTION_DANGEROUS: {
12565                    // If a permission review is required for legacy apps we represent
12566                    // their permissions as always granted runtime ones since we need
12567                    // to keep the review required permission flag per user while an
12568                    // install permission's state is shared across all users.
12569                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12570                        // For legacy apps dangerous permissions are install time ones.
12571                        grant = GRANT_INSTALL;
12572                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12573                        // For legacy apps that became modern, install becomes runtime.
12574                        grant = GRANT_UPGRADE;
12575                    } else if (mPromoteSystemApps
12576                            && isSystemApp(ps)
12577                            && mExistingSystemPackages.contains(ps.name)) {
12578                        // For legacy system apps, install becomes runtime.
12579                        // We cannot check hasInstallPermission() for system apps since those
12580                        // permissions were granted implicitly and not persisted pre-M.
12581                        grant = GRANT_UPGRADE;
12582                    } else {
12583                        // For modern apps keep runtime permissions unchanged.
12584                        grant = GRANT_RUNTIME;
12585                    }
12586                } break;
12587
12588                case PermissionInfo.PROTECTION_SIGNATURE: {
12589                    // For all apps signature permissions are install time ones.
12590                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12591                    if (allowedSig) {
12592                        grant = GRANT_INSTALL;
12593                    }
12594                } break;
12595            }
12596
12597            if (DEBUG_PERMISSIONS) {
12598                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12599            }
12600
12601            if (grant != GRANT_DENIED) {
12602                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12603                    // If this is an existing, non-system package, then
12604                    // we can't add any new permissions to it.
12605                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12606                        // Except...  if this is a permission that was added
12607                        // to the platform (note: need to only do this when
12608                        // updating the platform).
12609                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12610                            grant = GRANT_DENIED;
12611                        }
12612                    }
12613                }
12614
12615                switch (grant) {
12616                    case GRANT_INSTALL: {
12617                        // Revoke this as runtime permission to handle the case of
12618                        // a runtime permission being downgraded to an install one.
12619                        // Also in permission review mode we keep dangerous permissions
12620                        // for legacy apps
12621                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12622                            if (origPermissions.getRuntimePermissionState(
12623                                    bp.name, userId) != null) {
12624                                // Revoke the runtime permission and clear the flags.
12625                                origPermissions.revokeRuntimePermission(bp, userId);
12626                                origPermissions.updatePermissionFlags(bp, userId,
12627                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12628                                // If we revoked a permission permission, we have to write.
12629                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12630                                        changedRuntimePermissionUserIds, userId);
12631                            }
12632                        }
12633                        // Grant an install permission.
12634                        if (permissionsState.grantInstallPermission(bp) !=
12635                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12636                            changedInstallPermission = true;
12637                        }
12638                    } break;
12639
12640                    case GRANT_RUNTIME: {
12641                        // Grant previously granted runtime permissions.
12642                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12643                            PermissionState permissionState = origPermissions
12644                                    .getRuntimePermissionState(bp.name, userId);
12645                            int flags = permissionState != null
12646                                    ? permissionState.getFlags() : 0;
12647                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12648                                // Don't propagate the permission in a permission review mode if
12649                                // the former was revoked, i.e. marked to not propagate on upgrade.
12650                                // Note that in a permission review mode install permissions are
12651                                // represented as constantly granted runtime ones since we need to
12652                                // keep a per user state associated with the permission. Also the
12653                                // revoke on upgrade flag is no longer applicable and is reset.
12654                                final boolean revokeOnUpgrade = (flags & PackageManager
12655                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12656                                if (revokeOnUpgrade) {
12657                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12658                                    // Since we changed the flags, we have to write.
12659                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12660                                            changedRuntimePermissionUserIds, userId);
12661                                }
12662                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12663                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12664                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12665                                        // If we cannot put the permission as it was,
12666                                        // we have to write.
12667                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12668                                                changedRuntimePermissionUserIds, userId);
12669                                    }
12670                                }
12671
12672                                // If the app supports runtime permissions no need for a review.
12673                                if (mPermissionReviewRequired
12674                                        && appSupportsRuntimePermissions
12675                                        && (flags & PackageManager
12676                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12677                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12678                                    // Since we changed the flags, we have to write.
12679                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12680                                            changedRuntimePermissionUserIds, userId);
12681                                }
12682                            } else if (mPermissionReviewRequired
12683                                    && !appSupportsRuntimePermissions) {
12684                                // For legacy apps that need a permission review, every new
12685                                // runtime permission is granted but it is pending a review.
12686                                // We also need to review only platform defined runtime
12687                                // permissions as these are the only ones the platform knows
12688                                // how to disable the API to simulate revocation as legacy
12689                                // apps don't expect to run with revoked permissions.
12690                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12691                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12692                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12693                                        // We changed the flags, hence have to write.
12694                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12695                                                changedRuntimePermissionUserIds, userId);
12696                                    }
12697                                }
12698                                if (permissionsState.grantRuntimePermission(bp, userId)
12699                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12700                                    // We changed the permission, hence have to write.
12701                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12702                                            changedRuntimePermissionUserIds, userId);
12703                                }
12704                            }
12705                            // Propagate the permission flags.
12706                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12707                        }
12708                    } break;
12709
12710                    case GRANT_UPGRADE: {
12711                        // Grant runtime permissions for a previously held install permission.
12712                        PermissionState permissionState = origPermissions
12713                                .getInstallPermissionState(bp.name);
12714                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12715
12716                        if (origPermissions.revokeInstallPermission(bp)
12717                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12718                            // We will be transferring the permission flags, so clear them.
12719                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12720                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12721                            changedInstallPermission = true;
12722                        }
12723
12724                        // If the permission is not to be promoted to runtime we ignore it and
12725                        // also its other flags as they are not applicable to install permissions.
12726                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12727                            for (int userId : currentUserIds) {
12728                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12729                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12730                                    // Transfer the permission flags.
12731                                    permissionsState.updatePermissionFlags(bp, userId,
12732                                            flags, flags);
12733                                    // If we granted the permission, we have to write.
12734                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12735                                            changedRuntimePermissionUserIds, userId);
12736                                }
12737                            }
12738                        }
12739                    } break;
12740
12741                    default: {
12742                        if (packageOfInterest == null
12743                                || packageOfInterest.equals(pkg.packageName)) {
12744                            if (DEBUG_PERMISSIONS) {
12745                                Slog.i(TAG, "Not granting permission " + perm
12746                                        + " to package " + pkg.packageName
12747                                        + " because it was previously installed without");
12748                            }
12749                        }
12750                    } break;
12751                }
12752            } else {
12753                if (permissionsState.revokeInstallPermission(bp) !=
12754                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12755                    // Also drop the permission flags.
12756                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12757                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12758                    changedInstallPermission = true;
12759                    Slog.i(TAG, "Un-granting permission " + perm
12760                            + " from package " + pkg.packageName
12761                            + " (protectionLevel=" + bp.protectionLevel
12762                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12763                            + ")");
12764                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12765                    // Don't print warning for app op permissions, since it is fine for them
12766                    // not to be granted, there is a UI for the user to decide.
12767                    if (DEBUG_PERMISSIONS
12768                            && (packageOfInterest == null
12769                                    || packageOfInterest.equals(pkg.packageName))) {
12770                        Slog.i(TAG, "Not granting permission " + perm
12771                                + " to package " + pkg.packageName
12772                                + " (protectionLevel=" + bp.protectionLevel
12773                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12774                                + ")");
12775                    }
12776                }
12777            }
12778        }
12779
12780        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12781                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12782            // This is the first that we have heard about this package, so the
12783            // permissions we have now selected are fixed until explicitly
12784            // changed.
12785            ps.installPermissionsFixed = true;
12786        }
12787
12788        // Persist the runtime permissions state for users with changes. If permissions
12789        // were revoked because no app in the shared user declares them we have to
12790        // write synchronously to avoid losing runtime permissions state.
12791        for (int userId : changedRuntimePermissionUserIds) {
12792            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12793        }
12794    }
12795
12796    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12797        boolean allowed = false;
12798        final int NP = PackageParser.NEW_PERMISSIONS.length;
12799        for (int ip=0; ip<NP; ip++) {
12800            final PackageParser.NewPermissionInfo npi
12801                    = PackageParser.NEW_PERMISSIONS[ip];
12802            if (npi.name.equals(perm)
12803                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12804                allowed = true;
12805                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12806                        + pkg.packageName);
12807                break;
12808            }
12809        }
12810        return allowed;
12811    }
12812
12813    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12814            BasePermission bp, PermissionsState origPermissions) {
12815        boolean privilegedPermission = (bp.protectionLevel
12816                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12817        boolean privappPermissionsDisable =
12818                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12819        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12820        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12821        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12822                && !platformPackage && platformPermission) {
12823            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12824                    .getPrivAppPermissions(pkg.packageName);
12825            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12826            if (!whitelisted) {
12827                Slog.w(TAG, "Privileged permission " + perm + " for package "
12828                        + pkg.packageName + " - not in privapp-permissions whitelist");
12829                // Only report violations for apps on system image
12830                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12831                    if (mPrivappPermissionsViolations == null) {
12832                        mPrivappPermissionsViolations = new ArraySet<>();
12833                    }
12834                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12835                }
12836                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12837                    return false;
12838                }
12839            }
12840        }
12841        boolean allowed = (compareSignatures(
12842                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12843                        == PackageManager.SIGNATURE_MATCH)
12844                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12845                        == PackageManager.SIGNATURE_MATCH);
12846        if (!allowed && privilegedPermission) {
12847            if (isSystemApp(pkg)) {
12848                // For updated system applications, a system permission
12849                // is granted only if it had been defined by the original application.
12850                if (pkg.isUpdatedSystemApp()) {
12851                    final PackageSetting sysPs = mSettings
12852                            .getDisabledSystemPkgLPr(pkg.packageName);
12853                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12854                        // If the original was granted this permission, we take
12855                        // that grant decision as read and propagate it to the
12856                        // update.
12857                        if (sysPs.isPrivileged()) {
12858                            allowed = true;
12859                        }
12860                    } else {
12861                        // The system apk may have been updated with an older
12862                        // version of the one on the data partition, but which
12863                        // granted a new system permission that it didn't have
12864                        // before.  In this case we do want to allow the app to
12865                        // now get the new permission if the ancestral apk is
12866                        // privileged to get it.
12867                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12868                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12869                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12870                                    allowed = true;
12871                                    break;
12872                                }
12873                            }
12874                        }
12875                        // Also if a privileged parent package on the system image or any of
12876                        // its children requested a privileged permission, the updated child
12877                        // packages can also get the permission.
12878                        if (pkg.parentPackage != null) {
12879                            final PackageSetting disabledSysParentPs = mSettings
12880                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12881                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12882                                    && disabledSysParentPs.isPrivileged()) {
12883                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12884                                    allowed = true;
12885                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12886                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12887                                    for (int i = 0; i < count; i++) {
12888                                        PackageParser.Package disabledSysChildPkg =
12889                                                disabledSysParentPs.pkg.childPackages.get(i);
12890                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12891                                                perm)) {
12892                                            allowed = true;
12893                                            break;
12894                                        }
12895                                    }
12896                                }
12897                            }
12898                        }
12899                    }
12900                } else {
12901                    allowed = isPrivilegedApp(pkg);
12902                }
12903            }
12904        }
12905        if (!allowed) {
12906            if (!allowed && (bp.protectionLevel
12907                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12908                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12909                // If this was a previously normal/dangerous permission that got moved
12910                // to a system permission as part of the runtime permission redesign, then
12911                // we still want to blindly grant it to old apps.
12912                allowed = true;
12913            }
12914            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12915                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12916                // If this permission is to be granted to the system installer and
12917                // this app is an installer, then it gets the permission.
12918                allowed = true;
12919            }
12920            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12921                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12922                // If this permission is to be granted to the system verifier and
12923                // this app is a verifier, then it gets the permission.
12924                allowed = true;
12925            }
12926            if (!allowed && (bp.protectionLevel
12927                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12928                    && isSystemApp(pkg)) {
12929                // Any pre-installed system app is allowed to get this permission.
12930                allowed = true;
12931            }
12932            if (!allowed && (bp.protectionLevel
12933                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12934                // For development permissions, a development permission
12935                // is granted only if it was already granted.
12936                allowed = origPermissions.hasInstallPermission(perm);
12937            }
12938            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12939                    && pkg.packageName.equals(mSetupWizardPackage)) {
12940                // If this permission is to be granted to the system setup wizard and
12941                // this app is a setup wizard, then it gets the permission.
12942                allowed = true;
12943            }
12944        }
12945        return allowed;
12946    }
12947
12948    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12949        final int permCount = pkg.requestedPermissions.size();
12950        for (int j = 0; j < permCount; j++) {
12951            String requestedPermission = pkg.requestedPermissions.get(j);
12952            if (permission.equals(requestedPermission)) {
12953                return true;
12954            }
12955        }
12956        return false;
12957    }
12958
12959    final class ActivityIntentResolver
12960            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12961        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12962                boolean defaultOnly, int userId) {
12963            if (!sUserManager.exists(userId)) return null;
12964            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12965            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12966        }
12967
12968        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12969                int userId) {
12970            if (!sUserManager.exists(userId)) return null;
12971            mFlags = flags;
12972            return super.queryIntent(intent, resolvedType,
12973                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12974                    userId);
12975        }
12976
12977        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12978                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12979            if (!sUserManager.exists(userId)) return null;
12980            if (packageActivities == null) {
12981                return null;
12982            }
12983            mFlags = flags;
12984            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12985            final int N = packageActivities.size();
12986            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12987                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12988
12989            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12990            for (int i = 0; i < N; ++i) {
12991                intentFilters = packageActivities.get(i).intents;
12992                if (intentFilters != null && intentFilters.size() > 0) {
12993                    PackageParser.ActivityIntentInfo[] array =
12994                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12995                    intentFilters.toArray(array);
12996                    listCut.add(array);
12997                }
12998            }
12999            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13000        }
13001
13002        /**
13003         * Finds a privileged activity that matches the specified activity names.
13004         */
13005        private PackageParser.Activity findMatchingActivity(
13006                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13007            for (PackageParser.Activity sysActivity : activityList) {
13008                if (sysActivity.info.name.equals(activityInfo.name)) {
13009                    return sysActivity;
13010                }
13011                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13012                    return sysActivity;
13013                }
13014                if (sysActivity.info.targetActivity != null) {
13015                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13016                        return sysActivity;
13017                    }
13018                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13019                        return sysActivity;
13020                    }
13021                }
13022            }
13023            return null;
13024        }
13025
13026        public class IterGenerator<E> {
13027            public Iterator<E> generate(ActivityIntentInfo info) {
13028                return null;
13029            }
13030        }
13031
13032        public class ActionIterGenerator extends IterGenerator<String> {
13033            @Override
13034            public Iterator<String> generate(ActivityIntentInfo info) {
13035                return info.actionsIterator();
13036            }
13037        }
13038
13039        public class CategoriesIterGenerator extends IterGenerator<String> {
13040            @Override
13041            public Iterator<String> generate(ActivityIntentInfo info) {
13042                return info.categoriesIterator();
13043            }
13044        }
13045
13046        public class SchemesIterGenerator extends IterGenerator<String> {
13047            @Override
13048            public Iterator<String> generate(ActivityIntentInfo info) {
13049                return info.schemesIterator();
13050            }
13051        }
13052
13053        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13054            @Override
13055            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13056                return info.authoritiesIterator();
13057            }
13058        }
13059
13060        /**
13061         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13062         * MODIFIED. Do not pass in a list that should not be changed.
13063         */
13064        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13065                IterGenerator<T> generator, Iterator<T> searchIterator) {
13066            // loop through the set of actions; every one must be found in the intent filter
13067            while (searchIterator.hasNext()) {
13068                // we must have at least one filter in the list to consider a match
13069                if (intentList.size() == 0) {
13070                    break;
13071                }
13072
13073                final T searchAction = searchIterator.next();
13074
13075                // loop through the set of intent filters
13076                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13077                while (intentIter.hasNext()) {
13078                    final ActivityIntentInfo intentInfo = intentIter.next();
13079                    boolean selectionFound = false;
13080
13081                    // loop through the intent filter's selection criteria; at least one
13082                    // of them must match the searched criteria
13083                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13084                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13085                        final T intentSelection = intentSelectionIter.next();
13086                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13087                            selectionFound = true;
13088                            break;
13089                        }
13090                    }
13091
13092                    // the selection criteria wasn't found in this filter's set; this filter
13093                    // is not a potential match
13094                    if (!selectionFound) {
13095                        intentIter.remove();
13096                    }
13097                }
13098            }
13099        }
13100
13101        private boolean isProtectedAction(ActivityIntentInfo filter) {
13102            final Iterator<String> actionsIter = filter.actionsIterator();
13103            while (actionsIter != null && actionsIter.hasNext()) {
13104                final String filterAction = actionsIter.next();
13105                if (PROTECTED_ACTIONS.contains(filterAction)) {
13106                    return true;
13107                }
13108            }
13109            return false;
13110        }
13111
13112        /**
13113         * Adjusts the priority of the given intent filter according to policy.
13114         * <p>
13115         * <ul>
13116         * <li>The priority for non privileged applications is capped to '0'</li>
13117         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13118         * <li>The priority for unbundled updates to privileged applications is capped to the
13119         *      priority defined on the system partition</li>
13120         * </ul>
13121         * <p>
13122         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13123         * allowed to obtain any priority on any action.
13124         */
13125        private void adjustPriority(
13126                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13127            // nothing to do; priority is fine as-is
13128            if (intent.getPriority() <= 0) {
13129                return;
13130            }
13131
13132            final ActivityInfo activityInfo = intent.activity.info;
13133            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13134
13135            final boolean privilegedApp =
13136                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13137            if (!privilegedApp) {
13138                // non-privileged applications can never define a priority >0
13139                if (DEBUG_FILTERS) {
13140                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13141                            + " package: " + applicationInfo.packageName
13142                            + " activity: " + intent.activity.className
13143                            + " origPrio: " + intent.getPriority());
13144                }
13145                intent.setPriority(0);
13146                return;
13147            }
13148
13149            if (systemActivities == null) {
13150                // the system package is not disabled; we're parsing the system partition
13151                if (isProtectedAction(intent)) {
13152                    if (mDeferProtectedFilters) {
13153                        // We can't deal with these just yet. No component should ever obtain a
13154                        // >0 priority for a protected actions, with ONE exception -- the setup
13155                        // wizard. The setup wizard, however, cannot be known until we're able to
13156                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13157                        // until all intent filters have been processed. Chicken, meet egg.
13158                        // Let the filter temporarily have a high priority and rectify the
13159                        // priorities after all system packages have been scanned.
13160                        mProtectedFilters.add(intent);
13161                        if (DEBUG_FILTERS) {
13162                            Slog.i(TAG, "Protected action; save for later;"
13163                                    + " package: " + applicationInfo.packageName
13164                                    + " activity: " + intent.activity.className
13165                                    + " origPrio: " + intent.getPriority());
13166                        }
13167                        return;
13168                    } else {
13169                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13170                            Slog.i(TAG, "No setup wizard;"
13171                                + " All protected intents capped to priority 0");
13172                        }
13173                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13174                            if (DEBUG_FILTERS) {
13175                                Slog.i(TAG, "Found setup wizard;"
13176                                    + " allow priority " + intent.getPriority() + ";"
13177                                    + " package: " + intent.activity.info.packageName
13178                                    + " activity: " + intent.activity.className
13179                                    + " priority: " + intent.getPriority());
13180                            }
13181                            // setup wizard gets whatever it wants
13182                            return;
13183                        }
13184                        if (DEBUG_FILTERS) {
13185                            Slog.i(TAG, "Protected action; cap priority to 0;"
13186                                    + " package: " + intent.activity.info.packageName
13187                                    + " activity: " + intent.activity.className
13188                                    + " origPrio: " + intent.getPriority());
13189                        }
13190                        intent.setPriority(0);
13191                        return;
13192                    }
13193                }
13194                // privileged apps on the system image get whatever priority they request
13195                return;
13196            }
13197
13198            // privileged app unbundled update ... try to find the same activity
13199            final PackageParser.Activity foundActivity =
13200                    findMatchingActivity(systemActivities, activityInfo);
13201            if (foundActivity == null) {
13202                // this is a new activity; it cannot obtain >0 priority
13203                if (DEBUG_FILTERS) {
13204                    Slog.i(TAG, "New activity; cap priority to 0;"
13205                            + " package: " + applicationInfo.packageName
13206                            + " activity: " + intent.activity.className
13207                            + " origPrio: " + intent.getPriority());
13208                }
13209                intent.setPriority(0);
13210                return;
13211            }
13212
13213            // found activity, now check for filter equivalence
13214
13215            // a shallow copy is enough; we modify the list, not its contents
13216            final List<ActivityIntentInfo> intentListCopy =
13217                    new ArrayList<>(foundActivity.intents);
13218            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13219
13220            // find matching action subsets
13221            final Iterator<String> actionsIterator = intent.actionsIterator();
13222            if (actionsIterator != null) {
13223                getIntentListSubset(
13224                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13225                if (intentListCopy.size() == 0) {
13226                    // no more intents to match; we're not equivalent
13227                    if (DEBUG_FILTERS) {
13228                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13229                                + " package: " + applicationInfo.packageName
13230                                + " activity: " + intent.activity.className
13231                                + " origPrio: " + intent.getPriority());
13232                    }
13233                    intent.setPriority(0);
13234                    return;
13235                }
13236            }
13237
13238            // find matching category subsets
13239            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13240            if (categoriesIterator != null) {
13241                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13242                        categoriesIterator);
13243                if (intentListCopy.size() == 0) {
13244                    // no more intents to match; we're not equivalent
13245                    if (DEBUG_FILTERS) {
13246                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13247                                + " package: " + applicationInfo.packageName
13248                                + " activity: " + intent.activity.className
13249                                + " origPrio: " + intent.getPriority());
13250                    }
13251                    intent.setPriority(0);
13252                    return;
13253                }
13254            }
13255
13256            // find matching schemes subsets
13257            final Iterator<String> schemesIterator = intent.schemesIterator();
13258            if (schemesIterator != null) {
13259                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13260                        schemesIterator);
13261                if (intentListCopy.size() == 0) {
13262                    // no more intents to match; we're not equivalent
13263                    if (DEBUG_FILTERS) {
13264                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13265                                + " package: " + applicationInfo.packageName
13266                                + " activity: " + intent.activity.className
13267                                + " origPrio: " + intent.getPriority());
13268                    }
13269                    intent.setPriority(0);
13270                    return;
13271                }
13272            }
13273
13274            // find matching authorities subsets
13275            final Iterator<IntentFilter.AuthorityEntry>
13276                    authoritiesIterator = intent.authoritiesIterator();
13277            if (authoritiesIterator != null) {
13278                getIntentListSubset(intentListCopy,
13279                        new AuthoritiesIterGenerator(),
13280                        authoritiesIterator);
13281                if (intentListCopy.size() == 0) {
13282                    // no more intents to match; we're not equivalent
13283                    if (DEBUG_FILTERS) {
13284                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13285                                + " package: " + applicationInfo.packageName
13286                                + " activity: " + intent.activity.className
13287                                + " origPrio: " + intent.getPriority());
13288                    }
13289                    intent.setPriority(0);
13290                    return;
13291                }
13292            }
13293
13294            // we found matching filter(s); app gets the max priority of all intents
13295            int cappedPriority = 0;
13296            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13297                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13298            }
13299            if (intent.getPriority() > cappedPriority) {
13300                if (DEBUG_FILTERS) {
13301                    Slog.i(TAG, "Found matching filter(s);"
13302                            + " cap priority to " + cappedPriority + ";"
13303                            + " package: " + applicationInfo.packageName
13304                            + " activity: " + intent.activity.className
13305                            + " origPrio: " + intent.getPriority());
13306                }
13307                intent.setPriority(cappedPriority);
13308                return;
13309            }
13310            // all this for nothing; the requested priority was <= what was on the system
13311        }
13312
13313        public final void addActivity(PackageParser.Activity a, String type) {
13314            mActivities.put(a.getComponentName(), a);
13315            if (DEBUG_SHOW_INFO)
13316                Log.v(
13317                TAG, "  " + type + " " +
13318                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13319            if (DEBUG_SHOW_INFO)
13320                Log.v(TAG, "    Class=" + a.info.name);
13321            final int NI = a.intents.size();
13322            for (int j=0; j<NI; j++) {
13323                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13324                if ("activity".equals(type)) {
13325                    final PackageSetting ps =
13326                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13327                    final List<PackageParser.Activity> systemActivities =
13328                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13329                    adjustPriority(systemActivities, intent);
13330                }
13331                if (DEBUG_SHOW_INFO) {
13332                    Log.v(TAG, "    IntentFilter:");
13333                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13334                }
13335                if (!intent.debugCheck()) {
13336                    Log.w(TAG, "==> For Activity " + a.info.name);
13337                }
13338                addFilter(intent);
13339            }
13340        }
13341
13342        public final void removeActivity(PackageParser.Activity a, String type) {
13343            mActivities.remove(a.getComponentName());
13344            if (DEBUG_SHOW_INFO) {
13345                Log.v(TAG, "  " + type + " "
13346                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13347                                : a.info.name) + ":");
13348                Log.v(TAG, "    Class=" + a.info.name);
13349            }
13350            final int NI = a.intents.size();
13351            for (int j=0; j<NI; j++) {
13352                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13353                if (DEBUG_SHOW_INFO) {
13354                    Log.v(TAG, "    IntentFilter:");
13355                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13356                }
13357                removeFilter(intent);
13358            }
13359        }
13360
13361        @Override
13362        protected boolean allowFilterResult(
13363                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13364            ActivityInfo filterAi = filter.activity.info;
13365            for (int i=dest.size()-1; i>=0; i--) {
13366                ActivityInfo destAi = dest.get(i).activityInfo;
13367                if (destAi.name == filterAi.name
13368                        && destAi.packageName == filterAi.packageName) {
13369                    return false;
13370                }
13371            }
13372            return true;
13373        }
13374
13375        @Override
13376        protected ActivityIntentInfo[] newArray(int size) {
13377            return new ActivityIntentInfo[size];
13378        }
13379
13380        @Override
13381        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13382            if (!sUserManager.exists(userId)) return true;
13383            PackageParser.Package p = filter.activity.owner;
13384            if (p != null) {
13385                PackageSetting ps = (PackageSetting)p.mExtras;
13386                if (ps != null) {
13387                    // System apps are never considered stopped for purposes of
13388                    // filtering, because there may be no way for the user to
13389                    // actually re-launch them.
13390                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13391                            && ps.getStopped(userId);
13392                }
13393            }
13394            return false;
13395        }
13396
13397        @Override
13398        protected boolean isPackageForFilter(String packageName,
13399                PackageParser.ActivityIntentInfo info) {
13400            return packageName.equals(info.activity.owner.packageName);
13401        }
13402
13403        @Override
13404        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13405                int match, int userId) {
13406            if (!sUserManager.exists(userId)) return null;
13407            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13408                return null;
13409            }
13410            final PackageParser.Activity activity = info.activity;
13411            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13412            if (ps == null) {
13413                return null;
13414            }
13415            final PackageUserState userState = ps.readUserState(userId);
13416            ActivityInfo ai =
13417                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13418            if (ai == null) {
13419                return null;
13420            }
13421            final boolean matchExplicitlyVisibleOnly =
13422                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13423            final boolean matchVisibleToInstantApp =
13424                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13425            final boolean componentVisible =
13426                    matchVisibleToInstantApp
13427                    && info.isVisibleToInstantApp()
13428                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13429            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13430            // throw out filters that aren't visible to ephemeral apps
13431            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13432                return null;
13433            }
13434            // throw out instant app filters if we're not explicitly requesting them
13435            if (!matchInstantApp && userState.instantApp) {
13436                return null;
13437            }
13438            // throw out instant app filters if updates are available; will trigger
13439            // instant app resolution
13440            if (userState.instantApp && ps.isUpdateAvailable()) {
13441                return null;
13442            }
13443            final ResolveInfo res = new ResolveInfo();
13444            res.activityInfo = ai;
13445            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13446                res.filter = info;
13447            }
13448            if (info != null) {
13449                res.handleAllWebDataURI = info.handleAllWebDataURI();
13450            }
13451            res.priority = info.getPriority();
13452            res.preferredOrder = activity.owner.mPreferredOrder;
13453            //System.out.println("Result: " + res.activityInfo.className +
13454            //                   " = " + res.priority);
13455            res.match = match;
13456            res.isDefault = info.hasDefault;
13457            res.labelRes = info.labelRes;
13458            res.nonLocalizedLabel = info.nonLocalizedLabel;
13459            if (userNeedsBadging(userId)) {
13460                res.noResourceId = true;
13461            } else {
13462                res.icon = info.icon;
13463            }
13464            res.iconResourceId = info.icon;
13465            res.system = res.activityInfo.applicationInfo.isSystemApp();
13466            res.isInstantAppAvailable = userState.instantApp;
13467            return res;
13468        }
13469
13470        @Override
13471        protected void sortResults(List<ResolveInfo> results) {
13472            Collections.sort(results, mResolvePrioritySorter);
13473        }
13474
13475        @Override
13476        protected void dumpFilter(PrintWriter out, String prefix,
13477                PackageParser.ActivityIntentInfo filter) {
13478            out.print(prefix); out.print(
13479                    Integer.toHexString(System.identityHashCode(filter.activity)));
13480                    out.print(' ');
13481                    filter.activity.printComponentShortName(out);
13482                    out.print(" filter ");
13483                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13484        }
13485
13486        @Override
13487        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13488            return filter.activity;
13489        }
13490
13491        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13492            PackageParser.Activity activity = (PackageParser.Activity)label;
13493            out.print(prefix); out.print(
13494                    Integer.toHexString(System.identityHashCode(activity)));
13495                    out.print(' ');
13496                    activity.printComponentShortName(out);
13497            if (count > 1) {
13498                out.print(" ("); out.print(count); out.print(" filters)");
13499            }
13500            out.println();
13501        }
13502
13503        // Keys are String (activity class name), values are Activity.
13504        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13505                = new ArrayMap<ComponentName, PackageParser.Activity>();
13506        private int mFlags;
13507    }
13508
13509    private final class ServiceIntentResolver
13510            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13511        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13512                boolean defaultOnly, int userId) {
13513            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13514            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13515        }
13516
13517        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13518                int userId) {
13519            if (!sUserManager.exists(userId)) return null;
13520            mFlags = flags;
13521            return super.queryIntent(intent, resolvedType,
13522                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13523                    userId);
13524        }
13525
13526        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13527                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13528            if (!sUserManager.exists(userId)) return null;
13529            if (packageServices == null) {
13530                return null;
13531            }
13532            mFlags = flags;
13533            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13534            final int N = packageServices.size();
13535            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13536                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13537
13538            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13539            for (int i = 0; i < N; ++i) {
13540                intentFilters = packageServices.get(i).intents;
13541                if (intentFilters != null && intentFilters.size() > 0) {
13542                    PackageParser.ServiceIntentInfo[] array =
13543                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13544                    intentFilters.toArray(array);
13545                    listCut.add(array);
13546                }
13547            }
13548            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13549        }
13550
13551        public final void addService(PackageParser.Service s) {
13552            mServices.put(s.getComponentName(), s);
13553            if (DEBUG_SHOW_INFO) {
13554                Log.v(TAG, "  "
13555                        + (s.info.nonLocalizedLabel != null
13556                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13557                Log.v(TAG, "    Class=" + s.info.name);
13558            }
13559            final int NI = s.intents.size();
13560            int j;
13561            for (j=0; j<NI; j++) {
13562                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13563                if (DEBUG_SHOW_INFO) {
13564                    Log.v(TAG, "    IntentFilter:");
13565                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13566                }
13567                if (!intent.debugCheck()) {
13568                    Log.w(TAG, "==> For Service " + s.info.name);
13569                }
13570                addFilter(intent);
13571            }
13572        }
13573
13574        public final void removeService(PackageParser.Service s) {
13575            mServices.remove(s.getComponentName());
13576            if (DEBUG_SHOW_INFO) {
13577                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13578                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13579                Log.v(TAG, "    Class=" + s.info.name);
13580            }
13581            final int NI = s.intents.size();
13582            int j;
13583            for (j=0; j<NI; j++) {
13584                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13585                if (DEBUG_SHOW_INFO) {
13586                    Log.v(TAG, "    IntentFilter:");
13587                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13588                }
13589                removeFilter(intent);
13590            }
13591        }
13592
13593        @Override
13594        protected boolean allowFilterResult(
13595                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13596            ServiceInfo filterSi = filter.service.info;
13597            for (int i=dest.size()-1; i>=0; i--) {
13598                ServiceInfo destAi = dest.get(i).serviceInfo;
13599                if (destAi.name == filterSi.name
13600                        && destAi.packageName == filterSi.packageName) {
13601                    return false;
13602                }
13603            }
13604            return true;
13605        }
13606
13607        @Override
13608        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13609            return new PackageParser.ServiceIntentInfo[size];
13610        }
13611
13612        @Override
13613        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13614            if (!sUserManager.exists(userId)) return true;
13615            PackageParser.Package p = filter.service.owner;
13616            if (p != null) {
13617                PackageSetting ps = (PackageSetting)p.mExtras;
13618                if (ps != null) {
13619                    // System apps are never considered stopped for purposes of
13620                    // filtering, because there may be no way for the user to
13621                    // actually re-launch them.
13622                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13623                            && ps.getStopped(userId);
13624                }
13625            }
13626            return false;
13627        }
13628
13629        @Override
13630        protected boolean isPackageForFilter(String packageName,
13631                PackageParser.ServiceIntentInfo info) {
13632            return packageName.equals(info.service.owner.packageName);
13633        }
13634
13635        @Override
13636        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13637                int match, int userId) {
13638            if (!sUserManager.exists(userId)) return null;
13639            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13640            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13641                return null;
13642            }
13643            final PackageParser.Service service = info.service;
13644            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13645            if (ps == null) {
13646                return null;
13647            }
13648            final PackageUserState userState = ps.readUserState(userId);
13649            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13650                    userState, userId);
13651            if (si == null) {
13652                return null;
13653            }
13654            final boolean matchVisibleToInstantApp =
13655                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13656            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13657            // throw out filters that aren't visible to ephemeral apps
13658            if (matchVisibleToInstantApp
13659                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13660                return null;
13661            }
13662            // throw out ephemeral filters if we're not explicitly requesting them
13663            if (!isInstantApp && userState.instantApp) {
13664                return null;
13665            }
13666            // throw out instant app filters if updates are available; will trigger
13667            // instant app resolution
13668            if (userState.instantApp && ps.isUpdateAvailable()) {
13669                return null;
13670            }
13671            final ResolveInfo res = new ResolveInfo();
13672            res.serviceInfo = si;
13673            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13674                res.filter = filter;
13675            }
13676            res.priority = info.getPriority();
13677            res.preferredOrder = service.owner.mPreferredOrder;
13678            res.match = match;
13679            res.isDefault = info.hasDefault;
13680            res.labelRes = info.labelRes;
13681            res.nonLocalizedLabel = info.nonLocalizedLabel;
13682            res.icon = info.icon;
13683            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13684            return res;
13685        }
13686
13687        @Override
13688        protected void sortResults(List<ResolveInfo> results) {
13689            Collections.sort(results, mResolvePrioritySorter);
13690        }
13691
13692        @Override
13693        protected void dumpFilter(PrintWriter out, String prefix,
13694                PackageParser.ServiceIntentInfo filter) {
13695            out.print(prefix); out.print(
13696                    Integer.toHexString(System.identityHashCode(filter.service)));
13697                    out.print(' ');
13698                    filter.service.printComponentShortName(out);
13699                    out.print(" filter ");
13700                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13701        }
13702
13703        @Override
13704        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13705            return filter.service;
13706        }
13707
13708        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13709            PackageParser.Service service = (PackageParser.Service)label;
13710            out.print(prefix); out.print(
13711                    Integer.toHexString(System.identityHashCode(service)));
13712                    out.print(' ');
13713                    service.printComponentShortName(out);
13714            if (count > 1) {
13715                out.print(" ("); out.print(count); out.print(" filters)");
13716            }
13717            out.println();
13718        }
13719
13720//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13721//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13722//            final List<ResolveInfo> retList = Lists.newArrayList();
13723//            while (i.hasNext()) {
13724//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13725//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13726//                    retList.add(resolveInfo);
13727//                }
13728//            }
13729//            return retList;
13730//        }
13731
13732        // Keys are String (activity class name), values are Activity.
13733        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13734                = new ArrayMap<ComponentName, PackageParser.Service>();
13735        private int mFlags;
13736    }
13737
13738    private final class ProviderIntentResolver
13739            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13740        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13741                boolean defaultOnly, int userId) {
13742            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13743            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13744        }
13745
13746        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13747                int userId) {
13748            if (!sUserManager.exists(userId))
13749                return null;
13750            mFlags = flags;
13751            return super.queryIntent(intent, resolvedType,
13752                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13753                    userId);
13754        }
13755
13756        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13757                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13758            if (!sUserManager.exists(userId))
13759                return null;
13760            if (packageProviders == null) {
13761                return null;
13762            }
13763            mFlags = flags;
13764            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13765            final int N = packageProviders.size();
13766            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13767                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13768
13769            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13770            for (int i = 0; i < N; ++i) {
13771                intentFilters = packageProviders.get(i).intents;
13772                if (intentFilters != null && intentFilters.size() > 0) {
13773                    PackageParser.ProviderIntentInfo[] array =
13774                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13775                    intentFilters.toArray(array);
13776                    listCut.add(array);
13777                }
13778            }
13779            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13780        }
13781
13782        public final void addProvider(PackageParser.Provider p) {
13783            if (mProviders.containsKey(p.getComponentName())) {
13784                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13785                return;
13786            }
13787
13788            mProviders.put(p.getComponentName(), p);
13789            if (DEBUG_SHOW_INFO) {
13790                Log.v(TAG, "  "
13791                        + (p.info.nonLocalizedLabel != null
13792                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13793                Log.v(TAG, "    Class=" + p.info.name);
13794            }
13795            final int NI = p.intents.size();
13796            int j;
13797            for (j = 0; j < NI; j++) {
13798                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13799                if (DEBUG_SHOW_INFO) {
13800                    Log.v(TAG, "    IntentFilter:");
13801                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13802                }
13803                if (!intent.debugCheck()) {
13804                    Log.w(TAG, "==> For Provider " + p.info.name);
13805                }
13806                addFilter(intent);
13807            }
13808        }
13809
13810        public final void removeProvider(PackageParser.Provider p) {
13811            mProviders.remove(p.getComponentName());
13812            if (DEBUG_SHOW_INFO) {
13813                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13814                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13815                Log.v(TAG, "    Class=" + p.info.name);
13816            }
13817            final int NI = p.intents.size();
13818            int j;
13819            for (j = 0; j < NI; j++) {
13820                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13821                if (DEBUG_SHOW_INFO) {
13822                    Log.v(TAG, "    IntentFilter:");
13823                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13824                }
13825                removeFilter(intent);
13826            }
13827        }
13828
13829        @Override
13830        protected boolean allowFilterResult(
13831                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13832            ProviderInfo filterPi = filter.provider.info;
13833            for (int i = dest.size() - 1; i >= 0; i--) {
13834                ProviderInfo destPi = dest.get(i).providerInfo;
13835                if (destPi.name == filterPi.name
13836                        && destPi.packageName == filterPi.packageName) {
13837                    return false;
13838                }
13839            }
13840            return true;
13841        }
13842
13843        @Override
13844        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13845            return new PackageParser.ProviderIntentInfo[size];
13846        }
13847
13848        @Override
13849        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13850            if (!sUserManager.exists(userId))
13851                return true;
13852            PackageParser.Package p = filter.provider.owner;
13853            if (p != null) {
13854                PackageSetting ps = (PackageSetting) p.mExtras;
13855                if (ps != null) {
13856                    // System apps are never considered stopped for purposes of
13857                    // filtering, because there may be no way for the user to
13858                    // actually re-launch them.
13859                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13860                            && ps.getStopped(userId);
13861                }
13862            }
13863            return false;
13864        }
13865
13866        @Override
13867        protected boolean isPackageForFilter(String packageName,
13868                PackageParser.ProviderIntentInfo info) {
13869            return packageName.equals(info.provider.owner.packageName);
13870        }
13871
13872        @Override
13873        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13874                int match, int userId) {
13875            if (!sUserManager.exists(userId))
13876                return null;
13877            final PackageParser.ProviderIntentInfo info = filter;
13878            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13879                return null;
13880            }
13881            final PackageParser.Provider provider = info.provider;
13882            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13883            if (ps == null) {
13884                return null;
13885            }
13886            final PackageUserState userState = ps.readUserState(userId);
13887            final boolean matchVisibleToInstantApp =
13888                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13889            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13890            // throw out filters that aren't visible to instant applications
13891            if (matchVisibleToInstantApp
13892                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13893                return null;
13894            }
13895            // throw out instant application filters if we're not explicitly requesting them
13896            if (!isInstantApp && userState.instantApp) {
13897                return null;
13898            }
13899            // throw out instant application filters if updates are available; will trigger
13900            // instant application resolution
13901            if (userState.instantApp && ps.isUpdateAvailable()) {
13902                return null;
13903            }
13904            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13905                    userState, userId);
13906            if (pi == null) {
13907                return null;
13908            }
13909            final ResolveInfo res = new ResolveInfo();
13910            res.providerInfo = pi;
13911            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13912                res.filter = filter;
13913            }
13914            res.priority = info.getPriority();
13915            res.preferredOrder = provider.owner.mPreferredOrder;
13916            res.match = match;
13917            res.isDefault = info.hasDefault;
13918            res.labelRes = info.labelRes;
13919            res.nonLocalizedLabel = info.nonLocalizedLabel;
13920            res.icon = info.icon;
13921            res.system = res.providerInfo.applicationInfo.isSystemApp();
13922            return res;
13923        }
13924
13925        @Override
13926        protected void sortResults(List<ResolveInfo> results) {
13927            Collections.sort(results, mResolvePrioritySorter);
13928        }
13929
13930        @Override
13931        protected void dumpFilter(PrintWriter out, String prefix,
13932                PackageParser.ProviderIntentInfo filter) {
13933            out.print(prefix);
13934            out.print(
13935                    Integer.toHexString(System.identityHashCode(filter.provider)));
13936            out.print(' ');
13937            filter.provider.printComponentShortName(out);
13938            out.print(" filter ");
13939            out.println(Integer.toHexString(System.identityHashCode(filter)));
13940        }
13941
13942        @Override
13943        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13944            return filter.provider;
13945        }
13946
13947        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13948            PackageParser.Provider provider = (PackageParser.Provider)label;
13949            out.print(prefix); out.print(
13950                    Integer.toHexString(System.identityHashCode(provider)));
13951                    out.print(' ');
13952                    provider.printComponentShortName(out);
13953            if (count > 1) {
13954                out.print(" ("); out.print(count); out.print(" filters)");
13955            }
13956            out.println();
13957        }
13958
13959        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13960                = new ArrayMap<ComponentName, PackageParser.Provider>();
13961        private int mFlags;
13962    }
13963
13964    static final class EphemeralIntentResolver
13965            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13966        /**
13967         * The result that has the highest defined order. Ordering applies on a
13968         * per-package basis. Mapping is from package name to Pair of order and
13969         * EphemeralResolveInfo.
13970         * <p>
13971         * NOTE: This is implemented as a field variable for convenience and efficiency.
13972         * By having a field variable, we're able to track filter ordering as soon as
13973         * a non-zero order is defined. Otherwise, multiple loops across the result set
13974         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13975         * this needs to be contained entirely within {@link #filterResults}.
13976         */
13977        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13978
13979        @Override
13980        protected AuxiliaryResolveInfo[] newArray(int size) {
13981            return new AuxiliaryResolveInfo[size];
13982        }
13983
13984        @Override
13985        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13986            return true;
13987        }
13988
13989        @Override
13990        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13991                int userId) {
13992            if (!sUserManager.exists(userId)) {
13993                return null;
13994            }
13995            final String packageName = responseObj.resolveInfo.getPackageName();
13996            final Integer order = responseObj.getOrder();
13997            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13998                    mOrderResult.get(packageName);
13999            // ordering is enabled and this item's order isn't high enough
14000            if (lastOrderResult != null && lastOrderResult.first >= order) {
14001                return null;
14002            }
14003            final InstantAppResolveInfo res = responseObj.resolveInfo;
14004            if (order > 0) {
14005                // non-zero order, enable ordering
14006                mOrderResult.put(packageName, new Pair<>(order, res));
14007            }
14008            return responseObj;
14009        }
14010
14011        @Override
14012        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14013            // only do work if ordering is enabled [most of the time it won't be]
14014            if (mOrderResult.size() == 0) {
14015                return;
14016            }
14017            int resultSize = results.size();
14018            for (int i = 0; i < resultSize; i++) {
14019                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14020                final String packageName = info.getPackageName();
14021                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14022                if (savedInfo == null) {
14023                    // package doesn't having ordering
14024                    continue;
14025                }
14026                if (savedInfo.second == info) {
14027                    // circled back to the highest ordered item; remove from order list
14028                    mOrderResult.remove(savedInfo);
14029                    if (mOrderResult.size() == 0) {
14030                        // no more ordered items
14031                        break;
14032                    }
14033                    continue;
14034                }
14035                // item has a worse order, remove it from the result list
14036                results.remove(i);
14037                resultSize--;
14038                i--;
14039            }
14040        }
14041    }
14042
14043    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14044            new Comparator<ResolveInfo>() {
14045        public int compare(ResolveInfo r1, ResolveInfo r2) {
14046            int v1 = r1.priority;
14047            int v2 = r2.priority;
14048            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14049            if (v1 != v2) {
14050                return (v1 > v2) ? -1 : 1;
14051            }
14052            v1 = r1.preferredOrder;
14053            v2 = r2.preferredOrder;
14054            if (v1 != v2) {
14055                return (v1 > v2) ? -1 : 1;
14056            }
14057            if (r1.isDefault != r2.isDefault) {
14058                return r1.isDefault ? -1 : 1;
14059            }
14060            v1 = r1.match;
14061            v2 = r2.match;
14062            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14063            if (v1 != v2) {
14064                return (v1 > v2) ? -1 : 1;
14065            }
14066            if (r1.system != r2.system) {
14067                return r1.system ? -1 : 1;
14068            }
14069            if (r1.activityInfo != null) {
14070                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14071            }
14072            if (r1.serviceInfo != null) {
14073                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14074            }
14075            if (r1.providerInfo != null) {
14076                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14077            }
14078            return 0;
14079        }
14080    };
14081
14082    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14083            new Comparator<ProviderInfo>() {
14084        public int compare(ProviderInfo p1, ProviderInfo p2) {
14085            final int v1 = p1.initOrder;
14086            final int v2 = p2.initOrder;
14087            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14088        }
14089    };
14090
14091    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14092            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14093            final int[] userIds) {
14094        mHandler.post(new Runnable() {
14095            @Override
14096            public void run() {
14097                try {
14098                    final IActivityManager am = ActivityManager.getService();
14099                    if (am == null) return;
14100                    final int[] resolvedUserIds;
14101                    if (userIds == null) {
14102                        resolvedUserIds = am.getRunningUserIds();
14103                    } else {
14104                        resolvedUserIds = userIds;
14105                    }
14106                    for (int id : resolvedUserIds) {
14107                        final Intent intent = new Intent(action,
14108                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14109                        if (extras != null) {
14110                            intent.putExtras(extras);
14111                        }
14112                        if (targetPkg != null) {
14113                            intent.setPackage(targetPkg);
14114                        }
14115                        // Modify the UID when posting to other users
14116                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14117                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14118                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14119                            intent.putExtra(Intent.EXTRA_UID, uid);
14120                        }
14121                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14122                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14123                        if (DEBUG_BROADCASTS) {
14124                            RuntimeException here = new RuntimeException("here");
14125                            here.fillInStackTrace();
14126                            Slog.d(TAG, "Sending to user " + id + ": "
14127                                    + intent.toShortString(false, true, false, false)
14128                                    + " " + intent.getExtras(), here);
14129                        }
14130                        am.broadcastIntent(null, intent, null, finishedReceiver,
14131                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14132                                null, finishedReceiver != null, false, id);
14133                    }
14134                } catch (RemoteException ex) {
14135                }
14136            }
14137        });
14138    }
14139
14140    /**
14141     * Check if the external storage media is available. This is true if there
14142     * is a mounted external storage medium or if the external storage is
14143     * emulated.
14144     */
14145    private boolean isExternalMediaAvailable() {
14146        return mMediaMounted || Environment.isExternalStorageEmulated();
14147    }
14148
14149    @Override
14150    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14151        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14152            return null;
14153        }
14154        // writer
14155        synchronized (mPackages) {
14156            if (!isExternalMediaAvailable()) {
14157                // If the external storage is no longer mounted at this point,
14158                // the caller may not have been able to delete all of this
14159                // packages files and can not delete any more.  Bail.
14160                return null;
14161            }
14162            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14163            if (lastPackage != null) {
14164                pkgs.remove(lastPackage);
14165            }
14166            if (pkgs.size() > 0) {
14167                return pkgs.get(0);
14168            }
14169        }
14170        return null;
14171    }
14172
14173    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14174        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14175                userId, andCode ? 1 : 0, packageName);
14176        if (mSystemReady) {
14177            msg.sendToTarget();
14178        } else {
14179            if (mPostSystemReadyMessages == null) {
14180                mPostSystemReadyMessages = new ArrayList<>();
14181            }
14182            mPostSystemReadyMessages.add(msg);
14183        }
14184    }
14185
14186    void startCleaningPackages() {
14187        // reader
14188        if (!isExternalMediaAvailable()) {
14189            return;
14190        }
14191        synchronized (mPackages) {
14192            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14193                return;
14194            }
14195        }
14196        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14197        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14198        IActivityManager am = ActivityManager.getService();
14199        if (am != null) {
14200            int dcsUid = -1;
14201            synchronized (mPackages) {
14202                if (!mDefaultContainerWhitelisted) {
14203                    mDefaultContainerWhitelisted = true;
14204                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14205                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14206                }
14207            }
14208            try {
14209                if (dcsUid > 0) {
14210                    am.backgroundWhitelistUid(dcsUid);
14211                }
14212                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14213                        UserHandle.USER_SYSTEM);
14214            } catch (RemoteException e) {
14215            }
14216        }
14217    }
14218
14219    @Override
14220    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14221            int installFlags, String installerPackageName, int userId) {
14222        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14223
14224        final int callingUid = Binder.getCallingUid();
14225        enforceCrossUserPermission(callingUid, userId,
14226                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14227
14228        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14229            try {
14230                if (observer != null) {
14231                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14232                }
14233            } catch (RemoteException re) {
14234            }
14235            return;
14236        }
14237
14238        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14239            installFlags |= PackageManager.INSTALL_FROM_ADB;
14240
14241        } else {
14242            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14243            // about installerPackageName.
14244
14245            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14246            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14247        }
14248
14249        UserHandle user;
14250        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14251            user = UserHandle.ALL;
14252        } else {
14253            user = new UserHandle(userId);
14254        }
14255
14256        // Only system components can circumvent runtime permissions when installing.
14257        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14258                && mContext.checkCallingOrSelfPermission(Manifest.permission
14259                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14260            throw new SecurityException("You need the "
14261                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14262                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14263        }
14264
14265        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14266                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14267            throw new IllegalArgumentException(
14268                    "New installs into ASEC containers no longer supported");
14269        }
14270
14271        final File originFile = new File(originPath);
14272        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14273
14274        final Message msg = mHandler.obtainMessage(INIT_COPY);
14275        final VerificationInfo verificationInfo = new VerificationInfo(
14276                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14277        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14278                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14279                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14280                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14281        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14282        msg.obj = params;
14283
14284        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14285                System.identityHashCode(msg.obj));
14286        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14287                System.identityHashCode(msg.obj));
14288
14289        mHandler.sendMessage(msg);
14290    }
14291
14292
14293    /**
14294     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14295     * it is acting on behalf on an enterprise or the user).
14296     *
14297     * Note that the ordering of the conditionals in this method is important. The checks we perform
14298     * are as follows, in this order:
14299     *
14300     * 1) If the install is being performed by a system app, we can trust the app to have set the
14301     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14302     *    what it is.
14303     * 2) If the install is being performed by a device or profile owner app, the install reason
14304     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14305     *    set the install reason correctly. If the app targets an older SDK version where install
14306     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14307     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14308     * 3) In all other cases, the install is being performed by a regular app that is neither part
14309     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14310     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14311     *    set to enterprise policy and if so, change it to unknown instead.
14312     */
14313    private int fixUpInstallReason(String installerPackageName, int installerUid,
14314            int installReason) {
14315        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14316                == PERMISSION_GRANTED) {
14317            // If the install is being performed by a system app, we trust that app to have set the
14318            // install reason correctly.
14319            return installReason;
14320        }
14321
14322        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14323            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14324        if (dpm != null) {
14325            ComponentName owner = null;
14326            try {
14327                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14328                if (owner == null) {
14329                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14330                }
14331            } catch (RemoteException e) {
14332            }
14333            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14334                // If the install is being performed by a device or profile owner, the install
14335                // reason should be enterprise policy.
14336                return PackageManager.INSTALL_REASON_POLICY;
14337            }
14338        }
14339
14340        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14341            // If the install is being performed by a regular app (i.e. neither system app nor
14342            // device or profile owner), we have no reason to believe that the app is acting on
14343            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14344            // change it to unknown instead.
14345            return PackageManager.INSTALL_REASON_UNKNOWN;
14346        }
14347
14348        // If the install is being performed by a regular app and the install reason was set to any
14349        // value but enterprise policy, leave the install reason unchanged.
14350        return installReason;
14351    }
14352
14353    void installStage(String packageName, File stagedDir, String stagedCid,
14354            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14355            String installerPackageName, int installerUid, UserHandle user,
14356            Certificate[][] certificates) {
14357        if (DEBUG_EPHEMERAL) {
14358            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14359                Slog.d(TAG, "Ephemeral install of " + packageName);
14360            }
14361        }
14362        final VerificationInfo verificationInfo = new VerificationInfo(
14363                sessionParams.originatingUri, sessionParams.referrerUri,
14364                sessionParams.originatingUid, installerUid);
14365
14366        final OriginInfo origin;
14367        if (stagedDir != null) {
14368            origin = OriginInfo.fromStagedFile(stagedDir);
14369        } else {
14370            origin = OriginInfo.fromStagedContainer(stagedCid);
14371        }
14372
14373        final Message msg = mHandler.obtainMessage(INIT_COPY);
14374        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14375                sessionParams.installReason);
14376        final InstallParams params = new InstallParams(origin, null, observer,
14377                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14378                verificationInfo, user, sessionParams.abiOverride,
14379                sessionParams.grantedRuntimePermissions, certificates, installReason);
14380        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14381        msg.obj = params;
14382
14383        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14384                System.identityHashCode(msg.obj));
14385        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14386                System.identityHashCode(msg.obj));
14387
14388        mHandler.sendMessage(msg);
14389    }
14390
14391    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14392            int userId) {
14393        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14394        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14395
14396        // Send a session commit broadcast
14397        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14398        info.installReason = pkgSetting.getInstallReason(userId);
14399        info.appPackageName = packageName;
14400        sendSessionCommitBroadcast(info, userId);
14401    }
14402
14403    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14404        if (ArrayUtils.isEmpty(userIds)) {
14405            return;
14406        }
14407        Bundle extras = new Bundle(1);
14408        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14409        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14410
14411        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14412                packageName, extras, 0, null, null, userIds);
14413        if (isSystem) {
14414            mHandler.post(() -> {
14415                        for (int userId : userIds) {
14416                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14417                        }
14418                    }
14419            );
14420        }
14421    }
14422
14423    /**
14424     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14425     * automatically without needing an explicit launch.
14426     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14427     */
14428    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14429        // If user is not running, the app didn't miss any broadcast
14430        if (!mUserManagerInternal.isUserRunning(userId)) {
14431            return;
14432        }
14433        final IActivityManager am = ActivityManager.getService();
14434        try {
14435            // Deliver LOCKED_BOOT_COMPLETED first
14436            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14437                    .setPackage(packageName);
14438            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14439            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14440                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14441
14442            // Deliver BOOT_COMPLETED only if user is unlocked
14443            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14444                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14445                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14446                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14447            }
14448        } catch (RemoteException e) {
14449            throw e.rethrowFromSystemServer();
14450        }
14451    }
14452
14453    @Override
14454    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14455            int userId) {
14456        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14457        PackageSetting pkgSetting;
14458        final int callingUid = Binder.getCallingUid();
14459        enforceCrossUserPermission(callingUid, userId,
14460                true /* requireFullPermission */, true /* checkShell */,
14461                "setApplicationHiddenSetting for user " + userId);
14462
14463        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14464            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14465            return false;
14466        }
14467
14468        long callingId = Binder.clearCallingIdentity();
14469        try {
14470            boolean sendAdded = false;
14471            boolean sendRemoved = false;
14472            // writer
14473            synchronized (mPackages) {
14474                pkgSetting = mSettings.mPackages.get(packageName);
14475                if (pkgSetting == null) {
14476                    return false;
14477                }
14478                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14479                    return false;
14480                }
14481                // Do not allow "android" is being disabled
14482                if ("android".equals(packageName)) {
14483                    Slog.w(TAG, "Cannot hide package: android");
14484                    return false;
14485                }
14486                // Cannot hide static shared libs as they are considered
14487                // a part of the using app (emulating static linking). Also
14488                // static libs are installed always on internal storage.
14489                PackageParser.Package pkg = mPackages.get(packageName);
14490                if (pkg != null && pkg.staticSharedLibName != null) {
14491                    Slog.w(TAG, "Cannot hide package: " + packageName
14492                            + " providing static shared library: "
14493                            + pkg.staticSharedLibName);
14494                    return false;
14495                }
14496                // Only allow protected packages to hide themselves.
14497                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14498                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14499                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14500                    return false;
14501                }
14502
14503                if (pkgSetting.getHidden(userId) != hidden) {
14504                    pkgSetting.setHidden(hidden, userId);
14505                    mSettings.writePackageRestrictionsLPr(userId);
14506                    if (hidden) {
14507                        sendRemoved = true;
14508                    } else {
14509                        sendAdded = true;
14510                    }
14511                }
14512            }
14513            if (sendAdded) {
14514                sendPackageAddedForUser(packageName, pkgSetting, userId);
14515                return true;
14516            }
14517            if (sendRemoved) {
14518                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14519                        "hiding pkg");
14520                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14521                return true;
14522            }
14523        } finally {
14524            Binder.restoreCallingIdentity(callingId);
14525        }
14526        return false;
14527    }
14528
14529    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14530            int userId) {
14531        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14532        info.removedPackage = packageName;
14533        info.installerPackageName = pkgSetting.installerPackageName;
14534        info.removedUsers = new int[] {userId};
14535        info.broadcastUsers = new int[] {userId};
14536        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14537        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14538    }
14539
14540    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14541        if (pkgList.length > 0) {
14542            Bundle extras = new Bundle(1);
14543            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14544
14545            sendPackageBroadcast(
14546                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14547                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14548                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14549                    new int[] {userId});
14550        }
14551    }
14552
14553    /**
14554     * Returns true if application is not found or there was an error. Otherwise it returns
14555     * the hidden state of the package for the given user.
14556     */
14557    @Override
14558    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14559        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14560        final int callingUid = Binder.getCallingUid();
14561        enforceCrossUserPermission(callingUid, userId,
14562                true /* requireFullPermission */, false /* checkShell */,
14563                "getApplicationHidden for user " + userId);
14564        PackageSetting ps;
14565        long callingId = Binder.clearCallingIdentity();
14566        try {
14567            // writer
14568            synchronized (mPackages) {
14569                ps = mSettings.mPackages.get(packageName);
14570                if (ps == null) {
14571                    return true;
14572                }
14573                if (filterAppAccessLPr(ps, callingUid, userId)) {
14574                    return true;
14575                }
14576                return ps.getHidden(userId);
14577            }
14578        } finally {
14579            Binder.restoreCallingIdentity(callingId);
14580        }
14581    }
14582
14583    /**
14584     * @hide
14585     */
14586    @Override
14587    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14588            int installReason) {
14589        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14590                null);
14591        PackageSetting pkgSetting;
14592        final int callingUid = Binder.getCallingUid();
14593        enforceCrossUserPermission(callingUid, userId,
14594                true /* requireFullPermission */, true /* checkShell */,
14595                "installExistingPackage for user " + userId);
14596        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14597            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14598        }
14599
14600        long callingId = Binder.clearCallingIdentity();
14601        try {
14602            boolean installed = false;
14603            final boolean instantApp =
14604                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14605            final boolean fullApp =
14606                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14607
14608            // writer
14609            synchronized (mPackages) {
14610                pkgSetting = mSettings.mPackages.get(packageName);
14611                if (pkgSetting == null) {
14612                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14613                }
14614                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14615                    // only allow the existing package to be used if it's installed as a full
14616                    // application for at least one user
14617                    boolean installAllowed = false;
14618                    for (int checkUserId : sUserManager.getUserIds()) {
14619                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14620                        if (installAllowed) {
14621                            break;
14622                        }
14623                    }
14624                    if (!installAllowed) {
14625                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14626                    }
14627                }
14628                if (!pkgSetting.getInstalled(userId)) {
14629                    pkgSetting.setInstalled(true, userId);
14630                    pkgSetting.setHidden(false, userId);
14631                    pkgSetting.setInstallReason(installReason, userId);
14632                    mSettings.writePackageRestrictionsLPr(userId);
14633                    mSettings.writeKernelMappingLPr(pkgSetting);
14634                    installed = true;
14635                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14636                    // upgrade app from instant to full; we don't allow app downgrade
14637                    installed = true;
14638                }
14639                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14640            }
14641
14642            if (installed) {
14643                if (pkgSetting.pkg != null) {
14644                    synchronized (mInstallLock) {
14645                        // We don't need to freeze for a brand new install
14646                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14647                    }
14648                }
14649                sendPackageAddedForUser(packageName, pkgSetting, userId);
14650                synchronized (mPackages) {
14651                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14652                }
14653            }
14654        } finally {
14655            Binder.restoreCallingIdentity(callingId);
14656        }
14657
14658        return PackageManager.INSTALL_SUCCEEDED;
14659    }
14660
14661    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14662            boolean instantApp, boolean fullApp) {
14663        // no state specified; do nothing
14664        if (!instantApp && !fullApp) {
14665            return;
14666        }
14667        if (userId != UserHandle.USER_ALL) {
14668            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14669                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14670            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14671                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14672            }
14673        } else {
14674            for (int currentUserId : sUserManager.getUserIds()) {
14675                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14676                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14677                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14678                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14679                }
14680            }
14681        }
14682    }
14683
14684    boolean isUserRestricted(int userId, String restrictionKey) {
14685        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14686        if (restrictions.getBoolean(restrictionKey, false)) {
14687            Log.w(TAG, "User is restricted: " + restrictionKey);
14688            return true;
14689        }
14690        return false;
14691    }
14692
14693    @Override
14694    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14695            int userId) {
14696        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14697        final int callingUid = Binder.getCallingUid();
14698        enforceCrossUserPermission(callingUid, userId,
14699                true /* requireFullPermission */, true /* checkShell */,
14700                "setPackagesSuspended for user " + userId);
14701
14702        if (ArrayUtils.isEmpty(packageNames)) {
14703            return packageNames;
14704        }
14705
14706        // List of package names for whom the suspended state has changed.
14707        List<String> changedPackages = new ArrayList<>(packageNames.length);
14708        // List of package names for whom the suspended state is not set as requested in this
14709        // method.
14710        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14711        long callingId = Binder.clearCallingIdentity();
14712        try {
14713            for (int i = 0; i < packageNames.length; i++) {
14714                String packageName = packageNames[i];
14715                boolean changed = false;
14716                final int appId;
14717                synchronized (mPackages) {
14718                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14719                    if (pkgSetting == null
14720                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14721                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14722                                + "\". Skipping suspending/un-suspending.");
14723                        unactionedPackages.add(packageName);
14724                        continue;
14725                    }
14726                    appId = pkgSetting.appId;
14727                    if (pkgSetting.getSuspended(userId) != suspended) {
14728                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14729                            unactionedPackages.add(packageName);
14730                            continue;
14731                        }
14732                        pkgSetting.setSuspended(suspended, userId);
14733                        mSettings.writePackageRestrictionsLPr(userId);
14734                        changed = true;
14735                        changedPackages.add(packageName);
14736                    }
14737                }
14738
14739                if (changed && suspended) {
14740                    killApplication(packageName, UserHandle.getUid(userId, appId),
14741                            "suspending package");
14742                }
14743            }
14744        } finally {
14745            Binder.restoreCallingIdentity(callingId);
14746        }
14747
14748        if (!changedPackages.isEmpty()) {
14749            sendPackagesSuspendedForUser(changedPackages.toArray(
14750                    new String[changedPackages.size()]), userId, suspended);
14751        }
14752
14753        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14754    }
14755
14756    @Override
14757    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14758        final int callingUid = Binder.getCallingUid();
14759        enforceCrossUserPermission(callingUid, userId,
14760                true /* requireFullPermission */, false /* checkShell */,
14761                "isPackageSuspendedForUser for user " + userId);
14762        synchronized (mPackages) {
14763            final PackageSetting ps = mSettings.mPackages.get(packageName);
14764            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14765                throw new IllegalArgumentException("Unknown target package: " + packageName);
14766            }
14767            return ps.getSuspended(userId);
14768        }
14769    }
14770
14771    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14772        if (isPackageDeviceAdmin(packageName, userId)) {
14773            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14774                    + "\": has an active device admin");
14775            return false;
14776        }
14777
14778        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14779        if (packageName.equals(activeLauncherPackageName)) {
14780            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14781                    + "\": contains the active launcher");
14782            return false;
14783        }
14784
14785        if (packageName.equals(mRequiredInstallerPackage)) {
14786            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14787                    + "\": required for package installation");
14788            return false;
14789        }
14790
14791        if (packageName.equals(mRequiredUninstallerPackage)) {
14792            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14793                    + "\": required for package uninstallation");
14794            return false;
14795        }
14796
14797        if (packageName.equals(mRequiredVerifierPackage)) {
14798            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14799                    + "\": required for package verification");
14800            return false;
14801        }
14802
14803        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14804            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14805                    + "\": is the default dialer");
14806            return false;
14807        }
14808
14809        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14810            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14811                    + "\": protected package");
14812            return false;
14813        }
14814
14815        // Cannot suspend static shared libs as they are considered
14816        // a part of the using app (emulating static linking). Also
14817        // static libs are installed always on internal storage.
14818        PackageParser.Package pkg = mPackages.get(packageName);
14819        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14820            Slog.w(TAG, "Cannot suspend package: " + packageName
14821                    + " providing static shared library: "
14822                    + pkg.staticSharedLibName);
14823            return false;
14824        }
14825
14826        return true;
14827    }
14828
14829    private String getActiveLauncherPackageName(int userId) {
14830        Intent intent = new Intent(Intent.ACTION_MAIN);
14831        intent.addCategory(Intent.CATEGORY_HOME);
14832        ResolveInfo resolveInfo = resolveIntent(
14833                intent,
14834                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14835                PackageManager.MATCH_DEFAULT_ONLY,
14836                userId);
14837
14838        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14839    }
14840
14841    private String getDefaultDialerPackageName(int userId) {
14842        synchronized (mPackages) {
14843            return mSettings.getDefaultDialerPackageNameLPw(userId);
14844        }
14845    }
14846
14847    @Override
14848    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14849        mContext.enforceCallingOrSelfPermission(
14850                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14851                "Only package verification agents can verify applications");
14852
14853        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14854        final PackageVerificationResponse response = new PackageVerificationResponse(
14855                verificationCode, Binder.getCallingUid());
14856        msg.arg1 = id;
14857        msg.obj = response;
14858        mHandler.sendMessage(msg);
14859    }
14860
14861    @Override
14862    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14863            long millisecondsToDelay) {
14864        mContext.enforceCallingOrSelfPermission(
14865                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14866                "Only package verification agents can extend verification timeouts");
14867
14868        final PackageVerificationState state = mPendingVerification.get(id);
14869        final PackageVerificationResponse response = new PackageVerificationResponse(
14870                verificationCodeAtTimeout, Binder.getCallingUid());
14871
14872        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14873            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14874        }
14875        if (millisecondsToDelay < 0) {
14876            millisecondsToDelay = 0;
14877        }
14878        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14879                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14880            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14881        }
14882
14883        if ((state != null) && !state.timeoutExtended()) {
14884            state.extendTimeout();
14885
14886            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14887            msg.arg1 = id;
14888            msg.obj = response;
14889            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14890        }
14891    }
14892
14893    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14894            int verificationCode, UserHandle user) {
14895        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14896        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14897        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14898        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14899        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14900
14901        mContext.sendBroadcastAsUser(intent, user,
14902                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14903    }
14904
14905    private ComponentName matchComponentForVerifier(String packageName,
14906            List<ResolveInfo> receivers) {
14907        ActivityInfo targetReceiver = null;
14908
14909        final int NR = receivers.size();
14910        for (int i = 0; i < NR; i++) {
14911            final ResolveInfo info = receivers.get(i);
14912            if (info.activityInfo == null) {
14913                continue;
14914            }
14915
14916            if (packageName.equals(info.activityInfo.packageName)) {
14917                targetReceiver = info.activityInfo;
14918                break;
14919            }
14920        }
14921
14922        if (targetReceiver == null) {
14923            return null;
14924        }
14925
14926        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14927    }
14928
14929    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14930            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14931        if (pkgInfo.verifiers.length == 0) {
14932            return null;
14933        }
14934
14935        final int N = pkgInfo.verifiers.length;
14936        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14937        for (int i = 0; i < N; i++) {
14938            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14939
14940            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14941                    receivers);
14942            if (comp == null) {
14943                continue;
14944            }
14945
14946            final int verifierUid = getUidForVerifier(verifierInfo);
14947            if (verifierUid == -1) {
14948                continue;
14949            }
14950
14951            if (DEBUG_VERIFY) {
14952                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14953                        + " with the correct signature");
14954            }
14955            sufficientVerifiers.add(comp);
14956            verificationState.addSufficientVerifier(verifierUid);
14957        }
14958
14959        return sufficientVerifiers;
14960    }
14961
14962    private int getUidForVerifier(VerifierInfo verifierInfo) {
14963        synchronized (mPackages) {
14964            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14965            if (pkg == null) {
14966                return -1;
14967            } else if (pkg.mSignatures.length != 1) {
14968                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14969                        + " has more than one signature; ignoring");
14970                return -1;
14971            }
14972
14973            /*
14974             * If the public key of the package's signature does not match
14975             * our expected public key, then this is a different package and
14976             * we should skip.
14977             */
14978
14979            final byte[] expectedPublicKey;
14980            try {
14981                final Signature verifierSig = pkg.mSignatures[0];
14982                final PublicKey publicKey = verifierSig.getPublicKey();
14983                expectedPublicKey = publicKey.getEncoded();
14984            } catch (CertificateException e) {
14985                return -1;
14986            }
14987
14988            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14989
14990            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14991                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14992                        + " does not have the expected public key; ignoring");
14993                return -1;
14994            }
14995
14996            return pkg.applicationInfo.uid;
14997        }
14998    }
14999
15000    @Override
15001    public void finishPackageInstall(int token, boolean didLaunch) {
15002        enforceSystemOrRoot("Only the system is allowed to finish installs");
15003
15004        if (DEBUG_INSTALL) {
15005            Slog.v(TAG, "BM finishing package install for " + token);
15006        }
15007        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15008
15009        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15010        mHandler.sendMessage(msg);
15011    }
15012
15013    /**
15014     * Get the verification agent timeout.  Used for both the APK verifier and the
15015     * intent filter verifier.
15016     *
15017     * @return verification timeout in milliseconds
15018     */
15019    private long getVerificationTimeout() {
15020        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15021                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15022                DEFAULT_VERIFICATION_TIMEOUT);
15023    }
15024
15025    /**
15026     * Get the default verification agent response code.
15027     *
15028     * @return default verification response code
15029     */
15030    private int getDefaultVerificationResponse(UserHandle user) {
15031        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15032            return PackageManager.VERIFICATION_REJECT;
15033        }
15034        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15035                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15036                DEFAULT_VERIFICATION_RESPONSE);
15037    }
15038
15039    /**
15040     * Check whether or not package verification has been enabled.
15041     *
15042     * @return true if verification should be performed
15043     */
15044    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15045        if (!DEFAULT_VERIFY_ENABLE) {
15046            return false;
15047        }
15048
15049        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15050
15051        // Check if installing from ADB
15052        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15053            // Do not run verification in a test harness environment
15054            if (ActivityManager.isRunningInTestHarness()) {
15055                return false;
15056            }
15057            if (ensureVerifyAppsEnabled) {
15058                return true;
15059            }
15060            // Check if the developer does not want package verification for ADB installs
15061            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15062                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15063                return false;
15064            }
15065        } else {
15066            // only when not installed from ADB, skip verification for instant apps when
15067            // the installer and verifier are the same.
15068            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15069                if (mInstantAppInstallerActivity != null
15070                        && mInstantAppInstallerActivity.packageName.equals(
15071                                mRequiredVerifierPackage)) {
15072                    try {
15073                        mContext.getSystemService(AppOpsManager.class)
15074                                .checkPackage(installerUid, mRequiredVerifierPackage);
15075                        if (DEBUG_VERIFY) {
15076                            Slog.i(TAG, "disable verification for instant app");
15077                        }
15078                        return false;
15079                    } catch (SecurityException ignore) { }
15080                }
15081            }
15082        }
15083
15084        if (ensureVerifyAppsEnabled) {
15085            return true;
15086        }
15087
15088        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15089                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15090    }
15091
15092    @Override
15093    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15094            throws RemoteException {
15095        mContext.enforceCallingOrSelfPermission(
15096                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15097                "Only intentfilter verification agents can verify applications");
15098
15099        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15100        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15101                Binder.getCallingUid(), verificationCode, failedDomains);
15102        msg.arg1 = id;
15103        msg.obj = response;
15104        mHandler.sendMessage(msg);
15105    }
15106
15107    @Override
15108    public int getIntentVerificationStatus(String packageName, int userId) {
15109        final int callingUid = Binder.getCallingUid();
15110        if (getInstantAppPackageName(callingUid) != null) {
15111            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15112        }
15113        synchronized (mPackages) {
15114            final PackageSetting ps = mSettings.mPackages.get(packageName);
15115            if (ps == null
15116                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15117                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15118            }
15119            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15120        }
15121    }
15122
15123    @Override
15124    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15125        mContext.enforceCallingOrSelfPermission(
15126                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15127
15128        boolean result = false;
15129        synchronized (mPackages) {
15130            final PackageSetting ps = mSettings.mPackages.get(packageName);
15131            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15132                return false;
15133            }
15134            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15135        }
15136        if (result) {
15137            scheduleWritePackageRestrictionsLocked(userId);
15138        }
15139        return result;
15140    }
15141
15142    @Override
15143    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15144            String packageName) {
15145        final int callingUid = Binder.getCallingUid();
15146        if (getInstantAppPackageName(callingUid) != null) {
15147            return ParceledListSlice.emptyList();
15148        }
15149        synchronized (mPackages) {
15150            final PackageSetting ps = mSettings.mPackages.get(packageName);
15151            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15152                return ParceledListSlice.emptyList();
15153            }
15154            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15155        }
15156    }
15157
15158    @Override
15159    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15160        if (TextUtils.isEmpty(packageName)) {
15161            return ParceledListSlice.emptyList();
15162        }
15163        final int callingUid = Binder.getCallingUid();
15164        final int callingUserId = UserHandle.getUserId(callingUid);
15165        synchronized (mPackages) {
15166            PackageParser.Package pkg = mPackages.get(packageName);
15167            if (pkg == null || pkg.activities == null) {
15168                return ParceledListSlice.emptyList();
15169            }
15170            if (pkg.mExtras == null) {
15171                return ParceledListSlice.emptyList();
15172            }
15173            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15174            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15175                return ParceledListSlice.emptyList();
15176            }
15177            final int count = pkg.activities.size();
15178            ArrayList<IntentFilter> result = new ArrayList<>();
15179            for (int n=0; n<count; n++) {
15180                PackageParser.Activity activity = pkg.activities.get(n);
15181                if (activity.intents != null && activity.intents.size() > 0) {
15182                    result.addAll(activity.intents);
15183                }
15184            }
15185            return new ParceledListSlice<>(result);
15186        }
15187    }
15188
15189    @Override
15190    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15191        mContext.enforceCallingOrSelfPermission(
15192                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15193
15194        synchronized (mPackages) {
15195            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15196            if (packageName != null) {
15197                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15198                        packageName, userId);
15199            }
15200            return result;
15201        }
15202    }
15203
15204    @Override
15205    public String getDefaultBrowserPackageName(int userId) {
15206        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15207            return null;
15208        }
15209        synchronized (mPackages) {
15210            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15211        }
15212    }
15213
15214    /**
15215     * Get the "allow unknown sources" setting.
15216     *
15217     * @return the current "allow unknown sources" setting
15218     */
15219    private int getUnknownSourcesSettings() {
15220        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15221                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15222                -1);
15223    }
15224
15225    @Override
15226    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15227        final int callingUid = Binder.getCallingUid();
15228        if (getInstantAppPackageName(callingUid) != null) {
15229            return;
15230        }
15231        // writer
15232        synchronized (mPackages) {
15233            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15234            if (targetPackageSetting == null
15235                    || filterAppAccessLPr(
15236                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15237                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15238            }
15239
15240            PackageSetting installerPackageSetting;
15241            if (installerPackageName != null) {
15242                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15243                if (installerPackageSetting == null) {
15244                    throw new IllegalArgumentException("Unknown installer package: "
15245                            + installerPackageName);
15246                }
15247            } else {
15248                installerPackageSetting = null;
15249            }
15250
15251            Signature[] callerSignature;
15252            Object obj = mSettings.getUserIdLPr(callingUid);
15253            if (obj != null) {
15254                if (obj instanceof SharedUserSetting) {
15255                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15256                } else if (obj instanceof PackageSetting) {
15257                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15258                } else {
15259                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15260                }
15261            } else {
15262                throw new SecurityException("Unknown calling UID: " + callingUid);
15263            }
15264
15265            // Verify: can't set installerPackageName to a package that is
15266            // not signed with the same cert as the caller.
15267            if (installerPackageSetting != null) {
15268                if (compareSignatures(callerSignature,
15269                        installerPackageSetting.signatures.mSignatures)
15270                        != PackageManager.SIGNATURE_MATCH) {
15271                    throw new SecurityException(
15272                            "Caller does not have same cert as new installer package "
15273                            + installerPackageName);
15274                }
15275            }
15276
15277            // Verify: if target already has an installer package, it must
15278            // be signed with the same cert as the caller.
15279            if (targetPackageSetting.installerPackageName != null) {
15280                PackageSetting setting = mSettings.mPackages.get(
15281                        targetPackageSetting.installerPackageName);
15282                // If the currently set package isn't valid, then it's always
15283                // okay to change it.
15284                if (setting != null) {
15285                    if (compareSignatures(callerSignature,
15286                            setting.signatures.mSignatures)
15287                            != PackageManager.SIGNATURE_MATCH) {
15288                        throw new SecurityException(
15289                                "Caller does not have same cert as old installer package "
15290                                + targetPackageSetting.installerPackageName);
15291                    }
15292                }
15293            }
15294
15295            // Okay!
15296            targetPackageSetting.installerPackageName = installerPackageName;
15297            if (installerPackageName != null) {
15298                mSettings.mInstallerPackages.add(installerPackageName);
15299            }
15300            scheduleWriteSettingsLocked();
15301        }
15302    }
15303
15304    @Override
15305    public void setApplicationCategoryHint(String packageName, int categoryHint,
15306            String callerPackageName) {
15307        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15308            throw new SecurityException("Instant applications don't have access to this method");
15309        }
15310        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15311                callerPackageName);
15312        synchronized (mPackages) {
15313            PackageSetting ps = mSettings.mPackages.get(packageName);
15314            if (ps == null) {
15315                throw new IllegalArgumentException("Unknown target package " + packageName);
15316            }
15317            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15318                throw new IllegalArgumentException("Unknown target package " + packageName);
15319            }
15320            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15321                throw new IllegalArgumentException("Calling package " + callerPackageName
15322                        + " is not installer for " + packageName);
15323            }
15324
15325            if (ps.categoryHint != categoryHint) {
15326                ps.categoryHint = categoryHint;
15327                scheduleWriteSettingsLocked();
15328            }
15329        }
15330    }
15331
15332    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15333        // Queue up an async operation since the package installation may take a little while.
15334        mHandler.post(new Runnable() {
15335            public void run() {
15336                mHandler.removeCallbacks(this);
15337                 // Result object to be returned
15338                PackageInstalledInfo res = new PackageInstalledInfo();
15339                res.setReturnCode(currentStatus);
15340                res.uid = -1;
15341                res.pkg = null;
15342                res.removedInfo = null;
15343                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15344                    args.doPreInstall(res.returnCode);
15345                    synchronized (mInstallLock) {
15346                        installPackageTracedLI(args, res);
15347                    }
15348                    args.doPostInstall(res.returnCode, res.uid);
15349                }
15350
15351                // A restore should be performed at this point if (a) the install
15352                // succeeded, (b) the operation is not an update, and (c) the new
15353                // package has not opted out of backup participation.
15354                final boolean update = res.removedInfo != null
15355                        && res.removedInfo.removedPackage != null;
15356                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15357                boolean doRestore = !update
15358                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15359
15360                // Set up the post-install work request bookkeeping.  This will be used
15361                // and cleaned up by the post-install event handling regardless of whether
15362                // there's a restore pass performed.  Token values are >= 1.
15363                int token;
15364                if (mNextInstallToken < 0) mNextInstallToken = 1;
15365                token = mNextInstallToken++;
15366
15367                PostInstallData data = new PostInstallData(args, res);
15368                mRunningInstalls.put(token, data);
15369                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15370
15371                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15372                    // Pass responsibility to the Backup Manager.  It will perform a
15373                    // restore if appropriate, then pass responsibility back to the
15374                    // Package Manager to run the post-install observer callbacks
15375                    // and broadcasts.
15376                    IBackupManager bm = IBackupManager.Stub.asInterface(
15377                            ServiceManager.getService(Context.BACKUP_SERVICE));
15378                    if (bm != null) {
15379                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15380                                + " to BM for possible restore");
15381                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15382                        try {
15383                            // TODO: http://b/22388012
15384                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15385                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15386                            } else {
15387                                doRestore = false;
15388                            }
15389                        } catch (RemoteException e) {
15390                            // can't happen; the backup manager is local
15391                        } catch (Exception e) {
15392                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15393                            doRestore = false;
15394                        }
15395                    } else {
15396                        Slog.e(TAG, "Backup Manager not found!");
15397                        doRestore = false;
15398                    }
15399                }
15400
15401                if (!doRestore) {
15402                    // No restore possible, or the Backup Manager was mysteriously not
15403                    // available -- just fire the post-install work request directly.
15404                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15405
15406                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15407
15408                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15409                    mHandler.sendMessage(msg);
15410                }
15411            }
15412        });
15413    }
15414
15415    /**
15416     * Callback from PackageSettings whenever an app is first transitioned out of the
15417     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15418     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15419     * here whether the app is the target of an ongoing install, and only send the
15420     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15421     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15422     * handling.
15423     */
15424    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15425        // Serialize this with the rest of the install-process message chain.  In the
15426        // restore-at-install case, this Runnable will necessarily run before the
15427        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15428        // are coherent.  In the non-restore case, the app has already completed install
15429        // and been launched through some other means, so it is not in a problematic
15430        // state for observers to see the FIRST_LAUNCH signal.
15431        mHandler.post(new Runnable() {
15432            @Override
15433            public void run() {
15434                for (int i = 0; i < mRunningInstalls.size(); i++) {
15435                    final PostInstallData data = mRunningInstalls.valueAt(i);
15436                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15437                        continue;
15438                    }
15439                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15440                        // right package; but is it for the right user?
15441                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15442                            if (userId == data.res.newUsers[uIndex]) {
15443                                if (DEBUG_BACKUP) {
15444                                    Slog.i(TAG, "Package " + pkgName
15445                                            + " being restored so deferring FIRST_LAUNCH");
15446                                }
15447                                return;
15448                            }
15449                        }
15450                    }
15451                }
15452                // didn't find it, so not being restored
15453                if (DEBUG_BACKUP) {
15454                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15455                }
15456                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15457            }
15458        });
15459    }
15460
15461    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15462        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15463                installerPkg, null, userIds);
15464    }
15465
15466    private abstract class HandlerParams {
15467        private static final int MAX_RETRIES = 4;
15468
15469        /**
15470         * Number of times startCopy() has been attempted and had a non-fatal
15471         * error.
15472         */
15473        private int mRetries = 0;
15474
15475        /** User handle for the user requesting the information or installation. */
15476        private final UserHandle mUser;
15477        String traceMethod;
15478        int traceCookie;
15479
15480        HandlerParams(UserHandle user) {
15481            mUser = user;
15482        }
15483
15484        UserHandle getUser() {
15485            return mUser;
15486        }
15487
15488        HandlerParams setTraceMethod(String traceMethod) {
15489            this.traceMethod = traceMethod;
15490            return this;
15491        }
15492
15493        HandlerParams setTraceCookie(int traceCookie) {
15494            this.traceCookie = traceCookie;
15495            return this;
15496        }
15497
15498        final boolean startCopy() {
15499            boolean res;
15500            try {
15501                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15502
15503                if (++mRetries > MAX_RETRIES) {
15504                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15505                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15506                    handleServiceError();
15507                    return false;
15508                } else {
15509                    handleStartCopy();
15510                    res = true;
15511                }
15512            } catch (RemoteException e) {
15513                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15514                mHandler.sendEmptyMessage(MCS_RECONNECT);
15515                res = false;
15516            }
15517            handleReturnCode();
15518            return res;
15519        }
15520
15521        final void serviceError() {
15522            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15523            handleServiceError();
15524            handleReturnCode();
15525        }
15526
15527        abstract void handleStartCopy() throws RemoteException;
15528        abstract void handleServiceError();
15529        abstract void handleReturnCode();
15530    }
15531
15532    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15533        for (File path : paths) {
15534            try {
15535                mcs.clearDirectory(path.getAbsolutePath());
15536            } catch (RemoteException e) {
15537            }
15538        }
15539    }
15540
15541    static class OriginInfo {
15542        /**
15543         * Location where install is coming from, before it has been
15544         * copied/renamed into place. This could be a single monolithic APK
15545         * file, or a cluster directory. This location may be untrusted.
15546         */
15547        final File file;
15548        final String cid;
15549
15550        /**
15551         * Flag indicating that {@link #file} or {@link #cid} has already been
15552         * staged, meaning downstream users don't need to defensively copy the
15553         * contents.
15554         */
15555        final boolean staged;
15556
15557        /**
15558         * Flag indicating that {@link #file} or {@link #cid} is an already
15559         * installed app that is being moved.
15560         */
15561        final boolean existing;
15562
15563        final String resolvedPath;
15564        final File resolvedFile;
15565
15566        static OriginInfo fromNothing() {
15567            return new OriginInfo(null, null, false, false);
15568        }
15569
15570        static OriginInfo fromUntrustedFile(File file) {
15571            return new OriginInfo(file, null, false, false);
15572        }
15573
15574        static OriginInfo fromExistingFile(File file) {
15575            return new OriginInfo(file, null, false, true);
15576        }
15577
15578        static OriginInfo fromStagedFile(File file) {
15579            return new OriginInfo(file, null, true, false);
15580        }
15581
15582        static OriginInfo fromStagedContainer(String cid) {
15583            return new OriginInfo(null, cid, true, false);
15584        }
15585
15586        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15587            this.file = file;
15588            this.cid = cid;
15589            this.staged = staged;
15590            this.existing = existing;
15591
15592            if (cid != null) {
15593                resolvedPath = PackageHelper.getSdDir(cid);
15594                resolvedFile = new File(resolvedPath);
15595            } else if (file != null) {
15596                resolvedPath = file.getAbsolutePath();
15597                resolvedFile = file;
15598            } else {
15599                resolvedPath = null;
15600                resolvedFile = null;
15601            }
15602        }
15603    }
15604
15605    static class MoveInfo {
15606        final int moveId;
15607        final String fromUuid;
15608        final String toUuid;
15609        final String packageName;
15610        final String dataAppName;
15611        final int appId;
15612        final String seinfo;
15613        final int targetSdkVersion;
15614
15615        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15616                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15617            this.moveId = moveId;
15618            this.fromUuid = fromUuid;
15619            this.toUuid = toUuid;
15620            this.packageName = packageName;
15621            this.dataAppName = dataAppName;
15622            this.appId = appId;
15623            this.seinfo = seinfo;
15624            this.targetSdkVersion = targetSdkVersion;
15625        }
15626    }
15627
15628    static class VerificationInfo {
15629        /** A constant used to indicate that a uid value is not present. */
15630        public static final int NO_UID = -1;
15631
15632        /** URI referencing where the package was downloaded from. */
15633        final Uri originatingUri;
15634
15635        /** HTTP referrer URI associated with the originatingURI. */
15636        final Uri referrer;
15637
15638        /** UID of the application that the install request originated from. */
15639        final int originatingUid;
15640
15641        /** UID of application requesting the install */
15642        final int installerUid;
15643
15644        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15645            this.originatingUri = originatingUri;
15646            this.referrer = referrer;
15647            this.originatingUid = originatingUid;
15648            this.installerUid = installerUid;
15649        }
15650    }
15651
15652    class InstallParams extends HandlerParams {
15653        final OriginInfo origin;
15654        final MoveInfo move;
15655        final IPackageInstallObserver2 observer;
15656        int installFlags;
15657        final String installerPackageName;
15658        final String volumeUuid;
15659        private InstallArgs mArgs;
15660        private int mRet;
15661        final String packageAbiOverride;
15662        final String[] grantedRuntimePermissions;
15663        final VerificationInfo verificationInfo;
15664        final Certificate[][] certificates;
15665        final int installReason;
15666
15667        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15668                int installFlags, String installerPackageName, String volumeUuid,
15669                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15670                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15671            super(user);
15672            this.origin = origin;
15673            this.move = move;
15674            this.observer = observer;
15675            this.installFlags = installFlags;
15676            this.installerPackageName = installerPackageName;
15677            this.volumeUuid = volumeUuid;
15678            this.verificationInfo = verificationInfo;
15679            this.packageAbiOverride = packageAbiOverride;
15680            this.grantedRuntimePermissions = grantedPermissions;
15681            this.certificates = certificates;
15682            this.installReason = installReason;
15683        }
15684
15685        @Override
15686        public String toString() {
15687            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15688                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15689        }
15690
15691        private int installLocationPolicy(PackageInfoLite pkgLite) {
15692            String packageName = pkgLite.packageName;
15693            int installLocation = pkgLite.installLocation;
15694            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15695            // reader
15696            synchronized (mPackages) {
15697                // Currently installed package which the new package is attempting to replace or
15698                // null if no such package is installed.
15699                PackageParser.Package installedPkg = mPackages.get(packageName);
15700                // Package which currently owns the data which the new package will own if installed.
15701                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15702                // will be null whereas dataOwnerPkg will contain information about the package
15703                // which was uninstalled while keeping its data.
15704                PackageParser.Package dataOwnerPkg = installedPkg;
15705                if (dataOwnerPkg  == null) {
15706                    PackageSetting ps = mSettings.mPackages.get(packageName);
15707                    if (ps != null) {
15708                        dataOwnerPkg = ps.pkg;
15709                    }
15710                }
15711
15712                if (dataOwnerPkg != null) {
15713                    // If installed, the package will get access to data left on the device by its
15714                    // predecessor. As a security measure, this is permited only if this is not a
15715                    // version downgrade or if the predecessor package is marked as debuggable and
15716                    // a downgrade is explicitly requested.
15717                    //
15718                    // On debuggable platform builds, downgrades are permitted even for
15719                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15720                    // not offer security guarantees and thus it's OK to disable some security
15721                    // mechanisms to make debugging/testing easier on those builds. However, even on
15722                    // debuggable builds downgrades of packages are permitted only if requested via
15723                    // installFlags. This is because we aim to keep the behavior of debuggable
15724                    // platform builds as close as possible to the behavior of non-debuggable
15725                    // platform builds.
15726                    final boolean downgradeRequested =
15727                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15728                    final boolean packageDebuggable =
15729                                (dataOwnerPkg.applicationInfo.flags
15730                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15731                    final boolean downgradePermitted =
15732                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15733                    if (!downgradePermitted) {
15734                        try {
15735                            checkDowngrade(dataOwnerPkg, pkgLite);
15736                        } catch (PackageManagerException e) {
15737                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15738                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15739                        }
15740                    }
15741                }
15742
15743                if (installedPkg != null) {
15744                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15745                        // Check for updated system application.
15746                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15747                            if (onSd) {
15748                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15749                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15750                            }
15751                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15752                        } else {
15753                            if (onSd) {
15754                                // Install flag overrides everything.
15755                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15756                            }
15757                            // If current upgrade specifies particular preference
15758                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15759                                // Application explicitly specified internal.
15760                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15761                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15762                                // App explictly prefers external. Let policy decide
15763                            } else {
15764                                // Prefer previous location
15765                                if (isExternal(installedPkg)) {
15766                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15767                                }
15768                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15769                            }
15770                        }
15771                    } else {
15772                        // Invalid install. Return error code
15773                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15774                    }
15775                }
15776            }
15777            // All the special cases have been taken care of.
15778            // Return result based on recommended install location.
15779            if (onSd) {
15780                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15781            }
15782            return pkgLite.recommendedInstallLocation;
15783        }
15784
15785        /*
15786         * Invoke remote method to get package information and install
15787         * location values. Override install location based on default
15788         * policy if needed and then create install arguments based
15789         * on the install location.
15790         */
15791        public void handleStartCopy() throws RemoteException {
15792            int ret = PackageManager.INSTALL_SUCCEEDED;
15793
15794            // If we're already staged, we've firmly committed to an install location
15795            if (origin.staged) {
15796                if (origin.file != null) {
15797                    installFlags |= PackageManager.INSTALL_INTERNAL;
15798                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15799                } else if (origin.cid != null) {
15800                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15801                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15802                } else {
15803                    throw new IllegalStateException("Invalid stage location");
15804                }
15805            }
15806
15807            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15808            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15809            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15810            PackageInfoLite pkgLite = null;
15811
15812            if (onInt && onSd) {
15813                // Check if both bits are set.
15814                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15815                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15816            } else if (onSd && ephemeral) {
15817                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15818                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15819            } else {
15820                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15821                        packageAbiOverride);
15822
15823                if (DEBUG_EPHEMERAL && ephemeral) {
15824                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15825                }
15826
15827                /*
15828                 * If we have too little free space, try to free cache
15829                 * before giving up.
15830                 */
15831                if (!origin.staged && pkgLite.recommendedInstallLocation
15832                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15833                    // TODO: focus freeing disk space on the target device
15834                    final StorageManager storage = StorageManager.from(mContext);
15835                    final long lowThreshold = storage.getStorageLowBytes(
15836                            Environment.getDataDirectory());
15837
15838                    final long sizeBytes = mContainerService.calculateInstalledSize(
15839                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15840
15841                    try {
15842                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15843                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15844                                installFlags, packageAbiOverride);
15845                    } catch (InstallerException e) {
15846                        Slog.w(TAG, "Failed to free cache", e);
15847                    }
15848
15849                    /*
15850                     * The cache free must have deleted the file we
15851                     * downloaded to install.
15852                     *
15853                     * TODO: fix the "freeCache" call to not delete
15854                     *       the file we care about.
15855                     */
15856                    if (pkgLite.recommendedInstallLocation
15857                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15858                        pkgLite.recommendedInstallLocation
15859                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15860                    }
15861                }
15862            }
15863
15864            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15865                int loc = pkgLite.recommendedInstallLocation;
15866                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15867                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15868                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15869                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15870                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15871                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15872                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15873                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15874                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15875                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15876                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15877                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15878                } else {
15879                    // Override with defaults if needed.
15880                    loc = installLocationPolicy(pkgLite);
15881                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15882                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15883                    } else if (!onSd && !onInt) {
15884                        // Override install location with flags
15885                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15886                            // Set the flag to install on external media.
15887                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15888                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15889                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15890                            if (DEBUG_EPHEMERAL) {
15891                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15892                            }
15893                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15894                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15895                                    |PackageManager.INSTALL_INTERNAL);
15896                        } else {
15897                            // Make sure the flag for installing on external
15898                            // media is unset
15899                            installFlags |= PackageManager.INSTALL_INTERNAL;
15900                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15901                        }
15902                    }
15903                }
15904            }
15905
15906            final InstallArgs args = createInstallArgs(this);
15907            mArgs = args;
15908
15909            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15910                // TODO: http://b/22976637
15911                // Apps installed for "all" users use the device owner to verify the app
15912                UserHandle verifierUser = getUser();
15913                if (verifierUser == UserHandle.ALL) {
15914                    verifierUser = UserHandle.SYSTEM;
15915                }
15916
15917                /*
15918                 * Determine if we have any installed package verifiers. If we
15919                 * do, then we'll defer to them to verify the packages.
15920                 */
15921                final int requiredUid = mRequiredVerifierPackage == null ? -1
15922                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15923                                verifierUser.getIdentifier());
15924                final int installerUid =
15925                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15926                if (!origin.existing && requiredUid != -1
15927                        && isVerificationEnabled(
15928                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15929                    final Intent verification = new Intent(
15930                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15931                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15932                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15933                            PACKAGE_MIME_TYPE);
15934                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15935
15936                    // Query all live verifiers based on current user state
15937                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15938                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15939
15940                    if (DEBUG_VERIFY) {
15941                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15942                                + verification.toString() + " with " + pkgLite.verifiers.length
15943                                + " optional verifiers");
15944                    }
15945
15946                    final int verificationId = mPendingVerificationToken++;
15947
15948                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15949
15950                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15951                            installerPackageName);
15952
15953                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15954                            installFlags);
15955
15956                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15957                            pkgLite.packageName);
15958
15959                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15960                            pkgLite.versionCode);
15961
15962                    if (verificationInfo != null) {
15963                        if (verificationInfo.originatingUri != null) {
15964                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15965                                    verificationInfo.originatingUri);
15966                        }
15967                        if (verificationInfo.referrer != null) {
15968                            verification.putExtra(Intent.EXTRA_REFERRER,
15969                                    verificationInfo.referrer);
15970                        }
15971                        if (verificationInfo.originatingUid >= 0) {
15972                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15973                                    verificationInfo.originatingUid);
15974                        }
15975                        if (verificationInfo.installerUid >= 0) {
15976                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15977                                    verificationInfo.installerUid);
15978                        }
15979                    }
15980
15981                    final PackageVerificationState verificationState = new PackageVerificationState(
15982                            requiredUid, args);
15983
15984                    mPendingVerification.append(verificationId, verificationState);
15985
15986                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15987                            receivers, verificationState);
15988
15989                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15990                    final long idleDuration = getVerificationTimeout();
15991
15992                    /*
15993                     * If any sufficient verifiers were listed in the package
15994                     * manifest, attempt to ask them.
15995                     */
15996                    if (sufficientVerifiers != null) {
15997                        final int N = sufficientVerifiers.size();
15998                        if (N == 0) {
15999                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16000                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16001                        } else {
16002                            for (int i = 0; i < N; i++) {
16003                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16004                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16005                                        verifierComponent.getPackageName(), idleDuration,
16006                                        verifierUser.getIdentifier(), false, "package verifier");
16007
16008                                final Intent sufficientIntent = new Intent(verification);
16009                                sufficientIntent.setComponent(verifierComponent);
16010                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16011                            }
16012                        }
16013                    }
16014
16015                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16016                            mRequiredVerifierPackage, receivers);
16017                    if (ret == PackageManager.INSTALL_SUCCEEDED
16018                            && mRequiredVerifierPackage != null) {
16019                        Trace.asyncTraceBegin(
16020                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16021                        /*
16022                         * Send the intent to the required verification agent,
16023                         * but only start the verification timeout after the
16024                         * target BroadcastReceivers have run.
16025                         */
16026                        verification.setComponent(requiredVerifierComponent);
16027                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16028                                mRequiredVerifierPackage, idleDuration,
16029                                verifierUser.getIdentifier(), false, "package verifier");
16030                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16031                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16032                                new BroadcastReceiver() {
16033                                    @Override
16034                                    public void onReceive(Context context, Intent intent) {
16035                                        final Message msg = mHandler
16036                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16037                                        msg.arg1 = verificationId;
16038                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16039                                    }
16040                                }, null, 0, null, null);
16041
16042                        /*
16043                         * We don't want the copy to proceed until verification
16044                         * succeeds, so null out this field.
16045                         */
16046                        mArgs = null;
16047                    }
16048                } else {
16049                    /*
16050                     * No package verification is enabled, so immediately start
16051                     * the remote call to initiate copy using temporary file.
16052                     */
16053                    ret = args.copyApk(mContainerService, true);
16054                }
16055            }
16056
16057            mRet = ret;
16058        }
16059
16060        @Override
16061        void handleReturnCode() {
16062            // If mArgs is null, then MCS couldn't be reached. When it
16063            // reconnects, it will try again to install. At that point, this
16064            // will succeed.
16065            if (mArgs != null) {
16066                processPendingInstall(mArgs, mRet);
16067            }
16068        }
16069
16070        @Override
16071        void handleServiceError() {
16072            mArgs = createInstallArgs(this);
16073            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16074        }
16075
16076        public boolean isForwardLocked() {
16077            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16078        }
16079    }
16080
16081    /**
16082     * Used during creation of InstallArgs
16083     *
16084     * @param installFlags package installation flags
16085     * @return true if should be installed on external storage
16086     */
16087    private static boolean installOnExternalAsec(int installFlags) {
16088        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16089            return false;
16090        }
16091        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16092            return true;
16093        }
16094        return false;
16095    }
16096
16097    /**
16098     * Used during creation of InstallArgs
16099     *
16100     * @param installFlags package installation flags
16101     * @return true if should be installed as forward locked
16102     */
16103    private static boolean installForwardLocked(int installFlags) {
16104        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16105    }
16106
16107    private InstallArgs createInstallArgs(InstallParams params) {
16108        if (params.move != null) {
16109            return new MoveInstallArgs(params);
16110        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16111            return new AsecInstallArgs(params);
16112        } else {
16113            return new FileInstallArgs(params);
16114        }
16115    }
16116
16117    /**
16118     * Create args that describe an existing installed package. Typically used
16119     * when cleaning up old installs, or used as a move source.
16120     */
16121    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16122            String resourcePath, String[] instructionSets) {
16123        final boolean isInAsec;
16124        if (installOnExternalAsec(installFlags)) {
16125            /* Apps on SD card are always in ASEC containers. */
16126            isInAsec = true;
16127        } else if (installForwardLocked(installFlags)
16128                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16129            /*
16130             * Forward-locked apps are only in ASEC containers if they're the
16131             * new style
16132             */
16133            isInAsec = true;
16134        } else {
16135            isInAsec = false;
16136        }
16137
16138        if (isInAsec) {
16139            return new AsecInstallArgs(codePath, instructionSets,
16140                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16141        } else {
16142            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16143        }
16144    }
16145
16146    static abstract class InstallArgs {
16147        /** @see InstallParams#origin */
16148        final OriginInfo origin;
16149        /** @see InstallParams#move */
16150        final MoveInfo move;
16151
16152        final IPackageInstallObserver2 observer;
16153        // Always refers to PackageManager flags only
16154        final int installFlags;
16155        final String installerPackageName;
16156        final String volumeUuid;
16157        final UserHandle user;
16158        final String abiOverride;
16159        final String[] installGrantPermissions;
16160        /** If non-null, drop an async trace when the install completes */
16161        final String traceMethod;
16162        final int traceCookie;
16163        final Certificate[][] certificates;
16164        final int installReason;
16165
16166        // The list of instruction sets supported by this app. This is currently
16167        // only used during the rmdex() phase to clean up resources. We can get rid of this
16168        // if we move dex files under the common app path.
16169        /* nullable */ String[] instructionSets;
16170
16171        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16172                int installFlags, String installerPackageName, String volumeUuid,
16173                UserHandle user, String[] instructionSets,
16174                String abiOverride, String[] installGrantPermissions,
16175                String traceMethod, int traceCookie, Certificate[][] certificates,
16176                int installReason) {
16177            this.origin = origin;
16178            this.move = move;
16179            this.installFlags = installFlags;
16180            this.observer = observer;
16181            this.installerPackageName = installerPackageName;
16182            this.volumeUuid = volumeUuid;
16183            this.user = user;
16184            this.instructionSets = instructionSets;
16185            this.abiOverride = abiOverride;
16186            this.installGrantPermissions = installGrantPermissions;
16187            this.traceMethod = traceMethod;
16188            this.traceCookie = traceCookie;
16189            this.certificates = certificates;
16190            this.installReason = installReason;
16191        }
16192
16193        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16194        abstract int doPreInstall(int status);
16195
16196        /**
16197         * Rename package into final resting place. All paths on the given
16198         * scanned package should be updated to reflect the rename.
16199         */
16200        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16201        abstract int doPostInstall(int status, int uid);
16202
16203        /** @see PackageSettingBase#codePathString */
16204        abstract String getCodePath();
16205        /** @see PackageSettingBase#resourcePathString */
16206        abstract String getResourcePath();
16207
16208        // Need installer lock especially for dex file removal.
16209        abstract void cleanUpResourcesLI();
16210        abstract boolean doPostDeleteLI(boolean delete);
16211
16212        /**
16213         * Called before the source arguments are copied. This is used mostly
16214         * for MoveParams when it needs to read the source file to put it in the
16215         * destination.
16216         */
16217        int doPreCopy() {
16218            return PackageManager.INSTALL_SUCCEEDED;
16219        }
16220
16221        /**
16222         * Called after the source arguments are copied. This is used mostly for
16223         * MoveParams when it needs to read the source file to put it in the
16224         * destination.
16225         */
16226        int doPostCopy(int uid) {
16227            return PackageManager.INSTALL_SUCCEEDED;
16228        }
16229
16230        protected boolean isFwdLocked() {
16231            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16232        }
16233
16234        protected boolean isExternalAsec() {
16235            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16236        }
16237
16238        protected boolean isEphemeral() {
16239            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16240        }
16241
16242        UserHandle getUser() {
16243            return user;
16244        }
16245    }
16246
16247    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16248        if (!allCodePaths.isEmpty()) {
16249            if (instructionSets == null) {
16250                throw new IllegalStateException("instructionSet == null");
16251            }
16252            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16253            for (String codePath : allCodePaths) {
16254                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16255                    try {
16256                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16257                    } catch (InstallerException ignored) {
16258                    }
16259                }
16260            }
16261        }
16262    }
16263
16264    /**
16265     * Logic to handle installation of non-ASEC applications, including copying
16266     * and renaming logic.
16267     */
16268    class FileInstallArgs extends InstallArgs {
16269        private File codeFile;
16270        private File resourceFile;
16271
16272        // Example topology:
16273        // /data/app/com.example/base.apk
16274        // /data/app/com.example/split_foo.apk
16275        // /data/app/com.example/lib/arm/libfoo.so
16276        // /data/app/com.example/lib/arm64/libfoo.so
16277        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16278
16279        /** New install */
16280        FileInstallArgs(InstallParams params) {
16281            super(params.origin, params.move, params.observer, params.installFlags,
16282                    params.installerPackageName, params.volumeUuid,
16283                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16284                    params.grantedRuntimePermissions,
16285                    params.traceMethod, params.traceCookie, params.certificates,
16286                    params.installReason);
16287            if (isFwdLocked()) {
16288                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16289            }
16290        }
16291
16292        /** Existing install */
16293        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16294            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16295                    null, null, null, 0, null /*certificates*/,
16296                    PackageManager.INSTALL_REASON_UNKNOWN);
16297            this.codeFile = (codePath != null) ? new File(codePath) : null;
16298            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16299        }
16300
16301        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16302            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16303            try {
16304                return doCopyApk(imcs, temp);
16305            } finally {
16306                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16307            }
16308        }
16309
16310        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16311            if (origin.staged) {
16312                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16313                codeFile = origin.file;
16314                resourceFile = origin.file;
16315                return PackageManager.INSTALL_SUCCEEDED;
16316            }
16317
16318            try {
16319                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16320                final File tempDir =
16321                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16322                codeFile = tempDir;
16323                resourceFile = tempDir;
16324            } catch (IOException e) {
16325                Slog.w(TAG, "Failed to create copy file: " + e);
16326                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16327            }
16328
16329            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16330                @Override
16331                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16332                    if (!FileUtils.isValidExtFilename(name)) {
16333                        throw new IllegalArgumentException("Invalid filename: " + name);
16334                    }
16335                    try {
16336                        final File file = new File(codeFile, name);
16337                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16338                                O_RDWR | O_CREAT, 0644);
16339                        Os.chmod(file.getAbsolutePath(), 0644);
16340                        return new ParcelFileDescriptor(fd);
16341                    } catch (ErrnoException e) {
16342                        throw new RemoteException("Failed to open: " + e.getMessage());
16343                    }
16344                }
16345            };
16346
16347            int ret = PackageManager.INSTALL_SUCCEEDED;
16348            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16349            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16350                Slog.e(TAG, "Failed to copy package");
16351                return ret;
16352            }
16353
16354            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16355            NativeLibraryHelper.Handle handle = null;
16356            try {
16357                handle = NativeLibraryHelper.Handle.create(codeFile);
16358                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16359                        abiOverride);
16360            } catch (IOException e) {
16361                Slog.e(TAG, "Copying native libraries failed", e);
16362                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16363            } finally {
16364                IoUtils.closeQuietly(handle);
16365            }
16366
16367            return ret;
16368        }
16369
16370        int doPreInstall(int status) {
16371            if (status != PackageManager.INSTALL_SUCCEEDED) {
16372                cleanUp();
16373            }
16374            return status;
16375        }
16376
16377        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16378            if (status != PackageManager.INSTALL_SUCCEEDED) {
16379                cleanUp();
16380                return false;
16381            }
16382
16383            final File targetDir = codeFile.getParentFile();
16384            final File beforeCodeFile = codeFile;
16385            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16386
16387            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16388            try {
16389                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16390            } catch (ErrnoException e) {
16391                Slog.w(TAG, "Failed to rename", e);
16392                return false;
16393            }
16394
16395            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16396                Slog.w(TAG, "Failed to restorecon");
16397                return false;
16398            }
16399
16400            // Reflect the rename internally
16401            codeFile = afterCodeFile;
16402            resourceFile = afterCodeFile;
16403
16404            // Reflect the rename in scanned details
16405            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16406            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16407                    afterCodeFile, pkg.baseCodePath));
16408            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16409                    afterCodeFile, pkg.splitCodePaths));
16410
16411            // Reflect the rename in app info
16412            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16413            pkg.setApplicationInfoCodePath(pkg.codePath);
16414            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16415            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16416            pkg.setApplicationInfoResourcePath(pkg.codePath);
16417            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16418            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16419
16420            return true;
16421        }
16422
16423        int doPostInstall(int status, int uid) {
16424            if (status != PackageManager.INSTALL_SUCCEEDED) {
16425                cleanUp();
16426            }
16427            return status;
16428        }
16429
16430        @Override
16431        String getCodePath() {
16432            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16433        }
16434
16435        @Override
16436        String getResourcePath() {
16437            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16438        }
16439
16440        private boolean cleanUp() {
16441            if (codeFile == null || !codeFile.exists()) {
16442                return false;
16443            }
16444
16445            removeCodePathLI(codeFile);
16446
16447            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16448                resourceFile.delete();
16449            }
16450
16451            return true;
16452        }
16453
16454        void cleanUpResourcesLI() {
16455            // Try enumerating all code paths before deleting
16456            List<String> allCodePaths = Collections.EMPTY_LIST;
16457            if (codeFile != null && codeFile.exists()) {
16458                try {
16459                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16460                    allCodePaths = pkg.getAllCodePaths();
16461                } catch (PackageParserException e) {
16462                    // Ignored; we tried our best
16463                }
16464            }
16465
16466            cleanUp();
16467            removeDexFiles(allCodePaths, instructionSets);
16468        }
16469
16470        boolean doPostDeleteLI(boolean delete) {
16471            // XXX err, shouldn't we respect the delete flag?
16472            cleanUpResourcesLI();
16473            return true;
16474        }
16475    }
16476
16477    private boolean isAsecExternal(String cid) {
16478        final String asecPath = PackageHelper.getSdFilesystem(cid);
16479        return !asecPath.startsWith(mAsecInternalPath);
16480    }
16481
16482    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16483            PackageManagerException {
16484        if (copyRet < 0) {
16485            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16486                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16487                throw new PackageManagerException(copyRet, message);
16488            }
16489        }
16490    }
16491
16492    /**
16493     * Extract the StorageManagerService "container ID" from the full code path of an
16494     * .apk.
16495     */
16496    static String cidFromCodePath(String fullCodePath) {
16497        int eidx = fullCodePath.lastIndexOf("/");
16498        String subStr1 = fullCodePath.substring(0, eidx);
16499        int sidx = subStr1.lastIndexOf("/");
16500        return subStr1.substring(sidx+1, eidx);
16501    }
16502
16503    /**
16504     * Logic to handle installation of ASEC applications, including copying and
16505     * renaming logic.
16506     */
16507    class AsecInstallArgs extends InstallArgs {
16508        static final String RES_FILE_NAME = "pkg.apk";
16509        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16510
16511        String cid;
16512        String packagePath;
16513        String resourcePath;
16514
16515        /** New install */
16516        AsecInstallArgs(InstallParams params) {
16517            super(params.origin, params.move, params.observer, params.installFlags,
16518                    params.installerPackageName, params.volumeUuid,
16519                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16520                    params.grantedRuntimePermissions,
16521                    params.traceMethod, params.traceCookie, params.certificates,
16522                    params.installReason);
16523        }
16524
16525        /** Existing install */
16526        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16527                        boolean isExternal, boolean isForwardLocked) {
16528            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16529                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16530                    instructionSets, null, null, null, 0, null /*certificates*/,
16531                    PackageManager.INSTALL_REASON_UNKNOWN);
16532            // Hackily pretend we're still looking at a full code path
16533            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16534                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16535            }
16536
16537            // Extract cid from fullCodePath
16538            int eidx = fullCodePath.lastIndexOf("/");
16539            String subStr1 = fullCodePath.substring(0, eidx);
16540            int sidx = subStr1.lastIndexOf("/");
16541            cid = subStr1.substring(sidx+1, eidx);
16542            setMountPath(subStr1);
16543        }
16544
16545        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16546            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16547                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16548                    instructionSets, null, null, null, 0, null /*certificates*/,
16549                    PackageManager.INSTALL_REASON_UNKNOWN);
16550            this.cid = cid;
16551            setMountPath(PackageHelper.getSdDir(cid));
16552        }
16553
16554        void createCopyFile() {
16555            cid = mInstallerService.allocateExternalStageCidLegacy();
16556        }
16557
16558        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16559            if (origin.staged && origin.cid != null) {
16560                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16561                cid = origin.cid;
16562                setMountPath(PackageHelper.getSdDir(cid));
16563                return PackageManager.INSTALL_SUCCEEDED;
16564            }
16565
16566            if (temp) {
16567                createCopyFile();
16568            } else {
16569                /*
16570                 * Pre-emptively destroy the container since it's destroyed if
16571                 * copying fails due to it existing anyway.
16572                 */
16573                PackageHelper.destroySdDir(cid);
16574            }
16575
16576            final String newMountPath = imcs.copyPackageToContainer(
16577                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16578                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16579
16580            if (newMountPath != null) {
16581                setMountPath(newMountPath);
16582                return PackageManager.INSTALL_SUCCEEDED;
16583            } else {
16584                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16585            }
16586        }
16587
16588        @Override
16589        String getCodePath() {
16590            return packagePath;
16591        }
16592
16593        @Override
16594        String getResourcePath() {
16595            return resourcePath;
16596        }
16597
16598        int doPreInstall(int status) {
16599            if (status != PackageManager.INSTALL_SUCCEEDED) {
16600                // Destroy container
16601                PackageHelper.destroySdDir(cid);
16602            } else {
16603                boolean mounted = PackageHelper.isContainerMounted(cid);
16604                if (!mounted) {
16605                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16606                            Process.SYSTEM_UID);
16607                    if (newMountPath != null) {
16608                        setMountPath(newMountPath);
16609                    } else {
16610                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16611                    }
16612                }
16613            }
16614            return status;
16615        }
16616
16617        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16618            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16619            String newMountPath = null;
16620            if (PackageHelper.isContainerMounted(cid)) {
16621                // Unmount the container
16622                if (!PackageHelper.unMountSdDir(cid)) {
16623                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16624                    return false;
16625                }
16626            }
16627            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16628                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16629                        " which might be stale. Will try to clean up.");
16630                // Clean up the stale container and proceed to recreate.
16631                if (!PackageHelper.destroySdDir(newCacheId)) {
16632                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16633                    return false;
16634                }
16635                // Successfully cleaned up stale container. Try to rename again.
16636                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16637                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16638                            + " inspite of cleaning it up.");
16639                    return false;
16640                }
16641            }
16642            if (!PackageHelper.isContainerMounted(newCacheId)) {
16643                Slog.w(TAG, "Mounting container " + newCacheId);
16644                newMountPath = PackageHelper.mountSdDir(newCacheId,
16645                        getEncryptKey(), Process.SYSTEM_UID);
16646            } else {
16647                newMountPath = PackageHelper.getSdDir(newCacheId);
16648            }
16649            if (newMountPath == null) {
16650                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16651                return false;
16652            }
16653            Log.i(TAG, "Succesfully renamed " + cid +
16654                    " to " + newCacheId +
16655                    " at new path: " + newMountPath);
16656            cid = newCacheId;
16657
16658            final File beforeCodeFile = new File(packagePath);
16659            setMountPath(newMountPath);
16660            final File afterCodeFile = new File(packagePath);
16661
16662            // Reflect the rename in scanned details
16663            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16664            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16665                    afterCodeFile, pkg.baseCodePath));
16666            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16667                    afterCodeFile, pkg.splitCodePaths));
16668
16669            // Reflect the rename in app info
16670            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16671            pkg.setApplicationInfoCodePath(pkg.codePath);
16672            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16673            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16674            pkg.setApplicationInfoResourcePath(pkg.codePath);
16675            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16676            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16677
16678            return true;
16679        }
16680
16681        private void setMountPath(String mountPath) {
16682            final File mountFile = new File(mountPath);
16683
16684            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16685            if (monolithicFile.exists()) {
16686                packagePath = monolithicFile.getAbsolutePath();
16687                if (isFwdLocked()) {
16688                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16689                } else {
16690                    resourcePath = packagePath;
16691                }
16692            } else {
16693                packagePath = mountFile.getAbsolutePath();
16694                resourcePath = packagePath;
16695            }
16696        }
16697
16698        int doPostInstall(int status, int uid) {
16699            if (status != PackageManager.INSTALL_SUCCEEDED) {
16700                cleanUp();
16701            } else {
16702                final int groupOwner;
16703                final String protectedFile;
16704                if (isFwdLocked()) {
16705                    groupOwner = UserHandle.getSharedAppGid(uid);
16706                    protectedFile = RES_FILE_NAME;
16707                } else {
16708                    groupOwner = -1;
16709                    protectedFile = null;
16710                }
16711
16712                if (uid < Process.FIRST_APPLICATION_UID
16713                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16714                    Slog.e(TAG, "Failed to finalize " + cid);
16715                    PackageHelper.destroySdDir(cid);
16716                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16717                }
16718
16719                boolean mounted = PackageHelper.isContainerMounted(cid);
16720                if (!mounted) {
16721                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16722                }
16723            }
16724            return status;
16725        }
16726
16727        private void cleanUp() {
16728            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16729
16730            // Destroy secure container
16731            PackageHelper.destroySdDir(cid);
16732        }
16733
16734        private List<String> getAllCodePaths() {
16735            final File codeFile = new File(getCodePath());
16736            if (codeFile != null && codeFile.exists()) {
16737                try {
16738                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16739                    return pkg.getAllCodePaths();
16740                } catch (PackageParserException e) {
16741                    // Ignored; we tried our best
16742                }
16743            }
16744            return Collections.EMPTY_LIST;
16745        }
16746
16747        void cleanUpResourcesLI() {
16748            // Enumerate all code paths before deleting
16749            cleanUpResourcesLI(getAllCodePaths());
16750        }
16751
16752        private void cleanUpResourcesLI(List<String> allCodePaths) {
16753            cleanUp();
16754            removeDexFiles(allCodePaths, instructionSets);
16755        }
16756
16757        String getPackageName() {
16758            return getAsecPackageName(cid);
16759        }
16760
16761        boolean doPostDeleteLI(boolean delete) {
16762            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16763            final List<String> allCodePaths = getAllCodePaths();
16764            boolean mounted = PackageHelper.isContainerMounted(cid);
16765            if (mounted) {
16766                // Unmount first
16767                if (PackageHelper.unMountSdDir(cid)) {
16768                    mounted = false;
16769                }
16770            }
16771            if (!mounted && delete) {
16772                cleanUpResourcesLI(allCodePaths);
16773            }
16774            return !mounted;
16775        }
16776
16777        @Override
16778        int doPreCopy() {
16779            if (isFwdLocked()) {
16780                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16781                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16782                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16783                }
16784            }
16785
16786            return PackageManager.INSTALL_SUCCEEDED;
16787        }
16788
16789        @Override
16790        int doPostCopy(int uid) {
16791            if (isFwdLocked()) {
16792                if (uid < Process.FIRST_APPLICATION_UID
16793                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16794                                RES_FILE_NAME)) {
16795                    Slog.e(TAG, "Failed to finalize " + cid);
16796                    PackageHelper.destroySdDir(cid);
16797                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16798                }
16799            }
16800
16801            return PackageManager.INSTALL_SUCCEEDED;
16802        }
16803    }
16804
16805    /**
16806     * Logic to handle movement of existing installed applications.
16807     */
16808    class MoveInstallArgs extends InstallArgs {
16809        private File codeFile;
16810        private File resourceFile;
16811
16812        /** New install */
16813        MoveInstallArgs(InstallParams params) {
16814            super(params.origin, params.move, params.observer, params.installFlags,
16815                    params.installerPackageName, params.volumeUuid,
16816                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16817                    params.grantedRuntimePermissions,
16818                    params.traceMethod, params.traceCookie, params.certificates,
16819                    params.installReason);
16820        }
16821
16822        int copyApk(IMediaContainerService imcs, boolean temp) {
16823            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16824                    + move.fromUuid + " to " + move.toUuid);
16825            synchronized (mInstaller) {
16826                try {
16827                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16828                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16829                } catch (InstallerException e) {
16830                    Slog.w(TAG, "Failed to move app", e);
16831                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16832                }
16833            }
16834
16835            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16836            resourceFile = codeFile;
16837            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16838
16839            return PackageManager.INSTALL_SUCCEEDED;
16840        }
16841
16842        int doPreInstall(int status) {
16843            if (status != PackageManager.INSTALL_SUCCEEDED) {
16844                cleanUp(move.toUuid);
16845            }
16846            return status;
16847        }
16848
16849        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16850            if (status != PackageManager.INSTALL_SUCCEEDED) {
16851                cleanUp(move.toUuid);
16852                return false;
16853            }
16854
16855            // Reflect the move in app info
16856            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16857            pkg.setApplicationInfoCodePath(pkg.codePath);
16858            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16859            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16860            pkg.setApplicationInfoResourcePath(pkg.codePath);
16861            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16862            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16863
16864            return true;
16865        }
16866
16867        int doPostInstall(int status, int uid) {
16868            if (status == PackageManager.INSTALL_SUCCEEDED) {
16869                cleanUp(move.fromUuid);
16870            } else {
16871                cleanUp(move.toUuid);
16872            }
16873            return status;
16874        }
16875
16876        @Override
16877        String getCodePath() {
16878            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16879        }
16880
16881        @Override
16882        String getResourcePath() {
16883            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16884        }
16885
16886        private boolean cleanUp(String volumeUuid) {
16887            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16888                    move.dataAppName);
16889            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16890            final int[] userIds = sUserManager.getUserIds();
16891            synchronized (mInstallLock) {
16892                // Clean up both app data and code
16893                // All package moves are frozen until finished
16894                for (int userId : userIds) {
16895                    try {
16896                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16897                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16898                    } catch (InstallerException e) {
16899                        Slog.w(TAG, String.valueOf(e));
16900                    }
16901                }
16902                removeCodePathLI(codeFile);
16903            }
16904            return true;
16905        }
16906
16907        void cleanUpResourcesLI() {
16908            throw new UnsupportedOperationException();
16909        }
16910
16911        boolean doPostDeleteLI(boolean delete) {
16912            throw new UnsupportedOperationException();
16913        }
16914    }
16915
16916    static String getAsecPackageName(String packageCid) {
16917        int idx = packageCid.lastIndexOf("-");
16918        if (idx == -1) {
16919            return packageCid;
16920        }
16921        return packageCid.substring(0, idx);
16922    }
16923
16924    // Utility method used to create code paths based on package name and available index.
16925    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16926        String idxStr = "";
16927        int idx = 1;
16928        // Fall back to default value of idx=1 if prefix is not
16929        // part of oldCodePath
16930        if (oldCodePath != null) {
16931            String subStr = oldCodePath;
16932            // Drop the suffix right away
16933            if (suffix != null && subStr.endsWith(suffix)) {
16934                subStr = subStr.substring(0, subStr.length() - suffix.length());
16935            }
16936            // If oldCodePath already contains prefix find out the
16937            // ending index to either increment or decrement.
16938            int sidx = subStr.lastIndexOf(prefix);
16939            if (sidx != -1) {
16940                subStr = subStr.substring(sidx + prefix.length());
16941                if (subStr != null) {
16942                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16943                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16944                    }
16945                    try {
16946                        idx = Integer.parseInt(subStr);
16947                        if (idx <= 1) {
16948                            idx++;
16949                        } else {
16950                            idx--;
16951                        }
16952                    } catch(NumberFormatException e) {
16953                    }
16954                }
16955            }
16956        }
16957        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16958        return prefix + idxStr;
16959    }
16960
16961    private File getNextCodePath(File targetDir, String packageName) {
16962        File result;
16963        SecureRandom random = new SecureRandom();
16964        byte[] bytes = new byte[16];
16965        do {
16966            random.nextBytes(bytes);
16967            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16968            result = new File(targetDir, packageName + "-" + suffix);
16969        } while (result.exists());
16970        return result;
16971    }
16972
16973    // Utility method that returns the relative package path with respect
16974    // to the installation directory. Like say for /data/data/com.test-1.apk
16975    // string com.test-1 is returned.
16976    static String deriveCodePathName(String codePath) {
16977        if (codePath == null) {
16978            return null;
16979        }
16980        final File codeFile = new File(codePath);
16981        final String name = codeFile.getName();
16982        if (codeFile.isDirectory()) {
16983            return name;
16984        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16985            final int lastDot = name.lastIndexOf('.');
16986            return name.substring(0, lastDot);
16987        } else {
16988            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16989            return null;
16990        }
16991    }
16992
16993    static class PackageInstalledInfo {
16994        String name;
16995        int uid;
16996        // The set of users that originally had this package installed.
16997        int[] origUsers;
16998        // The set of users that now have this package installed.
16999        int[] newUsers;
17000        PackageParser.Package pkg;
17001        int returnCode;
17002        String returnMsg;
17003        PackageRemovedInfo removedInfo;
17004        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17005
17006        public void setError(int code, String msg) {
17007            setReturnCode(code);
17008            setReturnMessage(msg);
17009            Slog.w(TAG, msg);
17010        }
17011
17012        public void setError(String msg, PackageParserException e) {
17013            setReturnCode(e.error);
17014            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17015            Slog.w(TAG, msg, e);
17016        }
17017
17018        public void setError(String msg, PackageManagerException e) {
17019            returnCode = e.error;
17020            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17021            Slog.w(TAG, msg, e);
17022        }
17023
17024        public void setReturnCode(int returnCode) {
17025            this.returnCode = returnCode;
17026            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17027            for (int i = 0; i < childCount; i++) {
17028                addedChildPackages.valueAt(i).returnCode = returnCode;
17029            }
17030        }
17031
17032        private void setReturnMessage(String returnMsg) {
17033            this.returnMsg = returnMsg;
17034            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17035            for (int i = 0; i < childCount; i++) {
17036                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17037            }
17038        }
17039
17040        // In some error cases we want to convey more info back to the observer
17041        String origPackage;
17042        String origPermission;
17043    }
17044
17045    /*
17046     * Install a non-existing package.
17047     */
17048    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17049            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17050            PackageInstalledInfo res, int installReason) {
17051        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17052
17053        // Remember this for later, in case we need to rollback this install
17054        String pkgName = pkg.packageName;
17055
17056        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17057
17058        synchronized(mPackages) {
17059            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17060            if (renamedPackage != null) {
17061                // A package with the same name is already installed, though
17062                // it has been renamed to an older name.  The package we
17063                // are trying to install should be installed as an update to
17064                // the existing one, but that has not been requested, so bail.
17065                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17066                        + " without first uninstalling package running as "
17067                        + renamedPackage);
17068                return;
17069            }
17070            if (mPackages.containsKey(pkgName)) {
17071                // Don't allow installation over an existing package with the same name.
17072                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17073                        + " without first uninstalling.");
17074                return;
17075            }
17076        }
17077
17078        try {
17079            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17080                    System.currentTimeMillis(), user);
17081
17082            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17083
17084            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17085                prepareAppDataAfterInstallLIF(newPackage);
17086
17087            } else {
17088                // Remove package from internal structures, but keep around any
17089                // data that might have already existed
17090                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17091                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17092            }
17093        } catch (PackageManagerException e) {
17094            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17095        }
17096
17097        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17098    }
17099
17100    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17101        // Can't rotate keys during boot or if sharedUser.
17102        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17103                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17104            return false;
17105        }
17106        // app is using upgradeKeySets; make sure all are valid
17107        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17108        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17109        for (int i = 0; i < upgradeKeySets.length; i++) {
17110            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17111                Slog.wtf(TAG, "Package "
17112                         + (oldPs.name != null ? oldPs.name : "<null>")
17113                         + " contains upgrade-key-set reference to unknown key-set: "
17114                         + upgradeKeySets[i]
17115                         + " reverting to signatures check.");
17116                return false;
17117            }
17118        }
17119        return true;
17120    }
17121
17122    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17123        // Upgrade keysets are being used.  Determine if new package has a superset of the
17124        // required keys.
17125        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17126        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17127        for (int i = 0; i < upgradeKeySets.length; i++) {
17128            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17129            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17130                return true;
17131            }
17132        }
17133        return false;
17134    }
17135
17136    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17137        try (DigestInputStream digestStream =
17138                new DigestInputStream(new FileInputStream(file), digest)) {
17139            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17140        }
17141    }
17142
17143    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17144            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17145            int installReason) {
17146        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17147
17148        final PackageParser.Package oldPackage;
17149        final PackageSetting ps;
17150        final String pkgName = pkg.packageName;
17151        final int[] allUsers;
17152        final int[] installedUsers;
17153
17154        synchronized(mPackages) {
17155            oldPackage = mPackages.get(pkgName);
17156            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17157
17158            // don't allow upgrade to target a release SDK from a pre-release SDK
17159            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17160                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17161            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17162                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17163            if (oldTargetsPreRelease
17164                    && !newTargetsPreRelease
17165                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17166                Slog.w(TAG, "Can't install package targeting released sdk");
17167                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17168                return;
17169            }
17170
17171            ps = mSettings.mPackages.get(pkgName);
17172
17173            // verify signatures are valid
17174            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17175                if (!checkUpgradeKeySetLP(ps, pkg)) {
17176                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17177                            "New package not signed by keys specified by upgrade-keysets: "
17178                                    + pkgName);
17179                    return;
17180                }
17181            } else {
17182                // default to original signature matching
17183                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17184                        != PackageManager.SIGNATURE_MATCH) {
17185                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17186                            "New package has a different signature: " + pkgName);
17187                    return;
17188                }
17189            }
17190
17191            // don't allow a system upgrade unless the upgrade hash matches
17192            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17193                byte[] digestBytes = null;
17194                try {
17195                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17196                    updateDigest(digest, new File(pkg.baseCodePath));
17197                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17198                        for (String path : pkg.splitCodePaths) {
17199                            updateDigest(digest, new File(path));
17200                        }
17201                    }
17202                    digestBytes = digest.digest();
17203                } catch (NoSuchAlgorithmException | IOException e) {
17204                    res.setError(INSTALL_FAILED_INVALID_APK,
17205                            "Could not compute hash: " + pkgName);
17206                    return;
17207                }
17208                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17209                    res.setError(INSTALL_FAILED_INVALID_APK,
17210                            "New package fails restrict-update check: " + pkgName);
17211                    return;
17212                }
17213                // retain upgrade restriction
17214                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17215            }
17216
17217            // Check for shared user id changes
17218            String invalidPackageName =
17219                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17220            if (invalidPackageName != null) {
17221                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17222                        "Package " + invalidPackageName + " tried to change user "
17223                                + oldPackage.mSharedUserId);
17224                return;
17225            }
17226
17227            // In case of rollback, remember per-user/profile install state
17228            allUsers = sUserManager.getUserIds();
17229            installedUsers = ps.queryInstalledUsers(allUsers, true);
17230
17231            // don't allow an upgrade from full to ephemeral
17232            if (isInstantApp) {
17233                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17234                    for (int currentUser : allUsers) {
17235                        if (!ps.getInstantApp(currentUser)) {
17236                            // can't downgrade from full to instant
17237                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17238                                    + " for user: " + currentUser);
17239                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17240                            return;
17241                        }
17242                    }
17243                } else if (!ps.getInstantApp(user.getIdentifier())) {
17244                    // can't downgrade from full to instant
17245                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17246                            + " for user: " + user.getIdentifier());
17247                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17248                    return;
17249                }
17250            }
17251        }
17252
17253        // Update what is removed
17254        res.removedInfo = new PackageRemovedInfo(this);
17255        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17256        res.removedInfo.removedPackage = oldPackage.packageName;
17257        res.removedInfo.installerPackageName = ps.installerPackageName;
17258        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17259        res.removedInfo.isUpdate = true;
17260        res.removedInfo.origUsers = installedUsers;
17261        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17262        for (int i = 0; i < installedUsers.length; i++) {
17263            final int userId = installedUsers[i];
17264            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17265        }
17266
17267        final int childCount = (oldPackage.childPackages != null)
17268                ? oldPackage.childPackages.size() : 0;
17269        for (int i = 0; i < childCount; i++) {
17270            boolean childPackageUpdated = false;
17271            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17272            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17273            if (res.addedChildPackages != null) {
17274                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17275                if (childRes != null) {
17276                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17277                    childRes.removedInfo.removedPackage = childPkg.packageName;
17278                    if (childPs != null) {
17279                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17280                    }
17281                    childRes.removedInfo.isUpdate = true;
17282                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17283                    childPackageUpdated = true;
17284                }
17285            }
17286            if (!childPackageUpdated) {
17287                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17288                childRemovedRes.removedPackage = childPkg.packageName;
17289                if (childPs != null) {
17290                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17291                }
17292                childRemovedRes.isUpdate = false;
17293                childRemovedRes.dataRemoved = true;
17294                synchronized (mPackages) {
17295                    if (childPs != null) {
17296                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17297                    }
17298                }
17299                if (res.removedInfo.removedChildPackages == null) {
17300                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17301                }
17302                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17303            }
17304        }
17305
17306        boolean sysPkg = (isSystemApp(oldPackage));
17307        if (sysPkg) {
17308            // Set the system/privileged flags as needed
17309            final boolean privileged =
17310                    (oldPackage.applicationInfo.privateFlags
17311                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17312            final int systemPolicyFlags = policyFlags
17313                    | PackageParser.PARSE_IS_SYSTEM
17314                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17315
17316            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17317                    user, allUsers, installerPackageName, res, installReason);
17318        } else {
17319            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17320                    user, allUsers, installerPackageName, res, installReason);
17321        }
17322    }
17323
17324    @Override
17325    public List<String> getPreviousCodePaths(String packageName) {
17326        final int callingUid = Binder.getCallingUid();
17327        final List<String> result = new ArrayList<>();
17328        if (getInstantAppPackageName(callingUid) != null) {
17329            return result;
17330        }
17331        final PackageSetting ps = mSettings.mPackages.get(packageName);
17332        if (ps != null
17333                && ps.oldCodePaths != null
17334                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17335            result.addAll(ps.oldCodePaths);
17336        }
17337        return result;
17338    }
17339
17340    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17341            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17342            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17343            int installReason) {
17344        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17345                + deletedPackage);
17346
17347        String pkgName = deletedPackage.packageName;
17348        boolean deletedPkg = true;
17349        boolean addedPkg = false;
17350        boolean updatedSettings = false;
17351        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17352        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17353                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17354
17355        final long origUpdateTime = (pkg.mExtras != null)
17356                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17357
17358        // First delete the existing package while retaining the data directory
17359        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17360                res.removedInfo, true, pkg)) {
17361            // If the existing package wasn't successfully deleted
17362            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17363            deletedPkg = false;
17364        } else {
17365            // Successfully deleted the old package; proceed with replace.
17366
17367            // If deleted package lived in a container, give users a chance to
17368            // relinquish resources before killing.
17369            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17370                if (DEBUG_INSTALL) {
17371                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17372                }
17373                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17374                final ArrayList<String> pkgList = new ArrayList<String>(1);
17375                pkgList.add(deletedPackage.applicationInfo.packageName);
17376                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17377            }
17378
17379            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17380                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17381            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17382
17383            try {
17384                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17385                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17386                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17387                        installReason);
17388
17389                // Update the in-memory copy of the previous code paths.
17390                PackageSetting ps = mSettings.mPackages.get(pkgName);
17391                if (!killApp) {
17392                    if (ps.oldCodePaths == null) {
17393                        ps.oldCodePaths = new ArraySet<>();
17394                    }
17395                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17396                    if (deletedPackage.splitCodePaths != null) {
17397                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17398                    }
17399                } else {
17400                    ps.oldCodePaths = null;
17401                }
17402                if (ps.childPackageNames != null) {
17403                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17404                        final String childPkgName = ps.childPackageNames.get(i);
17405                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17406                        childPs.oldCodePaths = ps.oldCodePaths;
17407                    }
17408                }
17409                // set instant app status, but, only if it's explicitly specified
17410                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17411                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17412                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17413                prepareAppDataAfterInstallLIF(newPackage);
17414                addedPkg = true;
17415                mDexManager.notifyPackageUpdated(newPackage.packageName,
17416                        newPackage.baseCodePath, newPackage.splitCodePaths);
17417            } catch (PackageManagerException e) {
17418                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17419            }
17420        }
17421
17422        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17423            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17424
17425            // Revert all internal state mutations and added folders for the failed install
17426            if (addedPkg) {
17427                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17428                        res.removedInfo, true, null);
17429            }
17430
17431            // Restore the old package
17432            if (deletedPkg) {
17433                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17434                File restoreFile = new File(deletedPackage.codePath);
17435                // Parse old package
17436                boolean oldExternal = isExternal(deletedPackage);
17437                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17438                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17439                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17440                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17441                try {
17442                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17443                            null);
17444                } catch (PackageManagerException e) {
17445                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17446                            + e.getMessage());
17447                    return;
17448                }
17449
17450                synchronized (mPackages) {
17451                    // Ensure the installer package name up to date
17452                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17453
17454                    // Update permissions for restored package
17455                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17456
17457                    mSettings.writeLPr();
17458                }
17459
17460                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17461            }
17462        } else {
17463            synchronized (mPackages) {
17464                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17465                if (ps != null) {
17466                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17467                    if (res.removedInfo.removedChildPackages != null) {
17468                        final int childCount = res.removedInfo.removedChildPackages.size();
17469                        // Iterate in reverse as we may modify the collection
17470                        for (int i = childCount - 1; i >= 0; i--) {
17471                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17472                            if (res.addedChildPackages.containsKey(childPackageName)) {
17473                                res.removedInfo.removedChildPackages.removeAt(i);
17474                            } else {
17475                                PackageRemovedInfo childInfo = res.removedInfo
17476                                        .removedChildPackages.valueAt(i);
17477                                childInfo.removedForAllUsers = mPackages.get(
17478                                        childInfo.removedPackage) == null;
17479                            }
17480                        }
17481                    }
17482                }
17483            }
17484        }
17485    }
17486
17487    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17488            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17489            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17490            int installReason) {
17491        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17492                + ", old=" + deletedPackage);
17493
17494        final boolean disabledSystem;
17495
17496        // Remove existing system package
17497        removePackageLI(deletedPackage, true);
17498
17499        synchronized (mPackages) {
17500            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17501        }
17502        if (!disabledSystem) {
17503            // We didn't need to disable the .apk as a current system package,
17504            // which means we are replacing another update that is already
17505            // installed.  We need to make sure to delete the older one's .apk.
17506            res.removedInfo.args = createInstallArgsForExisting(0,
17507                    deletedPackage.applicationInfo.getCodePath(),
17508                    deletedPackage.applicationInfo.getResourcePath(),
17509                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17510        } else {
17511            res.removedInfo.args = null;
17512        }
17513
17514        // Successfully disabled the old package. Now proceed with re-installation
17515        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17516                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17517        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17518
17519        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17520        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17521                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17522
17523        PackageParser.Package newPackage = null;
17524        try {
17525            // Add the package to the internal data structures
17526            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17527
17528            // Set the update and install times
17529            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17530            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17531                    System.currentTimeMillis());
17532
17533            // Update the package dynamic state if succeeded
17534            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17535                // Now that the install succeeded make sure we remove data
17536                // directories for any child package the update removed.
17537                final int deletedChildCount = (deletedPackage.childPackages != null)
17538                        ? deletedPackage.childPackages.size() : 0;
17539                final int newChildCount = (newPackage.childPackages != null)
17540                        ? newPackage.childPackages.size() : 0;
17541                for (int i = 0; i < deletedChildCount; i++) {
17542                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17543                    boolean childPackageDeleted = true;
17544                    for (int j = 0; j < newChildCount; j++) {
17545                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17546                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17547                            childPackageDeleted = false;
17548                            break;
17549                        }
17550                    }
17551                    if (childPackageDeleted) {
17552                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17553                                deletedChildPkg.packageName);
17554                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17555                            PackageRemovedInfo removedChildRes = res.removedInfo
17556                                    .removedChildPackages.get(deletedChildPkg.packageName);
17557                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17558                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17559                        }
17560                    }
17561                }
17562
17563                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17564                        installReason);
17565                prepareAppDataAfterInstallLIF(newPackage);
17566
17567                mDexManager.notifyPackageUpdated(newPackage.packageName,
17568                            newPackage.baseCodePath, newPackage.splitCodePaths);
17569            }
17570        } catch (PackageManagerException e) {
17571            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17572            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17573        }
17574
17575        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17576            // Re installation failed. Restore old information
17577            // Remove new pkg information
17578            if (newPackage != null) {
17579                removeInstalledPackageLI(newPackage, true);
17580            }
17581            // Add back the old system package
17582            try {
17583                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17584            } catch (PackageManagerException e) {
17585                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17586            }
17587
17588            synchronized (mPackages) {
17589                if (disabledSystem) {
17590                    enableSystemPackageLPw(deletedPackage);
17591                }
17592
17593                // Ensure the installer package name up to date
17594                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17595
17596                // Update permissions for restored package
17597                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17598
17599                mSettings.writeLPr();
17600            }
17601
17602            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17603                    + " after failed upgrade");
17604        }
17605    }
17606
17607    /**
17608     * Checks whether the parent or any of the child packages have a change shared
17609     * user. For a package to be a valid update the shred users of the parent and
17610     * the children should match. We may later support changing child shared users.
17611     * @param oldPkg The updated package.
17612     * @param newPkg The update package.
17613     * @return The shared user that change between the versions.
17614     */
17615    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17616            PackageParser.Package newPkg) {
17617        // Check parent shared user
17618        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17619            return newPkg.packageName;
17620        }
17621        // Check child shared users
17622        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17623        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17624        for (int i = 0; i < newChildCount; i++) {
17625            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17626            // If this child was present, did it have the same shared user?
17627            for (int j = 0; j < oldChildCount; j++) {
17628                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17629                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17630                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17631                    return newChildPkg.packageName;
17632                }
17633            }
17634        }
17635        return null;
17636    }
17637
17638    private void removeNativeBinariesLI(PackageSetting ps) {
17639        // Remove the lib path for the parent package
17640        if (ps != null) {
17641            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17642            // Remove the lib path for the child packages
17643            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17644            for (int i = 0; i < childCount; i++) {
17645                PackageSetting childPs = null;
17646                synchronized (mPackages) {
17647                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17648                }
17649                if (childPs != null) {
17650                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17651                            .legacyNativeLibraryPathString);
17652                }
17653            }
17654        }
17655    }
17656
17657    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17658        // Enable the parent package
17659        mSettings.enableSystemPackageLPw(pkg.packageName);
17660        // Enable the child packages
17661        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17662        for (int i = 0; i < childCount; i++) {
17663            PackageParser.Package childPkg = pkg.childPackages.get(i);
17664            mSettings.enableSystemPackageLPw(childPkg.packageName);
17665        }
17666    }
17667
17668    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17669            PackageParser.Package newPkg) {
17670        // Disable the parent package (parent always replaced)
17671        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17672        // Disable the child packages
17673        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17674        for (int i = 0; i < childCount; i++) {
17675            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17676            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17677            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17678        }
17679        return disabled;
17680    }
17681
17682    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17683            String installerPackageName) {
17684        // Enable the parent package
17685        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17686        // Enable the child packages
17687        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17688        for (int i = 0; i < childCount; i++) {
17689            PackageParser.Package childPkg = pkg.childPackages.get(i);
17690            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17691        }
17692    }
17693
17694    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17695        // Collect all used permissions in the UID
17696        ArraySet<String> usedPermissions = new ArraySet<>();
17697        final int packageCount = su.packages.size();
17698        for (int i = 0; i < packageCount; i++) {
17699            PackageSetting ps = su.packages.valueAt(i);
17700            if (ps.pkg == null) {
17701                continue;
17702            }
17703            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17704            for (int j = 0; j < requestedPermCount; j++) {
17705                String permission = ps.pkg.requestedPermissions.get(j);
17706                BasePermission bp = mSettings.mPermissions.get(permission);
17707                if (bp != null) {
17708                    usedPermissions.add(permission);
17709                }
17710            }
17711        }
17712
17713        PermissionsState permissionsState = su.getPermissionsState();
17714        // Prune install permissions
17715        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17716        final int installPermCount = installPermStates.size();
17717        for (int i = installPermCount - 1; i >= 0;  i--) {
17718            PermissionState permissionState = installPermStates.get(i);
17719            if (!usedPermissions.contains(permissionState.getName())) {
17720                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17721                if (bp != null) {
17722                    permissionsState.revokeInstallPermission(bp);
17723                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17724                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17725                }
17726            }
17727        }
17728
17729        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17730
17731        // Prune runtime permissions
17732        for (int userId : allUserIds) {
17733            List<PermissionState> runtimePermStates = permissionsState
17734                    .getRuntimePermissionStates(userId);
17735            final int runtimePermCount = runtimePermStates.size();
17736            for (int i = runtimePermCount - 1; i >= 0; i--) {
17737                PermissionState permissionState = runtimePermStates.get(i);
17738                if (!usedPermissions.contains(permissionState.getName())) {
17739                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17740                    if (bp != null) {
17741                        permissionsState.revokeRuntimePermission(bp, userId);
17742                        permissionsState.updatePermissionFlags(bp, userId,
17743                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17744                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17745                                runtimePermissionChangedUserIds, userId);
17746                    }
17747                }
17748            }
17749        }
17750
17751        return runtimePermissionChangedUserIds;
17752    }
17753
17754    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17755            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17756        // Update the parent package setting
17757        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17758                res, user, installReason);
17759        // Update the child packages setting
17760        final int childCount = (newPackage.childPackages != null)
17761                ? newPackage.childPackages.size() : 0;
17762        for (int i = 0; i < childCount; i++) {
17763            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17764            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17765            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17766                    childRes.origUsers, childRes, user, installReason);
17767        }
17768    }
17769
17770    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17771            String installerPackageName, int[] allUsers, int[] installedForUsers,
17772            PackageInstalledInfo res, UserHandle user, int installReason) {
17773        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17774
17775        String pkgName = newPackage.packageName;
17776        synchronized (mPackages) {
17777            //write settings. the installStatus will be incomplete at this stage.
17778            //note that the new package setting would have already been
17779            //added to mPackages. It hasn't been persisted yet.
17780            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17781            // TODO: Remove this write? It's also written at the end of this method
17782            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17783            mSettings.writeLPr();
17784            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17785        }
17786
17787        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17788        synchronized (mPackages) {
17789            updatePermissionsLPw(newPackage.packageName, newPackage,
17790                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17791                            ? UPDATE_PERMISSIONS_ALL : 0));
17792            // For system-bundled packages, we assume that installing an upgraded version
17793            // of the package implies that the user actually wants to run that new code,
17794            // so we enable the package.
17795            PackageSetting ps = mSettings.mPackages.get(pkgName);
17796            final int userId = user.getIdentifier();
17797            if (ps != null) {
17798                if (isSystemApp(newPackage)) {
17799                    if (DEBUG_INSTALL) {
17800                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17801                    }
17802                    // Enable system package for requested users
17803                    if (res.origUsers != null) {
17804                        for (int origUserId : res.origUsers) {
17805                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17806                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17807                                        origUserId, installerPackageName);
17808                            }
17809                        }
17810                    }
17811                    // Also convey the prior install/uninstall state
17812                    if (allUsers != null && installedForUsers != null) {
17813                        for (int currentUserId : allUsers) {
17814                            final boolean installed = ArrayUtils.contains(
17815                                    installedForUsers, currentUserId);
17816                            if (DEBUG_INSTALL) {
17817                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17818                            }
17819                            ps.setInstalled(installed, currentUserId);
17820                        }
17821                        // these install state changes will be persisted in the
17822                        // upcoming call to mSettings.writeLPr().
17823                    }
17824                }
17825                // It's implied that when a user requests installation, they want the app to be
17826                // installed and enabled.
17827                if (userId != UserHandle.USER_ALL) {
17828                    ps.setInstalled(true, userId);
17829                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17830                }
17831
17832                // When replacing an existing package, preserve the original install reason for all
17833                // users that had the package installed before.
17834                final Set<Integer> previousUserIds = new ArraySet<>();
17835                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17836                    final int installReasonCount = res.removedInfo.installReasons.size();
17837                    for (int i = 0; i < installReasonCount; i++) {
17838                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17839                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17840                        ps.setInstallReason(previousInstallReason, previousUserId);
17841                        previousUserIds.add(previousUserId);
17842                    }
17843                }
17844
17845                // Set install reason for users that are having the package newly installed.
17846                if (userId == UserHandle.USER_ALL) {
17847                    for (int currentUserId : sUserManager.getUserIds()) {
17848                        if (!previousUserIds.contains(currentUserId)) {
17849                            ps.setInstallReason(installReason, currentUserId);
17850                        }
17851                    }
17852                } else if (!previousUserIds.contains(userId)) {
17853                    ps.setInstallReason(installReason, userId);
17854                }
17855                mSettings.writeKernelMappingLPr(ps);
17856            }
17857            res.name = pkgName;
17858            res.uid = newPackage.applicationInfo.uid;
17859            res.pkg = newPackage;
17860            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17861            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17862            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17863            //to update install status
17864            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17865            mSettings.writeLPr();
17866            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17867        }
17868
17869        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17870    }
17871
17872    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17873        try {
17874            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17875            installPackageLI(args, res);
17876        } finally {
17877            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17878        }
17879    }
17880
17881    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17882        final int installFlags = args.installFlags;
17883        final String installerPackageName = args.installerPackageName;
17884        final String volumeUuid = args.volumeUuid;
17885        final File tmpPackageFile = new File(args.getCodePath());
17886        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17887        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17888                || (args.volumeUuid != null));
17889        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17890        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17891        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17892        boolean replace = false;
17893        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17894        if (args.move != null) {
17895            // moving a complete application; perform an initial scan on the new install location
17896            scanFlags |= SCAN_INITIAL;
17897        }
17898        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17899            scanFlags |= SCAN_DONT_KILL_APP;
17900        }
17901        if (instantApp) {
17902            scanFlags |= SCAN_AS_INSTANT_APP;
17903        }
17904        if (fullApp) {
17905            scanFlags |= SCAN_AS_FULL_APP;
17906        }
17907
17908        // Result object to be returned
17909        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17910
17911        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17912
17913        // Sanity check
17914        if (instantApp && (forwardLocked || onExternal)) {
17915            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17916                    + " external=" + onExternal);
17917            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17918            return;
17919        }
17920
17921        // Retrieve PackageSettings and parse package
17922        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17923                | PackageParser.PARSE_ENFORCE_CODE
17924                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17925                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17926                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17927                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17928        PackageParser pp = new PackageParser();
17929        pp.setSeparateProcesses(mSeparateProcesses);
17930        pp.setDisplayMetrics(mMetrics);
17931        pp.setCallback(mPackageParserCallback);
17932
17933        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17934        final PackageParser.Package pkg;
17935        try {
17936            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17937        } catch (PackageParserException e) {
17938            res.setError("Failed parse during installPackageLI", e);
17939            return;
17940        } finally {
17941            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17942        }
17943
17944        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17945        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17946            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17947            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17948                    "Instant app package must target O");
17949            return;
17950        }
17951        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17952            Slog.w(TAG, "Instant app package " + pkg.packageName
17953                    + " does not target targetSandboxVersion 2");
17954            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17955                    "Instant app package must use targetSanboxVersion 2");
17956            return;
17957        }
17958
17959        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17960            // Static shared libraries have synthetic package names
17961            renameStaticSharedLibraryPackage(pkg);
17962
17963            // No static shared libs on external storage
17964            if (onExternal) {
17965                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17966                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17967                        "Packages declaring static-shared libs cannot be updated");
17968                return;
17969            }
17970        }
17971
17972        // If we are installing a clustered package add results for the children
17973        if (pkg.childPackages != null) {
17974            synchronized (mPackages) {
17975                final int childCount = pkg.childPackages.size();
17976                for (int i = 0; i < childCount; i++) {
17977                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17978                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17979                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17980                    childRes.pkg = childPkg;
17981                    childRes.name = childPkg.packageName;
17982                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17983                    if (childPs != null) {
17984                        childRes.origUsers = childPs.queryInstalledUsers(
17985                                sUserManager.getUserIds(), true);
17986                    }
17987                    if ((mPackages.containsKey(childPkg.packageName))) {
17988                        childRes.removedInfo = new PackageRemovedInfo(this);
17989                        childRes.removedInfo.removedPackage = childPkg.packageName;
17990                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17991                    }
17992                    if (res.addedChildPackages == null) {
17993                        res.addedChildPackages = new ArrayMap<>();
17994                    }
17995                    res.addedChildPackages.put(childPkg.packageName, childRes);
17996                }
17997            }
17998        }
17999
18000        // If package doesn't declare API override, mark that we have an install
18001        // time CPU ABI override.
18002        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18003            pkg.cpuAbiOverride = args.abiOverride;
18004        }
18005
18006        String pkgName = res.name = pkg.packageName;
18007        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18008            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18009                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18010                return;
18011            }
18012        }
18013
18014        try {
18015            // either use what we've been given or parse directly from the APK
18016            if (args.certificates != null) {
18017                try {
18018                    PackageParser.populateCertificates(pkg, args.certificates);
18019                } catch (PackageParserException e) {
18020                    // there was something wrong with the certificates we were given;
18021                    // try to pull them from the APK
18022                    PackageParser.collectCertificates(pkg, parseFlags);
18023                }
18024            } else {
18025                PackageParser.collectCertificates(pkg, parseFlags);
18026            }
18027        } catch (PackageParserException e) {
18028            res.setError("Failed collect during installPackageLI", e);
18029            return;
18030        }
18031
18032        // Get rid of all references to package scan path via parser.
18033        pp = null;
18034        String oldCodePath = null;
18035        boolean systemApp = false;
18036        synchronized (mPackages) {
18037            // Check if installing already existing package
18038            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18039                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18040                if (pkg.mOriginalPackages != null
18041                        && pkg.mOriginalPackages.contains(oldName)
18042                        && mPackages.containsKey(oldName)) {
18043                    // This package is derived from an original package,
18044                    // and this device has been updating from that original
18045                    // name.  We must continue using the original name, so
18046                    // rename the new package here.
18047                    pkg.setPackageName(oldName);
18048                    pkgName = pkg.packageName;
18049                    replace = true;
18050                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18051                            + oldName + " pkgName=" + pkgName);
18052                } else if (mPackages.containsKey(pkgName)) {
18053                    // This package, under its official name, already exists
18054                    // on the device; we should replace it.
18055                    replace = true;
18056                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18057                }
18058
18059                // Child packages are installed through the parent package
18060                if (pkg.parentPackage != null) {
18061                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18062                            "Package " + pkg.packageName + " is child of package "
18063                                    + pkg.parentPackage.parentPackage + ". Child packages "
18064                                    + "can be updated only through the parent package.");
18065                    return;
18066                }
18067
18068                if (replace) {
18069                    // Prevent apps opting out from runtime permissions
18070                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18071                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18072                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18073                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18074                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18075                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18076                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18077                                        + " doesn't support runtime permissions but the old"
18078                                        + " target SDK " + oldTargetSdk + " does.");
18079                        return;
18080                    }
18081                    // Prevent apps from downgrading their targetSandbox.
18082                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18083                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18084                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18085                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18086                                "Package " + pkg.packageName + " new target sandbox "
18087                                + newTargetSandbox + " is incompatible with the previous value of"
18088                                + oldTargetSandbox + ".");
18089                        return;
18090                    }
18091
18092                    // Prevent installing of child packages
18093                    if (oldPackage.parentPackage != null) {
18094                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18095                                "Package " + pkg.packageName + " is child of package "
18096                                        + oldPackage.parentPackage + ". Child packages "
18097                                        + "can be updated only through the parent package.");
18098                        return;
18099                    }
18100                }
18101            }
18102
18103            PackageSetting ps = mSettings.mPackages.get(pkgName);
18104            if (ps != null) {
18105                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18106
18107                // Static shared libs have same package with different versions where
18108                // we internally use a synthetic package name to allow multiple versions
18109                // of the same package, therefore we need to compare signatures against
18110                // the package setting for the latest library version.
18111                PackageSetting signatureCheckPs = ps;
18112                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18113                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18114                    if (libraryEntry != null) {
18115                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18116                    }
18117                }
18118
18119                // Quick sanity check that we're signed correctly if updating;
18120                // we'll check this again later when scanning, but we want to
18121                // bail early here before tripping over redefined permissions.
18122                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18123                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18124                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18125                                + pkg.packageName + " upgrade keys do not match the "
18126                                + "previously installed version");
18127                        return;
18128                    }
18129                } else {
18130                    try {
18131                        verifySignaturesLP(signatureCheckPs, pkg);
18132                    } catch (PackageManagerException e) {
18133                        res.setError(e.error, e.getMessage());
18134                        return;
18135                    }
18136                }
18137
18138                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18139                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18140                    systemApp = (ps.pkg.applicationInfo.flags &
18141                            ApplicationInfo.FLAG_SYSTEM) != 0;
18142                }
18143                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18144            }
18145
18146            int N = pkg.permissions.size();
18147            for (int i = N-1; i >= 0; i--) {
18148                PackageParser.Permission perm = pkg.permissions.get(i);
18149                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18150
18151                // Don't allow anyone but the system to define ephemeral permissions.
18152                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18153                        && !systemApp) {
18154                    Slog.w(TAG, "Non-System package " + pkg.packageName
18155                            + " attempting to delcare ephemeral permission "
18156                            + perm.info.name + "; Removing ephemeral.");
18157                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18158                }
18159                // Check whether the newly-scanned package wants to define an already-defined perm
18160                if (bp != null) {
18161                    // If the defining package is signed with our cert, it's okay.  This
18162                    // also includes the "updating the same package" case, of course.
18163                    // "updating same package" could also involve key-rotation.
18164                    final boolean sigsOk;
18165                    if (bp.sourcePackage.equals(pkg.packageName)
18166                            && (bp.packageSetting instanceof PackageSetting)
18167                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18168                                    scanFlags))) {
18169                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18170                    } else {
18171                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18172                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18173                    }
18174                    if (!sigsOk) {
18175                        // If the owning package is the system itself, we log but allow
18176                        // install to proceed; we fail the install on all other permission
18177                        // redefinitions.
18178                        if (!bp.sourcePackage.equals("android")) {
18179                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18180                                    + pkg.packageName + " attempting to redeclare permission "
18181                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18182                            res.origPermission = perm.info.name;
18183                            res.origPackage = bp.sourcePackage;
18184                            return;
18185                        } else {
18186                            Slog.w(TAG, "Package " + pkg.packageName
18187                                    + " attempting to redeclare system permission "
18188                                    + perm.info.name + "; ignoring new declaration");
18189                            pkg.permissions.remove(i);
18190                        }
18191                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18192                        // Prevent apps to change protection level to dangerous from any other
18193                        // type as this would allow a privilege escalation where an app adds a
18194                        // normal/signature permission in other app's group and later redefines
18195                        // it as dangerous leading to the group auto-grant.
18196                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18197                                == PermissionInfo.PROTECTION_DANGEROUS) {
18198                            if (bp != null && !bp.isRuntime()) {
18199                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18200                                        + "non-runtime permission " + perm.info.name
18201                                        + " to runtime; keeping old protection level");
18202                                perm.info.protectionLevel = bp.protectionLevel;
18203                            }
18204                        }
18205                    }
18206                }
18207            }
18208        }
18209
18210        if (systemApp) {
18211            if (onExternal) {
18212                // Abort update; system app can't be replaced with app on sdcard
18213                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18214                        "Cannot install updates to system apps on sdcard");
18215                return;
18216            } else if (instantApp) {
18217                // Abort update; system app can't be replaced with an instant app
18218                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18219                        "Cannot update a system app with an instant app");
18220                return;
18221            }
18222        }
18223
18224        if (args.move != null) {
18225            // We did an in-place move, so dex is ready to roll
18226            scanFlags |= SCAN_NO_DEX;
18227            scanFlags |= SCAN_MOVE;
18228
18229            synchronized (mPackages) {
18230                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18231                if (ps == null) {
18232                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18233                            "Missing settings for moved package " + pkgName);
18234                }
18235
18236                // We moved the entire application as-is, so bring over the
18237                // previously derived ABI information.
18238                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18239                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18240            }
18241
18242        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18243            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18244            scanFlags |= SCAN_NO_DEX;
18245
18246            try {
18247                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18248                    args.abiOverride : pkg.cpuAbiOverride);
18249                final boolean extractNativeLibs = !pkg.isLibrary();
18250                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18251                        extractNativeLibs, mAppLib32InstallDir);
18252            } catch (PackageManagerException pme) {
18253                Slog.e(TAG, "Error deriving application ABI", pme);
18254                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18255                return;
18256            }
18257
18258            // Shared libraries for the package need to be updated.
18259            synchronized (mPackages) {
18260                try {
18261                    updateSharedLibrariesLPr(pkg, null);
18262                } catch (PackageManagerException e) {
18263                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18264                }
18265            }
18266        }
18267
18268        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18269            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18270            return;
18271        }
18272
18273        // Verify if we need to dexopt the app.
18274        //
18275        // NOTE: it is *important* to call dexopt after doRename which will sync the
18276        // package data from PackageParser.Package and its corresponding ApplicationInfo.
18277        //
18278        // We only need to dexopt if the package meets ALL of the following conditions:
18279        //   1) it is not forward locked.
18280        //   2) it is not on on an external ASEC container.
18281        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18282        //
18283        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18284        // complete, so we skip this step during installation. Instead, we'll take extra time
18285        // the first time the instant app starts. It's preferred to do it this way to provide
18286        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18287        // middle of running an instant app. The default behaviour can be overridden
18288        // via gservices.
18289        final boolean performDexopt = !forwardLocked
18290            && !pkg.applicationInfo.isExternalAsec()
18291            && (!instantApp || Global.getInt(mContext.getContentResolver(),
18292                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18293
18294        if (performDexopt) {
18295            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18296            // Do not run PackageDexOptimizer through the local performDexOpt
18297            // method because `pkg` may not be in `mPackages` yet.
18298            //
18299            // Also, don't fail application installs if the dexopt step fails.
18300            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18301                REASON_INSTALL,
18302                DexoptOptions.DEXOPT_BOOT_COMPLETE);
18303            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18304                null /* instructionSets */,
18305                getOrCreateCompilerPackageStats(pkg),
18306                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18307                dexoptOptions);
18308            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18309        }
18310
18311        // Notify BackgroundDexOptService that the package has been changed.
18312        // If this is an update of a package which used to fail to compile,
18313        // BackgroundDexOptService will remove it from its blacklist.
18314        // TODO: Layering violation
18315        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18316
18317        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18318
18319        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18320                "installPackageLI")) {
18321            if (replace) {
18322                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18323                    // Static libs have a synthetic package name containing the version
18324                    // and cannot be updated as an update would get a new package name,
18325                    // unless this is the exact same version code which is useful for
18326                    // development.
18327                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18328                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18329                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18330                                + "static-shared libs cannot be updated");
18331                        return;
18332                    }
18333                }
18334                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18335                        installerPackageName, res, args.installReason);
18336            } else {
18337                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18338                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18339            }
18340        }
18341
18342        synchronized (mPackages) {
18343            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18344            if (ps != null) {
18345                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18346                ps.setUpdateAvailable(false /*updateAvailable*/);
18347            }
18348
18349            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18350            for (int i = 0; i < childCount; i++) {
18351                PackageParser.Package childPkg = pkg.childPackages.get(i);
18352                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18353                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18354                if (childPs != null) {
18355                    childRes.newUsers = childPs.queryInstalledUsers(
18356                            sUserManager.getUserIds(), true);
18357                }
18358            }
18359
18360            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18361                updateSequenceNumberLP(ps, res.newUsers);
18362                updateInstantAppInstallerLocked(pkgName);
18363            }
18364        }
18365    }
18366
18367    private void startIntentFilterVerifications(int userId, boolean replacing,
18368            PackageParser.Package pkg) {
18369        if (mIntentFilterVerifierComponent == null) {
18370            Slog.w(TAG, "No IntentFilter verification will not be done as "
18371                    + "there is no IntentFilterVerifier available!");
18372            return;
18373        }
18374
18375        final int verifierUid = getPackageUid(
18376                mIntentFilterVerifierComponent.getPackageName(),
18377                MATCH_DEBUG_TRIAGED_MISSING,
18378                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18379
18380        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18381        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18382        mHandler.sendMessage(msg);
18383
18384        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18385        for (int i = 0; i < childCount; i++) {
18386            PackageParser.Package childPkg = pkg.childPackages.get(i);
18387            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18388            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18389            mHandler.sendMessage(msg);
18390        }
18391    }
18392
18393    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18394            PackageParser.Package pkg) {
18395        int size = pkg.activities.size();
18396        if (size == 0) {
18397            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18398                    "No activity, so no need to verify any IntentFilter!");
18399            return;
18400        }
18401
18402        final boolean hasDomainURLs = hasDomainURLs(pkg);
18403        if (!hasDomainURLs) {
18404            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18405                    "No domain URLs, so no need to verify any IntentFilter!");
18406            return;
18407        }
18408
18409        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18410                + " if any IntentFilter from the " + size
18411                + " Activities needs verification ...");
18412
18413        int count = 0;
18414        final String packageName = pkg.packageName;
18415
18416        synchronized (mPackages) {
18417            // If this is a new install and we see that we've already run verification for this
18418            // package, we have nothing to do: it means the state was restored from backup.
18419            if (!replacing) {
18420                IntentFilterVerificationInfo ivi =
18421                        mSettings.getIntentFilterVerificationLPr(packageName);
18422                if (ivi != null) {
18423                    if (DEBUG_DOMAIN_VERIFICATION) {
18424                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18425                                + ivi.getStatusString());
18426                    }
18427                    return;
18428                }
18429            }
18430
18431            // If any filters need to be verified, then all need to be.
18432            boolean needToVerify = false;
18433            for (PackageParser.Activity a : pkg.activities) {
18434                for (ActivityIntentInfo filter : a.intents) {
18435                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18436                        if (DEBUG_DOMAIN_VERIFICATION) {
18437                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18438                        }
18439                        needToVerify = true;
18440                        break;
18441                    }
18442                }
18443            }
18444
18445            if (needToVerify) {
18446                final int verificationId = mIntentFilterVerificationToken++;
18447                for (PackageParser.Activity a : pkg.activities) {
18448                    for (ActivityIntentInfo filter : a.intents) {
18449                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18450                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18451                                    "Verification needed for IntentFilter:" + filter.toString());
18452                            mIntentFilterVerifier.addOneIntentFilterVerification(
18453                                    verifierUid, userId, verificationId, filter, packageName);
18454                            count++;
18455                        }
18456                    }
18457                }
18458            }
18459        }
18460
18461        if (count > 0) {
18462            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18463                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18464                    +  " for userId:" + userId);
18465            mIntentFilterVerifier.startVerifications(userId);
18466        } else {
18467            if (DEBUG_DOMAIN_VERIFICATION) {
18468                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18469            }
18470        }
18471    }
18472
18473    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18474        final ComponentName cn  = filter.activity.getComponentName();
18475        final String packageName = cn.getPackageName();
18476
18477        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18478                packageName);
18479        if (ivi == null) {
18480            return true;
18481        }
18482        int status = ivi.getStatus();
18483        switch (status) {
18484            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18485            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18486                return true;
18487
18488            default:
18489                // Nothing to do
18490                return false;
18491        }
18492    }
18493
18494    private static boolean isMultiArch(ApplicationInfo info) {
18495        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18496    }
18497
18498    private static boolean isExternal(PackageParser.Package pkg) {
18499        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18500    }
18501
18502    private static boolean isExternal(PackageSetting ps) {
18503        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18504    }
18505
18506    private static boolean isSystemApp(PackageParser.Package pkg) {
18507        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18508    }
18509
18510    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18511        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18512    }
18513
18514    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18515        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18516    }
18517
18518    private static boolean isSystemApp(PackageSetting ps) {
18519        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18520    }
18521
18522    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18523        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18524    }
18525
18526    private int packageFlagsToInstallFlags(PackageSetting ps) {
18527        int installFlags = 0;
18528        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18529            // This existing package was an external ASEC install when we have
18530            // the external flag without a UUID
18531            installFlags |= PackageManager.INSTALL_EXTERNAL;
18532        }
18533        if (ps.isForwardLocked()) {
18534            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18535        }
18536        return installFlags;
18537    }
18538
18539    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18540        if (isExternal(pkg)) {
18541            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18542                return StorageManager.UUID_PRIMARY_PHYSICAL;
18543            } else {
18544                return pkg.volumeUuid;
18545            }
18546        } else {
18547            return StorageManager.UUID_PRIVATE_INTERNAL;
18548        }
18549    }
18550
18551    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18552        if (isExternal(pkg)) {
18553            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18554                return mSettings.getExternalVersion();
18555            } else {
18556                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18557            }
18558        } else {
18559            return mSettings.getInternalVersion();
18560        }
18561    }
18562
18563    private void deleteTempPackageFiles() {
18564        final FilenameFilter filter = new FilenameFilter() {
18565            public boolean accept(File dir, String name) {
18566                return name.startsWith("vmdl") && name.endsWith(".tmp");
18567            }
18568        };
18569        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18570            file.delete();
18571        }
18572    }
18573
18574    @Override
18575    public void deletePackageAsUser(String packageName, int versionCode,
18576            IPackageDeleteObserver observer, int userId, int flags) {
18577        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18578                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18579    }
18580
18581    @Override
18582    public void deletePackageVersioned(VersionedPackage versionedPackage,
18583            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18584        final int callingUid = Binder.getCallingUid();
18585        mContext.enforceCallingOrSelfPermission(
18586                android.Manifest.permission.DELETE_PACKAGES, null);
18587        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18588        Preconditions.checkNotNull(versionedPackage);
18589        Preconditions.checkNotNull(observer);
18590        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18591                PackageManager.VERSION_CODE_HIGHEST,
18592                Integer.MAX_VALUE, "versionCode must be >= -1");
18593
18594        final String packageName = versionedPackage.getPackageName();
18595        final int versionCode = versionedPackage.getVersionCode();
18596        final String internalPackageName;
18597        synchronized (mPackages) {
18598            // Normalize package name to handle renamed packages and static libs
18599            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18600                    versionedPackage.getVersionCode());
18601        }
18602
18603        final int uid = Binder.getCallingUid();
18604        if (!isOrphaned(internalPackageName)
18605                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18606            try {
18607                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18608                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18609                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18610                observer.onUserActionRequired(intent);
18611            } catch (RemoteException re) {
18612            }
18613            return;
18614        }
18615        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18616        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18617        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18618            mContext.enforceCallingOrSelfPermission(
18619                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18620                    "deletePackage for user " + userId);
18621        }
18622
18623        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18624            try {
18625                observer.onPackageDeleted(packageName,
18626                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18627            } catch (RemoteException re) {
18628            }
18629            return;
18630        }
18631
18632        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18633            try {
18634                observer.onPackageDeleted(packageName,
18635                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18636            } catch (RemoteException re) {
18637            }
18638            return;
18639        }
18640
18641        if (DEBUG_REMOVE) {
18642            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18643                    + " deleteAllUsers: " + deleteAllUsers + " version="
18644                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18645                    ? "VERSION_CODE_HIGHEST" : versionCode));
18646        }
18647        // Queue up an async operation since the package deletion may take a little while.
18648        mHandler.post(new Runnable() {
18649            public void run() {
18650                mHandler.removeCallbacks(this);
18651                int returnCode;
18652                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18653                boolean doDeletePackage = true;
18654                if (ps != null) {
18655                    final boolean targetIsInstantApp =
18656                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18657                    doDeletePackage = !targetIsInstantApp
18658                            || canViewInstantApps;
18659                }
18660                if (doDeletePackage) {
18661                    if (!deleteAllUsers) {
18662                        returnCode = deletePackageX(internalPackageName, versionCode,
18663                                userId, deleteFlags);
18664                    } else {
18665                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18666                                internalPackageName, users);
18667                        // If nobody is blocking uninstall, proceed with delete for all users
18668                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18669                            returnCode = deletePackageX(internalPackageName, versionCode,
18670                                    userId, deleteFlags);
18671                        } else {
18672                            // Otherwise uninstall individually for users with blockUninstalls=false
18673                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18674                            for (int userId : users) {
18675                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18676                                    returnCode = deletePackageX(internalPackageName, versionCode,
18677                                            userId, userFlags);
18678                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18679                                        Slog.w(TAG, "Package delete failed for user " + userId
18680                                                + ", returnCode " + returnCode);
18681                                    }
18682                                }
18683                            }
18684                            // The app has only been marked uninstalled for certain users.
18685                            // We still need to report that delete was blocked
18686                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18687                        }
18688                    }
18689                } else {
18690                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18691                }
18692                try {
18693                    observer.onPackageDeleted(packageName, returnCode, null);
18694                } catch (RemoteException e) {
18695                    Log.i(TAG, "Observer no longer exists.");
18696                } //end catch
18697            } //end run
18698        });
18699    }
18700
18701    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18702        if (pkg.staticSharedLibName != null) {
18703            return pkg.manifestPackageName;
18704        }
18705        return pkg.packageName;
18706    }
18707
18708    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18709        // Handle renamed packages
18710        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18711        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18712
18713        // Is this a static library?
18714        SparseArray<SharedLibraryEntry> versionedLib =
18715                mStaticLibsByDeclaringPackage.get(packageName);
18716        if (versionedLib == null || versionedLib.size() <= 0) {
18717            return packageName;
18718        }
18719
18720        // Figure out which lib versions the caller can see
18721        SparseIntArray versionsCallerCanSee = null;
18722        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18723        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18724                && callingAppId != Process.ROOT_UID) {
18725            versionsCallerCanSee = new SparseIntArray();
18726            String libName = versionedLib.valueAt(0).info.getName();
18727            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18728            if (uidPackages != null) {
18729                for (String uidPackage : uidPackages) {
18730                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18731                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18732                    if (libIdx >= 0) {
18733                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18734                        versionsCallerCanSee.append(libVersion, libVersion);
18735                    }
18736                }
18737            }
18738        }
18739
18740        // Caller can see nothing - done
18741        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18742            return packageName;
18743        }
18744
18745        // Find the version the caller can see and the app version code
18746        SharedLibraryEntry highestVersion = null;
18747        final int versionCount = versionedLib.size();
18748        for (int i = 0; i < versionCount; i++) {
18749            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18750            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18751                    libEntry.info.getVersion()) < 0) {
18752                continue;
18753            }
18754            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18755            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18756                if (libVersionCode == versionCode) {
18757                    return libEntry.apk;
18758                }
18759            } else if (highestVersion == null) {
18760                highestVersion = libEntry;
18761            } else if (libVersionCode  > highestVersion.info
18762                    .getDeclaringPackage().getVersionCode()) {
18763                highestVersion = libEntry;
18764            }
18765        }
18766
18767        if (highestVersion != null) {
18768            return highestVersion.apk;
18769        }
18770
18771        return packageName;
18772    }
18773
18774    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18775        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18776              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18777            return true;
18778        }
18779        final int callingUserId = UserHandle.getUserId(callingUid);
18780        // If the caller installed the pkgName, then allow it to silently uninstall.
18781        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18782            return true;
18783        }
18784
18785        // Allow package verifier to silently uninstall.
18786        if (mRequiredVerifierPackage != null &&
18787                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18788            return true;
18789        }
18790
18791        // Allow package uninstaller to silently uninstall.
18792        if (mRequiredUninstallerPackage != null &&
18793                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18794            return true;
18795        }
18796
18797        // Allow storage manager to silently uninstall.
18798        if (mStorageManagerPackage != null &&
18799                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18800            return true;
18801        }
18802
18803        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18804        // uninstall for device owner provisioning.
18805        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18806                == PERMISSION_GRANTED) {
18807            return true;
18808        }
18809
18810        return false;
18811    }
18812
18813    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18814        int[] result = EMPTY_INT_ARRAY;
18815        for (int userId : userIds) {
18816            if (getBlockUninstallForUser(packageName, userId)) {
18817                result = ArrayUtils.appendInt(result, userId);
18818            }
18819        }
18820        return result;
18821    }
18822
18823    @Override
18824    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18825        final int callingUid = Binder.getCallingUid();
18826        if (getInstantAppPackageName(callingUid) != null
18827                && !isCallerSameApp(packageName, callingUid)) {
18828            return false;
18829        }
18830        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18831    }
18832
18833    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18834        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18835                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18836        try {
18837            if (dpm != null) {
18838                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18839                        /* callingUserOnly =*/ false);
18840                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18841                        : deviceOwnerComponentName.getPackageName();
18842                // Does the package contains the device owner?
18843                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18844                // this check is probably not needed, since DO should be registered as a device
18845                // admin on some user too. (Original bug for this: b/17657954)
18846                if (packageName.equals(deviceOwnerPackageName)) {
18847                    return true;
18848                }
18849                // Does it contain a device admin for any user?
18850                int[] users;
18851                if (userId == UserHandle.USER_ALL) {
18852                    users = sUserManager.getUserIds();
18853                } else {
18854                    users = new int[]{userId};
18855                }
18856                for (int i = 0; i < users.length; ++i) {
18857                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18858                        return true;
18859                    }
18860                }
18861            }
18862        } catch (RemoteException e) {
18863        }
18864        return false;
18865    }
18866
18867    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18868        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18869    }
18870
18871    /**
18872     *  This method is an internal method that could be get invoked either
18873     *  to delete an installed package or to clean up a failed installation.
18874     *  After deleting an installed package, a broadcast is sent to notify any
18875     *  listeners that the package has been removed. For cleaning up a failed
18876     *  installation, the broadcast is not necessary since the package's
18877     *  installation wouldn't have sent the initial broadcast either
18878     *  The key steps in deleting a package are
18879     *  deleting the package information in internal structures like mPackages,
18880     *  deleting the packages base directories through installd
18881     *  updating mSettings to reflect current status
18882     *  persisting settings for later use
18883     *  sending a broadcast if necessary
18884     */
18885    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18886        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18887        final boolean res;
18888
18889        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18890                ? UserHandle.USER_ALL : userId;
18891
18892        if (isPackageDeviceAdmin(packageName, removeUser)) {
18893            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18894            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18895        }
18896
18897        PackageSetting uninstalledPs = null;
18898        PackageParser.Package pkg = null;
18899
18900        // for the uninstall-updates case and restricted profiles, remember the per-
18901        // user handle installed state
18902        int[] allUsers;
18903        synchronized (mPackages) {
18904            uninstalledPs = mSettings.mPackages.get(packageName);
18905            if (uninstalledPs == null) {
18906                Slog.w(TAG, "Not removing non-existent package " + packageName);
18907                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18908            }
18909
18910            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18911                    && uninstalledPs.versionCode != versionCode) {
18912                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18913                        + uninstalledPs.versionCode + " != " + versionCode);
18914                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18915            }
18916
18917            // Static shared libs can be declared by any package, so let us not
18918            // allow removing a package if it provides a lib others depend on.
18919            pkg = mPackages.get(packageName);
18920
18921            allUsers = sUserManager.getUserIds();
18922
18923            if (pkg != null && pkg.staticSharedLibName != null) {
18924                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18925                        pkg.staticSharedLibVersion);
18926                if (libEntry != null) {
18927                    for (int currUserId : allUsers) {
18928                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18929                            continue;
18930                        }
18931                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18932                                libEntry.info, 0, currUserId);
18933                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18934                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18935                                    + " hosting lib " + libEntry.info.getName() + " version "
18936                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18937                                    + " for user " + currUserId);
18938                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18939                        }
18940                    }
18941                }
18942            }
18943
18944            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18945        }
18946
18947        final int freezeUser;
18948        if (isUpdatedSystemApp(uninstalledPs)
18949                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18950            // We're downgrading a system app, which will apply to all users, so
18951            // freeze them all during the downgrade
18952            freezeUser = UserHandle.USER_ALL;
18953        } else {
18954            freezeUser = removeUser;
18955        }
18956
18957        synchronized (mInstallLock) {
18958            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18959            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18960                    deleteFlags, "deletePackageX")) {
18961                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18962                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18963            }
18964            synchronized (mPackages) {
18965                if (res) {
18966                    if (pkg != null) {
18967                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18968                    }
18969                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18970                    updateInstantAppInstallerLocked(packageName);
18971                }
18972            }
18973        }
18974
18975        if (res) {
18976            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18977            info.sendPackageRemovedBroadcasts(killApp);
18978            info.sendSystemPackageUpdatedBroadcasts();
18979            info.sendSystemPackageAppearedBroadcasts();
18980        }
18981        // Force a gc here.
18982        Runtime.getRuntime().gc();
18983        // Delete the resources here after sending the broadcast to let
18984        // other processes clean up before deleting resources.
18985        if (info.args != null) {
18986            synchronized (mInstallLock) {
18987                info.args.doPostDeleteLI(true);
18988            }
18989        }
18990
18991        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18992    }
18993
18994    static class PackageRemovedInfo {
18995        final PackageSender packageSender;
18996        String removedPackage;
18997        String installerPackageName;
18998        int uid = -1;
18999        int removedAppId = -1;
19000        int[] origUsers;
19001        int[] removedUsers = null;
19002        int[] broadcastUsers = null;
19003        SparseArray<Integer> installReasons;
19004        boolean isRemovedPackageSystemUpdate = false;
19005        boolean isUpdate;
19006        boolean dataRemoved;
19007        boolean removedForAllUsers;
19008        boolean isStaticSharedLib;
19009        // Clean up resources deleted packages.
19010        InstallArgs args = null;
19011        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19012        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19013
19014        PackageRemovedInfo(PackageSender packageSender) {
19015            this.packageSender = packageSender;
19016        }
19017
19018        void sendPackageRemovedBroadcasts(boolean killApp) {
19019            sendPackageRemovedBroadcastInternal(killApp);
19020            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19021            for (int i = 0; i < childCount; i++) {
19022                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19023                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19024            }
19025        }
19026
19027        void sendSystemPackageUpdatedBroadcasts() {
19028            if (isRemovedPackageSystemUpdate) {
19029                sendSystemPackageUpdatedBroadcastsInternal();
19030                final int childCount = (removedChildPackages != null)
19031                        ? removedChildPackages.size() : 0;
19032                for (int i = 0; i < childCount; i++) {
19033                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19034                    if (childInfo.isRemovedPackageSystemUpdate) {
19035                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19036                    }
19037                }
19038            }
19039        }
19040
19041        void sendSystemPackageAppearedBroadcasts() {
19042            final int packageCount = (appearedChildPackages != null)
19043                    ? appearedChildPackages.size() : 0;
19044            for (int i = 0; i < packageCount; i++) {
19045                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19046                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19047                    true, UserHandle.getAppId(installedInfo.uid),
19048                    installedInfo.newUsers);
19049            }
19050        }
19051
19052        private void sendSystemPackageUpdatedBroadcastsInternal() {
19053            Bundle extras = new Bundle(2);
19054            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19055            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19056            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19057                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19058            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19059                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19060            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19061                null, null, 0, removedPackage, null, null);
19062            if (installerPackageName != null) {
19063                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19064                        removedPackage, extras, 0 /*flags*/,
19065                        installerPackageName, null, null);
19066                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19067                        removedPackage, extras, 0 /*flags*/,
19068                        installerPackageName, null, null);
19069            }
19070        }
19071
19072        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19073            // Don't send static shared library removal broadcasts as these
19074            // libs are visible only the the apps that depend on them an one
19075            // cannot remove the library if it has a dependency.
19076            if (isStaticSharedLib) {
19077                return;
19078            }
19079            Bundle extras = new Bundle(2);
19080            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19081            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19082            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19083            if (isUpdate || isRemovedPackageSystemUpdate) {
19084                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19085            }
19086            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19087            if (removedPackage != null) {
19088                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19089                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19090                if (installerPackageName != null) {
19091                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19092                            removedPackage, extras, 0 /*flags*/,
19093                            installerPackageName, null, broadcastUsers);
19094                }
19095                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19096                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19097                        removedPackage, extras,
19098                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19099                        null, null, broadcastUsers);
19100                }
19101            }
19102            if (removedAppId >= 0) {
19103                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19104                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19105                    null, null, broadcastUsers);
19106            }
19107        }
19108
19109        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19110            removedUsers = userIds;
19111            if (removedUsers == null) {
19112                broadcastUsers = null;
19113                return;
19114            }
19115
19116            broadcastUsers = EMPTY_INT_ARRAY;
19117            for (int i = userIds.length - 1; i >= 0; --i) {
19118                final int userId = userIds[i];
19119                if (deletedPackageSetting.getInstantApp(userId)) {
19120                    continue;
19121                }
19122                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19123            }
19124        }
19125    }
19126
19127    /*
19128     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19129     * flag is not set, the data directory is removed as well.
19130     * make sure this flag is set for partially installed apps. If not its meaningless to
19131     * delete a partially installed application.
19132     */
19133    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19134            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19135        String packageName = ps.name;
19136        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19137        // Retrieve object to delete permissions for shared user later on
19138        final PackageParser.Package deletedPkg;
19139        final PackageSetting deletedPs;
19140        // reader
19141        synchronized (mPackages) {
19142            deletedPkg = mPackages.get(packageName);
19143            deletedPs = mSettings.mPackages.get(packageName);
19144            if (outInfo != null) {
19145                outInfo.removedPackage = packageName;
19146                outInfo.installerPackageName = ps.installerPackageName;
19147                outInfo.isStaticSharedLib = deletedPkg != null
19148                        && deletedPkg.staticSharedLibName != null;
19149                outInfo.populateUsers(deletedPs == null ? null
19150                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19151            }
19152        }
19153
19154        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19155
19156        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19157            final PackageParser.Package resolvedPkg;
19158            if (deletedPkg != null) {
19159                resolvedPkg = deletedPkg;
19160            } else {
19161                // We don't have a parsed package when it lives on an ejected
19162                // adopted storage device, so fake something together
19163                resolvedPkg = new PackageParser.Package(ps.name);
19164                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19165            }
19166            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19167                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19168            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19169            if (outInfo != null) {
19170                outInfo.dataRemoved = true;
19171            }
19172            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19173        }
19174
19175        int removedAppId = -1;
19176
19177        // writer
19178        synchronized (mPackages) {
19179            boolean installedStateChanged = false;
19180            if (deletedPs != null) {
19181                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19182                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19183                    clearDefaultBrowserIfNeeded(packageName);
19184                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19185                    removedAppId = mSettings.removePackageLPw(packageName);
19186                    if (outInfo != null) {
19187                        outInfo.removedAppId = removedAppId;
19188                    }
19189                    updatePermissionsLPw(deletedPs.name, null, 0);
19190                    if (deletedPs.sharedUser != null) {
19191                        // Remove permissions associated with package. Since runtime
19192                        // permissions are per user we have to kill the removed package
19193                        // or packages running under the shared user of the removed
19194                        // package if revoking the permissions requested only by the removed
19195                        // package is successful and this causes a change in gids.
19196                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19197                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19198                                    userId);
19199                            if (userIdToKill == UserHandle.USER_ALL
19200                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19201                                // If gids changed for this user, kill all affected packages.
19202                                mHandler.post(new Runnable() {
19203                                    @Override
19204                                    public void run() {
19205                                        // This has to happen with no lock held.
19206                                        killApplication(deletedPs.name, deletedPs.appId,
19207                                                KILL_APP_REASON_GIDS_CHANGED);
19208                                    }
19209                                });
19210                                break;
19211                            }
19212                        }
19213                    }
19214                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19215                }
19216                // make sure to preserve per-user disabled state if this removal was just
19217                // a downgrade of a system app to the factory package
19218                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19219                    if (DEBUG_REMOVE) {
19220                        Slog.d(TAG, "Propagating install state across downgrade");
19221                    }
19222                    for (int userId : allUserHandles) {
19223                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19224                        if (DEBUG_REMOVE) {
19225                            Slog.d(TAG, "    user " + userId + " => " + installed);
19226                        }
19227                        if (installed != ps.getInstalled(userId)) {
19228                            installedStateChanged = true;
19229                        }
19230                        ps.setInstalled(installed, userId);
19231                    }
19232                }
19233            }
19234            // can downgrade to reader
19235            if (writeSettings) {
19236                // Save settings now
19237                mSettings.writeLPr();
19238            }
19239            if (installedStateChanged) {
19240                mSettings.writeKernelMappingLPr(ps);
19241            }
19242        }
19243        if (removedAppId != -1) {
19244            // A user ID was deleted here. Go through all users and remove it
19245            // from KeyStore.
19246            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19247        }
19248    }
19249
19250    static boolean locationIsPrivileged(File path) {
19251        try {
19252            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19253                    .getCanonicalPath();
19254            return path.getCanonicalPath().startsWith(privilegedAppDir);
19255        } catch (IOException e) {
19256            Slog.e(TAG, "Unable to access code path " + path);
19257        }
19258        return false;
19259    }
19260
19261    /*
19262     * Tries to delete system package.
19263     */
19264    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19265            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19266            boolean writeSettings) {
19267        if (deletedPs.parentPackageName != null) {
19268            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19269            return false;
19270        }
19271
19272        final boolean applyUserRestrictions
19273                = (allUserHandles != null) && (outInfo.origUsers != null);
19274        final PackageSetting disabledPs;
19275        // Confirm if the system package has been updated
19276        // An updated system app can be deleted. This will also have to restore
19277        // the system pkg from system partition
19278        // reader
19279        synchronized (mPackages) {
19280            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19281        }
19282
19283        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19284                + " disabledPs=" + disabledPs);
19285
19286        if (disabledPs == null) {
19287            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19288            return false;
19289        } else if (DEBUG_REMOVE) {
19290            Slog.d(TAG, "Deleting system pkg from data partition");
19291        }
19292
19293        if (DEBUG_REMOVE) {
19294            if (applyUserRestrictions) {
19295                Slog.d(TAG, "Remembering install states:");
19296                for (int userId : allUserHandles) {
19297                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19298                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19299                }
19300            }
19301        }
19302
19303        // Delete the updated package
19304        outInfo.isRemovedPackageSystemUpdate = true;
19305        if (outInfo.removedChildPackages != null) {
19306            final int childCount = (deletedPs.childPackageNames != null)
19307                    ? deletedPs.childPackageNames.size() : 0;
19308            for (int i = 0; i < childCount; i++) {
19309                String childPackageName = deletedPs.childPackageNames.get(i);
19310                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19311                        .contains(childPackageName)) {
19312                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19313                            childPackageName);
19314                    if (childInfo != null) {
19315                        childInfo.isRemovedPackageSystemUpdate = true;
19316                    }
19317                }
19318            }
19319        }
19320
19321        if (disabledPs.versionCode < deletedPs.versionCode) {
19322            // Delete data for downgrades
19323            flags &= ~PackageManager.DELETE_KEEP_DATA;
19324        } else {
19325            // Preserve data by setting flag
19326            flags |= PackageManager.DELETE_KEEP_DATA;
19327        }
19328
19329        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19330                outInfo, writeSettings, disabledPs.pkg);
19331        if (!ret) {
19332            return false;
19333        }
19334
19335        // writer
19336        synchronized (mPackages) {
19337            // Reinstate the old system package
19338            enableSystemPackageLPw(disabledPs.pkg);
19339            // Remove any native libraries from the upgraded package.
19340            removeNativeBinariesLI(deletedPs);
19341        }
19342
19343        // Install the system package
19344        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19345        int parseFlags = mDefParseFlags
19346                | PackageParser.PARSE_MUST_BE_APK
19347                | PackageParser.PARSE_IS_SYSTEM
19348                | PackageParser.PARSE_IS_SYSTEM_DIR;
19349        if (locationIsPrivileged(disabledPs.codePath)) {
19350            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19351        }
19352
19353        final PackageParser.Package newPkg;
19354        try {
19355            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19356                0 /* currentTime */, null);
19357        } catch (PackageManagerException e) {
19358            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19359                    + e.getMessage());
19360            return false;
19361        }
19362
19363        try {
19364            // update shared libraries for the newly re-installed system package
19365            updateSharedLibrariesLPr(newPkg, null);
19366        } catch (PackageManagerException e) {
19367            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19368        }
19369
19370        prepareAppDataAfterInstallLIF(newPkg);
19371
19372        // writer
19373        synchronized (mPackages) {
19374            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19375
19376            // Propagate the permissions state as we do not want to drop on the floor
19377            // runtime permissions. The update permissions method below will take
19378            // care of removing obsolete permissions and grant install permissions.
19379            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19380            updatePermissionsLPw(newPkg.packageName, newPkg,
19381                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19382
19383            if (applyUserRestrictions) {
19384                boolean installedStateChanged = false;
19385                if (DEBUG_REMOVE) {
19386                    Slog.d(TAG, "Propagating install state across reinstall");
19387                }
19388                for (int userId : allUserHandles) {
19389                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19390                    if (DEBUG_REMOVE) {
19391                        Slog.d(TAG, "    user " + userId + " => " + installed);
19392                    }
19393                    if (installed != ps.getInstalled(userId)) {
19394                        installedStateChanged = true;
19395                    }
19396                    ps.setInstalled(installed, userId);
19397
19398                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19399                }
19400                // Regardless of writeSettings we need to ensure that this restriction
19401                // state propagation is persisted
19402                mSettings.writeAllUsersPackageRestrictionsLPr();
19403                if (installedStateChanged) {
19404                    mSettings.writeKernelMappingLPr(ps);
19405                }
19406            }
19407            // can downgrade to reader here
19408            if (writeSettings) {
19409                mSettings.writeLPr();
19410            }
19411        }
19412        return true;
19413    }
19414
19415    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19416            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19417            PackageRemovedInfo outInfo, boolean writeSettings,
19418            PackageParser.Package replacingPackage) {
19419        synchronized (mPackages) {
19420            if (outInfo != null) {
19421                outInfo.uid = ps.appId;
19422            }
19423
19424            if (outInfo != null && outInfo.removedChildPackages != null) {
19425                final int childCount = (ps.childPackageNames != null)
19426                        ? ps.childPackageNames.size() : 0;
19427                for (int i = 0; i < childCount; i++) {
19428                    String childPackageName = ps.childPackageNames.get(i);
19429                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19430                    if (childPs == null) {
19431                        return false;
19432                    }
19433                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19434                            childPackageName);
19435                    if (childInfo != null) {
19436                        childInfo.uid = childPs.appId;
19437                    }
19438                }
19439            }
19440        }
19441
19442        // Delete package data from internal structures and also remove data if flag is set
19443        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19444
19445        // Delete the child packages data
19446        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19447        for (int i = 0; i < childCount; i++) {
19448            PackageSetting childPs;
19449            synchronized (mPackages) {
19450                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19451            }
19452            if (childPs != null) {
19453                PackageRemovedInfo childOutInfo = (outInfo != null
19454                        && outInfo.removedChildPackages != null)
19455                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19456                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19457                        && (replacingPackage != null
19458                        && !replacingPackage.hasChildPackage(childPs.name))
19459                        ? flags & ~DELETE_KEEP_DATA : flags;
19460                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19461                        deleteFlags, writeSettings);
19462            }
19463        }
19464
19465        // Delete application code and resources only for parent packages
19466        if (ps.parentPackageName == null) {
19467            if (deleteCodeAndResources && (outInfo != null)) {
19468                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19469                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19470                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19471            }
19472        }
19473
19474        return true;
19475    }
19476
19477    @Override
19478    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19479            int userId) {
19480        mContext.enforceCallingOrSelfPermission(
19481                android.Manifest.permission.DELETE_PACKAGES, null);
19482        synchronized (mPackages) {
19483            // Cannot block uninstall of static shared libs as they are
19484            // considered a part of the using app (emulating static linking).
19485            // Also static libs are installed always on internal storage.
19486            PackageParser.Package pkg = mPackages.get(packageName);
19487            if (pkg != null && pkg.staticSharedLibName != null) {
19488                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19489                        + " providing static shared library: " + pkg.staticSharedLibName);
19490                return false;
19491            }
19492            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19493            mSettings.writePackageRestrictionsLPr(userId);
19494        }
19495        return true;
19496    }
19497
19498    @Override
19499    public boolean getBlockUninstallForUser(String packageName, int userId) {
19500        synchronized (mPackages) {
19501            final PackageSetting ps = mSettings.mPackages.get(packageName);
19502            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19503                return false;
19504            }
19505            return mSettings.getBlockUninstallLPr(userId, packageName);
19506        }
19507    }
19508
19509    @Override
19510    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19511        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19512        synchronized (mPackages) {
19513            PackageSetting ps = mSettings.mPackages.get(packageName);
19514            if (ps == null) {
19515                Log.w(TAG, "Package doesn't exist: " + packageName);
19516                return false;
19517            }
19518            if (systemUserApp) {
19519                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19520            } else {
19521                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19522            }
19523            mSettings.writeLPr();
19524        }
19525        return true;
19526    }
19527
19528    /*
19529     * This method handles package deletion in general
19530     */
19531    private boolean deletePackageLIF(String packageName, UserHandle user,
19532            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19533            PackageRemovedInfo outInfo, boolean writeSettings,
19534            PackageParser.Package replacingPackage) {
19535        if (packageName == null) {
19536            Slog.w(TAG, "Attempt to delete null packageName.");
19537            return false;
19538        }
19539
19540        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19541
19542        PackageSetting ps;
19543        synchronized (mPackages) {
19544            ps = mSettings.mPackages.get(packageName);
19545            if (ps == null) {
19546                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19547                return false;
19548            }
19549
19550            if (ps.parentPackageName != null && (!isSystemApp(ps)
19551                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19552                if (DEBUG_REMOVE) {
19553                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19554                            + ((user == null) ? UserHandle.USER_ALL : user));
19555                }
19556                final int removedUserId = (user != null) ? user.getIdentifier()
19557                        : UserHandle.USER_ALL;
19558                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19559                    return false;
19560                }
19561                markPackageUninstalledForUserLPw(ps, user);
19562                scheduleWritePackageRestrictionsLocked(user);
19563                return true;
19564            }
19565        }
19566
19567        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19568                && user.getIdentifier() != UserHandle.USER_ALL)) {
19569            // The caller is asking that the package only be deleted for a single
19570            // user.  To do this, we just mark its uninstalled state and delete
19571            // its data. If this is a system app, we only allow this to happen if
19572            // they have set the special DELETE_SYSTEM_APP which requests different
19573            // semantics than normal for uninstalling system apps.
19574            markPackageUninstalledForUserLPw(ps, user);
19575
19576            if (!isSystemApp(ps)) {
19577                // Do not uninstall the APK if an app should be cached
19578                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19579                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19580                    // Other user still have this package installed, so all
19581                    // we need to do is clear this user's data and save that
19582                    // it is uninstalled.
19583                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19584                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19585                        return false;
19586                    }
19587                    scheduleWritePackageRestrictionsLocked(user);
19588                    return true;
19589                } else {
19590                    // We need to set it back to 'installed' so the uninstall
19591                    // broadcasts will be sent correctly.
19592                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19593                    ps.setInstalled(true, user.getIdentifier());
19594                    mSettings.writeKernelMappingLPr(ps);
19595                }
19596            } else {
19597                // This is a system app, so we assume that the
19598                // other users still have this package installed, so all
19599                // we need to do is clear this user's data and save that
19600                // it is uninstalled.
19601                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19602                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19603                    return false;
19604                }
19605                scheduleWritePackageRestrictionsLocked(user);
19606                return true;
19607            }
19608        }
19609
19610        // If we are deleting a composite package for all users, keep track
19611        // of result for each child.
19612        if (ps.childPackageNames != null && outInfo != null) {
19613            synchronized (mPackages) {
19614                final int childCount = ps.childPackageNames.size();
19615                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19616                for (int i = 0; i < childCount; i++) {
19617                    String childPackageName = ps.childPackageNames.get(i);
19618                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19619                    childInfo.removedPackage = childPackageName;
19620                    childInfo.installerPackageName = ps.installerPackageName;
19621                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19622                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19623                    if (childPs != null) {
19624                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19625                    }
19626                }
19627            }
19628        }
19629
19630        boolean ret = false;
19631        if (isSystemApp(ps)) {
19632            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19633            // When an updated system application is deleted we delete the existing resources
19634            // as well and fall back to existing code in system partition
19635            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19636        } else {
19637            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19638            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19639                    outInfo, writeSettings, replacingPackage);
19640        }
19641
19642        // Take a note whether we deleted the package for all users
19643        if (outInfo != null) {
19644            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19645            if (outInfo.removedChildPackages != null) {
19646                synchronized (mPackages) {
19647                    final int childCount = outInfo.removedChildPackages.size();
19648                    for (int i = 0; i < childCount; i++) {
19649                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19650                        if (childInfo != null) {
19651                            childInfo.removedForAllUsers = mPackages.get(
19652                                    childInfo.removedPackage) == null;
19653                        }
19654                    }
19655                }
19656            }
19657            // If we uninstalled an update to a system app there may be some
19658            // child packages that appeared as they are declared in the system
19659            // app but were not declared in the update.
19660            if (isSystemApp(ps)) {
19661                synchronized (mPackages) {
19662                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19663                    final int childCount = (updatedPs.childPackageNames != null)
19664                            ? updatedPs.childPackageNames.size() : 0;
19665                    for (int i = 0; i < childCount; i++) {
19666                        String childPackageName = updatedPs.childPackageNames.get(i);
19667                        if (outInfo.removedChildPackages == null
19668                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19669                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19670                            if (childPs == null) {
19671                                continue;
19672                            }
19673                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19674                            installRes.name = childPackageName;
19675                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19676                            installRes.pkg = mPackages.get(childPackageName);
19677                            installRes.uid = childPs.pkg.applicationInfo.uid;
19678                            if (outInfo.appearedChildPackages == null) {
19679                                outInfo.appearedChildPackages = new ArrayMap<>();
19680                            }
19681                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19682                        }
19683                    }
19684                }
19685            }
19686        }
19687
19688        return ret;
19689    }
19690
19691    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19692        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19693                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19694        for (int nextUserId : userIds) {
19695            if (DEBUG_REMOVE) {
19696                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19697            }
19698            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19699                    false /*installed*/,
19700                    true /*stopped*/,
19701                    true /*notLaunched*/,
19702                    false /*hidden*/,
19703                    false /*suspended*/,
19704                    false /*instantApp*/,
19705                    null /*lastDisableAppCaller*/,
19706                    null /*enabledComponents*/,
19707                    null /*disabledComponents*/,
19708                    ps.readUserState(nextUserId).domainVerificationStatus,
19709                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19710        }
19711        mSettings.writeKernelMappingLPr(ps);
19712    }
19713
19714    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19715            PackageRemovedInfo outInfo) {
19716        final PackageParser.Package pkg;
19717        synchronized (mPackages) {
19718            pkg = mPackages.get(ps.name);
19719        }
19720
19721        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19722                : new int[] {userId};
19723        for (int nextUserId : userIds) {
19724            if (DEBUG_REMOVE) {
19725                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19726                        + nextUserId);
19727            }
19728
19729            destroyAppDataLIF(pkg, userId,
19730                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19731            destroyAppProfilesLIF(pkg, userId);
19732            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19733            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19734            schedulePackageCleaning(ps.name, nextUserId, false);
19735            synchronized (mPackages) {
19736                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19737                    scheduleWritePackageRestrictionsLocked(nextUserId);
19738                }
19739                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19740            }
19741        }
19742
19743        if (outInfo != null) {
19744            outInfo.removedPackage = ps.name;
19745            outInfo.installerPackageName = ps.installerPackageName;
19746            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19747            outInfo.removedAppId = ps.appId;
19748            outInfo.removedUsers = userIds;
19749            outInfo.broadcastUsers = userIds;
19750        }
19751
19752        return true;
19753    }
19754
19755    private final class ClearStorageConnection implements ServiceConnection {
19756        IMediaContainerService mContainerService;
19757
19758        @Override
19759        public void onServiceConnected(ComponentName name, IBinder service) {
19760            synchronized (this) {
19761                mContainerService = IMediaContainerService.Stub
19762                        .asInterface(Binder.allowBlocking(service));
19763                notifyAll();
19764            }
19765        }
19766
19767        @Override
19768        public void onServiceDisconnected(ComponentName name) {
19769        }
19770    }
19771
19772    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19773        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19774
19775        final boolean mounted;
19776        if (Environment.isExternalStorageEmulated()) {
19777            mounted = true;
19778        } else {
19779            final String status = Environment.getExternalStorageState();
19780
19781            mounted = status.equals(Environment.MEDIA_MOUNTED)
19782                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19783        }
19784
19785        if (!mounted) {
19786            return;
19787        }
19788
19789        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19790        int[] users;
19791        if (userId == UserHandle.USER_ALL) {
19792            users = sUserManager.getUserIds();
19793        } else {
19794            users = new int[] { userId };
19795        }
19796        final ClearStorageConnection conn = new ClearStorageConnection();
19797        if (mContext.bindServiceAsUser(
19798                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19799            try {
19800                for (int curUser : users) {
19801                    long timeout = SystemClock.uptimeMillis() + 5000;
19802                    synchronized (conn) {
19803                        long now;
19804                        while (conn.mContainerService == null &&
19805                                (now = SystemClock.uptimeMillis()) < timeout) {
19806                            try {
19807                                conn.wait(timeout - now);
19808                            } catch (InterruptedException e) {
19809                            }
19810                        }
19811                    }
19812                    if (conn.mContainerService == null) {
19813                        return;
19814                    }
19815
19816                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19817                    clearDirectory(conn.mContainerService,
19818                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19819                    if (allData) {
19820                        clearDirectory(conn.mContainerService,
19821                                userEnv.buildExternalStorageAppDataDirs(packageName));
19822                        clearDirectory(conn.mContainerService,
19823                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19824                    }
19825                }
19826            } finally {
19827                mContext.unbindService(conn);
19828            }
19829        }
19830    }
19831
19832    @Override
19833    public void clearApplicationProfileData(String packageName) {
19834        enforceSystemOrRoot("Only the system can clear all profile data");
19835
19836        final PackageParser.Package pkg;
19837        synchronized (mPackages) {
19838            pkg = mPackages.get(packageName);
19839        }
19840
19841        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19842            synchronized (mInstallLock) {
19843                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19844            }
19845        }
19846    }
19847
19848    @Override
19849    public void clearApplicationUserData(final String packageName,
19850            final IPackageDataObserver observer, final int userId) {
19851        mContext.enforceCallingOrSelfPermission(
19852                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19853
19854        final int callingUid = Binder.getCallingUid();
19855        enforceCrossUserPermission(callingUid, userId,
19856                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19857
19858        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19859        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19860            return;
19861        }
19862        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19863            throw new SecurityException("Cannot clear data for a protected package: "
19864                    + packageName);
19865        }
19866        // Queue up an async operation since the package deletion may take a little while.
19867        mHandler.post(new Runnable() {
19868            public void run() {
19869                mHandler.removeCallbacks(this);
19870                final boolean succeeded;
19871                try (PackageFreezer freezer = freezePackage(packageName,
19872                        "clearApplicationUserData")) {
19873                    synchronized (mInstallLock) {
19874                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19875                    }
19876                    clearExternalStorageDataSync(packageName, userId, true);
19877                    synchronized (mPackages) {
19878                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19879                                packageName, userId);
19880                    }
19881                }
19882                if (succeeded) {
19883                    // invoke DeviceStorageMonitor's update method to clear any notifications
19884                    DeviceStorageMonitorInternal dsm = LocalServices
19885                            .getService(DeviceStorageMonitorInternal.class);
19886                    if (dsm != null) {
19887                        dsm.checkMemory();
19888                    }
19889                }
19890                if(observer != null) {
19891                    try {
19892                        observer.onRemoveCompleted(packageName, succeeded);
19893                    } catch (RemoteException e) {
19894                        Log.i(TAG, "Observer no longer exists.");
19895                    }
19896                } //end if observer
19897            } //end run
19898        });
19899    }
19900
19901    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19902        if (packageName == null) {
19903            Slog.w(TAG, "Attempt to delete null packageName.");
19904            return false;
19905        }
19906
19907        // Try finding details about the requested package
19908        PackageParser.Package pkg;
19909        synchronized (mPackages) {
19910            pkg = mPackages.get(packageName);
19911            if (pkg == null) {
19912                final PackageSetting ps = mSettings.mPackages.get(packageName);
19913                if (ps != null) {
19914                    pkg = ps.pkg;
19915                }
19916            }
19917
19918            if (pkg == null) {
19919                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19920                return false;
19921            }
19922
19923            PackageSetting ps = (PackageSetting) pkg.mExtras;
19924            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19925        }
19926
19927        clearAppDataLIF(pkg, userId,
19928                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19929
19930        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19931        removeKeystoreDataIfNeeded(userId, appId);
19932
19933        UserManagerInternal umInternal = getUserManagerInternal();
19934        final int flags;
19935        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19936            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19937        } else if (umInternal.isUserRunning(userId)) {
19938            flags = StorageManager.FLAG_STORAGE_DE;
19939        } else {
19940            flags = 0;
19941        }
19942        prepareAppDataContentsLIF(pkg, userId, flags);
19943
19944        return true;
19945    }
19946
19947    /**
19948     * Reverts user permission state changes (permissions and flags) in
19949     * all packages for a given user.
19950     *
19951     * @param userId The device user for which to do a reset.
19952     */
19953    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19954        final int packageCount = mPackages.size();
19955        for (int i = 0; i < packageCount; i++) {
19956            PackageParser.Package pkg = mPackages.valueAt(i);
19957            PackageSetting ps = (PackageSetting) pkg.mExtras;
19958            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19959        }
19960    }
19961
19962    private void resetNetworkPolicies(int userId) {
19963        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19964    }
19965
19966    /**
19967     * Reverts user permission state changes (permissions and flags).
19968     *
19969     * @param ps The package for which to reset.
19970     * @param userId The device user for which to do a reset.
19971     */
19972    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19973            final PackageSetting ps, final int userId) {
19974        if (ps.pkg == null) {
19975            return;
19976        }
19977
19978        // These are flags that can change base on user actions.
19979        final int userSettableMask = FLAG_PERMISSION_USER_SET
19980                | FLAG_PERMISSION_USER_FIXED
19981                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19982                | FLAG_PERMISSION_REVIEW_REQUIRED;
19983
19984        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19985                | FLAG_PERMISSION_POLICY_FIXED;
19986
19987        boolean writeInstallPermissions = false;
19988        boolean writeRuntimePermissions = false;
19989
19990        final int permissionCount = ps.pkg.requestedPermissions.size();
19991        for (int i = 0; i < permissionCount; i++) {
19992            String permission = ps.pkg.requestedPermissions.get(i);
19993
19994            BasePermission bp = mSettings.mPermissions.get(permission);
19995            if (bp == null) {
19996                continue;
19997            }
19998
19999            // If shared user we just reset the state to which only this app contributed.
20000            if (ps.sharedUser != null) {
20001                boolean used = false;
20002                final int packageCount = ps.sharedUser.packages.size();
20003                for (int j = 0; j < packageCount; j++) {
20004                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20005                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20006                            && pkg.pkg.requestedPermissions.contains(permission)) {
20007                        used = true;
20008                        break;
20009                    }
20010                }
20011                if (used) {
20012                    continue;
20013                }
20014            }
20015
20016            PermissionsState permissionsState = ps.getPermissionsState();
20017
20018            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20019
20020            // Always clear the user settable flags.
20021            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20022                    bp.name) != null;
20023            // If permission review is enabled and this is a legacy app, mark the
20024            // permission as requiring a review as this is the initial state.
20025            int flags = 0;
20026            if (mPermissionReviewRequired
20027                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20028                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20029            }
20030            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20031                if (hasInstallState) {
20032                    writeInstallPermissions = true;
20033                } else {
20034                    writeRuntimePermissions = true;
20035                }
20036            }
20037
20038            // Below is only runtime permission handling.
20039            if (!bp.isRuntime()) {
20040                continue;
20041            }
20042
20043            // Never clobber system or policy.
20044            if ((oldFlags & policyOrSystemFlags) != 0) {
20045                continue;
20046            }
20047
20048            // If this permission was granted by default, make sure it is.
20049            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20050                if (permissionsState.grantRuntimePermission(bp, userId)
20051                        != PERMISSION_OPERATION_FAILURE) {
20052                    writeRuntimePermissions = true;
20053                }
20054            // If permission review is enabled the permissions for a legacy apps
20055            // are represented as constantly granted runtime ones, so don't revoke.
20056            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20057                // Otherwise, reset the permission.
20058                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20059                switch (revokeResult) {
20060                    case PERMISSION_OPERATION_SUCCESS:
20061                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20062                        writeRuntimePermissions = true;
20063                        final int appId = ps.appId;
20064                        mHandler.post(new Runnable() {
20065                            @Override
20066                            public void run() {
20067                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20068                            }
20069                        });
20070                    } break;
20071                }
20072            }
20073        }
20074
20075        // Synchronously write as we are taking permissions away.
20076        if (writeRuntimePermissions) {
20077            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20078        }
20079
20080        // Synchronously write as we are taking permissions away.
20081        if (writeInstallPermissions) {
20082            mSettings.writeLPr();
20083        }
20084    }
20085
20086    /**
20087     * Remove entries from the keystore daemon. Will only remove it if the
20088     * {@code appId} is valid.
20089     */
20090    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20091        if (appId < 0) {
20092            return;
20093        }
20094
20095        final KeyStore keyStore = KeyStore.getInstance();
20096        if (keyStore != null) {
20097            if (userId == UserHandle.USER_ALL) {
20098                for (final int individual : sUserManager.getUserIds()) {
20099                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20100                }
20101            } else {
20102                keyStore.clearUid(UserHandle.getUid(userId, appId));
20103            }
20104        } else {
20105            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20106        }
20107    }
20108
20109    @Override
20110    public void deleteApplicationCacheFiles(final String packageName,
20111            final IPackageDataObserver observer) {
20112        final int userId = UserHandle.getCallingUserId();
20113        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20114    }
20115
20116    @Override
20117    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20118            final IPackageDataObserver observer) {
20119        final int callingUid = Binder.getCallingUid();
20120        mContext.enforceCallingOrSelfPermission(
20121                android.Manifest.permission.DELETE_CACHE_FILES, null);
20122        enforceCrossUserPermission(callingUid, userId,
20123                /* requireFullPermission= */ true, /* checkShell= */ false,
20124                "delete application cache files");
20125        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20126                android.Manifest.permission.ACCESS_INSTANT_APPS);
20127
20128        final PackageParser.Package pkg;
20129        synchronized (mPackages) {
20130            pkg = mPackages.get(packageName);
20131        }
20132
20133        // Queue up an async operation since the package deletion may take a little while.
20134        mHandler.post(new Runnable() {
20135            public void run() {
20136                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20137                boolean doClearData = true;
20138                if (ps != null) {
20139                    final boolean targetIsInstantApp =
20140                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20141                    doClearData = !targetIsInstantApp
20142                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20143                }
20144                if (doClearData) {
20145                    synchronized (mInstallLock) {
20146                        final int flags = StorageManager.FLAG_STORAGE_DE
20147                                | StorageManager.FLAG_STORAGE_CE;
20148                        // We're only clearing cache files, so we don't care if the
20149                        // app is unfrozen and still able to run
20150                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20151                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20152                    }
20153                    clearExternalStorageDataSync(packageName, userId, false);
20154                }
20155                if (observer != null) {
20156                    try {
20157                        observer.onRemoveCompleted(packageName, true);
20158                    } catch (RemoteException e) {
20159                        Log.i(TAG, "Observer no longer exists.");
20160                    }
20161                }
20162            }
20163        });
20164    }
20165
20166    @Override
20167    public void getPackageSizeInfo(final String packageName, int userHandle,
20168            final IPackageStatsObserver observer) {
20169        throw new UnsupportedOperationException(
20170                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20171    }
20172
20173    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20174        final PackageSetting ps;
20175        synchronized (mPackages) {
20176            ps = mSettings.mPackages.get(packageName);
20177            if (ps == null) {
20178                Slog.w(TAG, "Failed to find settings for " + packageName);
20179                return false;
20180            }
20181        }
20182
20183        final String[] packageNames = { packageName };
20184        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20185        final String[] codePaths = { ps.codePathString };
20186
20187        try {
20188            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20189                    ps.appId, ceDataInodes, codePaths, stats);
20190
20191            // For now, ignore code size of packages on system partition
20192            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20193                stats.codeSize = 0;
20194            }
20195
20196            // External clients expect these to be tracked separately
20197            stats.dataSize -= stats.cacheSize;
20198
20199        } catch (InstallerException e) {
20200            Slog.w(TAG, String.valueOf(e));
20201            return false;
20202        }
20203
20204        return true;
20205    }
20206
20207    private int getUidTargetSdkVersionLockedLPr(int uid) {
20208        Object obj = mSettings.getUserIdLPr(uid);
20209        if (obj instanceof SharedUserSetting) {
20210            final SharedUserSetting sus = (SharedUserSetting) obj;
20211            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20212            final Iterator<PackageSetting> it = sus.packages.iterator();
20213            while (it.hasNext()) {
20214                final PackageSetting ps = it.next();
20215                if (ps.pkg != null) {
20216                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20217                    if (v < vers) vers = v;
20218                }
20219            }
20220            return vers;
20221        } else if (obj instanceof PackageSetting) {
20222            final PackageSetting ps = (PackageSetting) obj;
20223            if (ps.pkg != null) {
20224                return ps.pkg.applicationInfo.targetSdkVersion;
20225            }
20226        }
20227        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20228    }
20229
20230    @Override
20231    public void addPreferredActivity(IntentFilter filter, int match,
20232            ComponentName[] set, ComponentName activity, int userId) {
20233        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20234                "Adding preferred");
20235    }
20236
20237    private void addPreferredActivityInternal(IntentFilter filter, int match,
20238            ComponentName[] set, ComponentName activity, boolean always, int userId,
20239            String opname) {
20240        // writer
20241        int callingUid = Binder.getCallingUid();
20242        enforceCrossUserPermission(callingUid, userId,
20243                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20244        if (filter.countActions() == 0) {
20245            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20246            return;
20247        }
20248        synchronized (mPackages) {
20249            if (mContext.checkCallingOrSelfPermission(
20250                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20251                    != PackageManager.PERMISSION_GRANTED) {
20252                if (getUidTargetSdkVersionLockedLPr(callingUid)
20253                        < Build.VERSION_CODES.FROYO) {
20254                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20255                            + callingUid);
20256                    return;
20257                }
20258                mContext.enforceCallingOrSelfPermission(
20259                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20260            }
20261
20262            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20263            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20264                    + userId + ":");
20265            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20266            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20267            scheduleWritePackageRestrictionsLocked(userId);
20268            postPreferredActivityChangedBroadcast(userId);
20269        }
20270    }
20271
20272    private void postPreferredActivityChangedBroadcast(int userId) {
20273        mHandler.post(() -> {
20274            final IActivityManager am = ActivityManager.getService();
20275            if (am == null) {
20276                return;
20277            }
20278
20279            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20280            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20281            try {
20282                am.broadcastIntent(null, intent, null, null,
20283                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20284                        null, false, false, userId);
20285            } catch (RemoteException e) {
20286            }
20287        });
20288    }
20289
20290    @Override
20291    public void replacePreferredActivity(IntentFilter filter, int match,
20292            ComponentName[] set, ComponentName activity, int userId) {
20293        if (filter.countActions() != 1) {
20294            throw new IllegalArgumentException(
20295                    "replacePreferredActivity expects filter to have only 1 action.");
20296        }
20297        if (filter.countDataAuthorities() != 0
20298                || filter.countDataPaths() != 0
20299                || filter.countDataSchemes() > 1
20300                || filter.countDataTypes() != 0) {
20301            throw new IllegalArgumentException(
20302                    "replacePreferredActivity expects filter to have no data authorities, " +
20303                    "paths, or types; and at most one scheme.");
20304        }
20305
20306        final int callingUid = Binder.getCallingUid();
20307        enforceCrossUserPermission(callingUid, userId,
20308                true /* requireFullPermission */, false /* checkShell */,
20309                "replace preferred activity");
20310        synchronized (mPackages) {
20311            if (mContext.checkCallingOrSelfPermission(
20312                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20313                    != PackageManager.PERMISSION_GRANTED) {
20314                if (getUidTargetSdkVersionLockedLPr(callingUid)
20315                        < Build.VERSION_CODES.FROYO) {
20316                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20317                            + Binder.getCallingUid());
20318                    return;
20319                }
20320                mContext.enforceCallingOrSelfPermission(
20321                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20322            }
20323
20324            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20325            if (pir != null) {
20326                // Get all of the existing entries that exactly match this filter.
20327                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20328                if (existing != null && existing.size() == 1) {
20329                    PreferredActivity cur = existing.get(0);
20330                    if (DEBUG_PREFERRED) {
20331                        Slog.i(TAG, "Checking replace of preferred:");
20332                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20333                        if (!cur.mPref.mAlways) {
20334                            Slog.i(TAG, "  -- CUR; not mAlways!");
20335                        } else {
20336                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20337                            Slog.i(TAG, "  -- CUR: mSet="
20338                                    + Arrays.toString(cur.mPref.mSetComponents));
20339                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20340                            Slog.i(TAG, "  -- NEW: mMatch="
20341                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20342                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20343                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20344                        }
20345                    }
20346                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20347                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20348                            && cur.mPref.sameSet(set)) {
20349                        // Setting the preferred activity to what it happens to be already
20350                        if (DEBUG_PREFERRED) {
20351                            Slog.i(TAG, "Replacing with same preferred activity "
20352                                    + cur.mPref.mShortComponent + " for user "
20353                                    + userId + ":");
20354                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20355                        }
20356                        return;
20357                    }
20358                }
20359
20360                if (existing != null) {
20361                    if (DEBUG_PREFERRED) {
20362                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20363                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20364                    }
20365                    for (int i = 0; i < existing.size(); i++) {
20366                        PreferredActivity pa = existing.get(i);
20367                        if (DEBUG_PREFERRED) {
20368                            Slog.i(TAG, "Removing existing preferred activity "
20369                                    + pa.mPref.mComponent + ":");
20370                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20371                        }
20372                        pir.removeFilter(pa);
20373                    }
20374                }
20375            }
20376            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20377                    "Replacing preferred");
20378        }
20379    }
20380
20381    @Override
20382    public void clearPackagePreferredActivities(String packageName) {
20383        final int callingUid = Binder.getCallingUid();
20384        if (getInstantAppPackageName(callingUid) != null) {
20385            return;
20386        }
20387        // writer
20388        synchronized (mPackages) {
20389            PackageParser.Package pkg = mPackages.get(packageName);
20390            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20391                if (mContext.checkCallingOrSelfPermission(
20392                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20393                        != PackageManager.PERMISSION_GRANTED) {
20394                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20395                            < Build.VERSION_CODES.FROYO) {
20396                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20397                                + callingUid);
20398                        return;
20399                    }
20400                    mContext.enforceCallingOrSelfPermission(
20401                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20402                }
20403            }
20404            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20405            if (ps != null
20406                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20407                return;
20408            }
20409            int user = UserHandle.getCallingUserId();
20410            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20411                scheduleWritePackageRestrictionsLocked(user);
20412            }
20413        }
20414    }
20415
20416    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20417    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20418        ArrayList<PreferredActivity> removed = null;
20419        boolean changed = false;
20420        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20421            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20422            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20423            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20424                continue;
20425            }
20426            Iterator<PreferredActivity> it = pir.filterIterator();
20427            while (it.hasNext()) {
20428                PreferredActivity pa = it.next();
20429                // Mark entry for removal only if it matches the package name
20430                // and the entry is of type "always".
20431                if (packageName == null ||
20432                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20433                                && pa.mPref.mAlways)) {
20434                    if (removed == null) {
20435                        removed = new ArrayList<PreferredActivity>();
20436                    }
20437                    removed.add(pa);
20438                }
20439            }
20440            if (removed != null) {
20441                for (int j=0; j<removed.size(); j++) {
20442                    PreferredActivity pa = removed.get(j);
20443                    pir.removeFilter(pa);
20444                }
20445                changed = true;
20446            }
20447        }
20448        if (changed) {
20449            postPreferredActivityChangedBroadcast(userId);
20450        }
20451        return changed;
20452    }
20453
20454    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20455    private void clearIntentFilterVerificationsLPw(int userId) {
20456        final int packageCount = mPackages.size();
20457        for (int i = 0; i < packageCount; i++) {
20458            PackageParser.Package pkg = mPackages.valueAt(i);
20459            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20460        }
20461    }
20462
20463    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20464    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20465        if (userId == UserHandle.USER_ALL) {
20466            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20467                    sUserManager.getUserIds())) {
20468                for (int oneUserId : sUserManager.getUserIds()) {
20469                    scheduleWritePackageRestrictionsLocked(oneUserId);
20470                }
20471            }
20472        } else {
20473            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20474                scheduleWritePackageRestrictionsLocked(userId);
20475            }
20476        }
20477    }
20478
20479    /** Clears state for all users, and touches intent filter verification policy */
20480    void clearDefaultBrowserIfNeeded(String packageName) {
20481        for (int oneUserId : sUserManager.getUserIds()) {
20482            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20483        }
20484    }
20485
20486    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20487        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20488        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20489            if (packageName.equals(defaultBrowserPackageName)) {
20490                setDefaultBrowserPackageName(null, userId);
20491            }
20492        }
20493    }
20494
20495    @Override
20496    public void resetApplicationPreferences(int userId) {
20497        mContext.enforceCallingOrSelfPermission(
20498                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20499        final long identity = Binder.clearCallingIdentity();
20500        // writer
20501        try {
20502            synchronized (mPackages) {
20503                clearPackagePreferredActivitiesLPw(null, userId);
20504                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20505                // TODO: We have to reset the default SMS and Phone. This requires
20506                // significant refactoring to keep all default apps in the package
20507                // manager (cleaner but more work) or have the services provide
20508                // callbacks to the package manager to request a default app reset.
20509                applyFactoryDefaultBrowserLPw(userId);
20510                clearIntentFilterVerificationsLPw(userId);
20511                primeDomainVerificationsLPw(userId);
20512                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20513                scheduleWritePackageRestrictionsLocked(userId);
20514            }
20515            resetNetworkPolicies(userId);
20516        } finally {
20517            Binder.restoreCallingIdentity(identity);
20518        }
20519    }
20520
20521    @Override
20522    public int getPreferredActivities(List<IntentFilter> outFilters,
20523            List<ComponentName> outActivities, String packageName) {
20524        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20525            return 0;
20526        }
20527        int num = 0;
20528        final int userId = UserHandle.getCallingUserId();
20529        // reader
20530        synchronized (mPackages) {
20531            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20532            if (pir != null) {
20533                final Iterator<PreferredActivity> it = pir.filterIterator();
20534                while (it.hasNext()) {
20535                    final PreferredActivity pa = it.next();
20536                    if (packageName == null
20537                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20538                                    && pa.mPref.mAlways)) {
20539                        if (outFilters != null) {
20540                            outFilters.add(new IntentFilter(pa));
20541                        }
20542                        if (outActivities != null) {
20543                            outActivities.add(pa.mPref.mComponent);
20544                        }
20545                    }
20546                }
20547            }
20548        }
20549
20550        return num;
20551    }
20552
20553    @Override
20554    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20555            int userId) {
20556        int callingUid = Binder.getCallingUid();
20557        if (callingUid != Process.SYSTEM_UID) {
20558            throw new SecurityException(
20559                    "addPersistentPreferredActivity can only be run by the system");
20560        }
20561        if (filter.countActions() == 0) {
20562            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20563            return;
20564        }
20565        synchronized (mPackages) {
20566            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20567                    ":");
20568            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20569            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20570                    new PersistentPreferredActivity(filter, activity));
20571            scheduleWritePackageRestrictionsLocked(userId);
20572            postPreferredActivityChangedBroadcast(userId);
20573        }
20574    }
20575
20576    @Override
20577    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20578        int callingUid = Binder.getCallingUid();
20579        if (callingUid != Process.SYSTEM_UID) {
20580            throw new SecurityException(
20581                    "clearPackagePersistentPreferredActivities can only be run by the system");
20582        }
20583        ArrayList<PersistentPreferredActivity> removed = null;
20584        boolean changed = false;
20585        synchronized (mPackages) {
20586            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20587                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20588                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20589                        .valueAt(i);
20590                if (userId != thisUserId) {
20591                    continue;
20592                }
20593                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20594                while (it.hasNext()) {
20595                    PersistentPreferredActivity ppa = it.next();
20596                    // Mark entry for removal only if it matches the package name.
20597                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20598                        if (removed == null) {
20599                            removed = new ArrayList<PersistentPreferredActivity>();
20600                        }
20601                        removed.add(ppa);
20602                    }
20603                }
20604                if (removed != null) {
20605                    for (int j=0; j<removed.size(); j++) {
20606                        PersistentPreferredActivity ppa = removed.get(j);
20607                        ppir.removeFilter(ppa);
20608                    }
20609                    changed = true;
20610                }
20611            }
20612
20613            if (changed) {
20614                scheduleWritePackageRestrictionsLocked(userId);
20615                postPreferredActivityChangedBroadcast(userId);
20616            }
20617        }
20618    }
20619
20620    /**
20621     * Common machinery for picking apart a restored XML blob and passing
20622     * it to a caller-supplied functor to be applied to the running system.
20623     */
20624    private void restoreFromXml(XmlPullParser parser, int userId,
20625            String expectedStartTag, BlobXmlRestorer functor)
20626            throws IOException, XmlPullParserException {
20627        int type;
20628        while ((type = parser.next()) != XmlPullParser.START_TAG
20629                && type != XmlPullParser.END_DOCUMENT) {
20630        }
20631        if (type != XmlPullParser.START_TAG) {
20632            // oops didn't find a start tag?!
20633            if (DEBUG_BACKUP) {
20634                Slog.e(TAG, "Didn't find start tag during restore");
20635            }
20636            return;
20637        }
20638Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20639        // this is supposed to be TAG_PREFERRED_BACKUP
20640        if (!expectedStartTag.equals(parser.getName())) {
20641            if (DEBUG_BACKUP) {
20642                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20643            }
20644            return;
20645        }
20646
20647        // skip interfering stuff, then we're aligned with the backing implementation
20648        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20649Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20650        functor.apply(parser, userId);
20651    }
20652
20653    private interface BlobXmlRestorer {
20654        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20655    }
20656
20657    /**
20658     * Non-Binder method, support for the backup/restore mechanism: write the
20659     * full set of preferred activities in its canonical XML format.  Returns the
20660     * XML output as a byte array, or null if there is none.
20661     */
20662    @Override
20663    public byte[] getPreferredActivityBackup(int userId) {
20664        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20665            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20666        }
20667
20668        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20669        try {
20670            final XmlSerializer serializer = new FastXmlSerializer();
20671            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20672            serializer.startDocument(null, true);
20673            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20674
20675            synchronized (mPackages) {
20676                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20677            }
20678
20679            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20680            serializer.endDocument();
20681            serializer.flush();
20682        } catch (Exception e) {
20683            if (DEBUG_BACKUP) {
20684                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20685            }
20686            return null;
20687        }
20688
20689        return dataStream.toByteArray();
20690    }
20691
20692    @Override
20693    public void restorePreferredActivities(byte[] backup, int userId) {
20694        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20695            throw new SecurityException("Only the system may call restorePreferredActivities()");
20696        }
20697
20698        try {
20699            final XmlPullParser parser = Xml.newPullParser();
20700            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20701            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20702                    new BlobXmlRestorer() {
20703                        @Override
20704                        public void apply(XmlPullParser parser, int userId)
20705                                throws XmlPullParserException, IOException {
20706                            synchronized (mPackages) {
20707                                mSettings.readPreferredActivitiesLPw(parser, userId);
20708                            }
20709                        }
20710                    } );
20711        } catch (Exception e) {
20712            if (DEBUG_BACKUP) {
20713                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20714            }
20715        }
20716    }
20717
20718    /**
20719     * Non-Binder method, support for the backup/restore mechanism: write the
20720     * default browser (etc) settings in its canonical XML format.  Returns the default
20721     * browser XML representation as a byte array, or null if there is none.
20722     */
20723    @Override
20724    public byte[] getDefaultAppsBackup(int userId) {
20725        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20726            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20727        }
20728
20729        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20730        try {
20731            final XmlSerializer serializer = new FastXmlSerializer();
20732            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20733            serializer.startDocument(null, true);
20734            serializer.startTag(null, TAG_DEFAULT_APPS);
20735
20736            synchronized (mPackages) {
20737                mSettings.writeDefaultAppsLPr(serializer, userId);
20738            }
20739
20740            serializer.endTag(null, TAG_DEFAULT_APPS);
20741            serializer.endDocument();
20742            serializer.flush();
20743        } catch (Exception e) {
20744            if (DEBUG_BACKUP) {
20745                Slog.e(TAG, "Unable to write default apps for backup", e);
20746            }
20747            return null;
20748        }
20749
20750        return dataStream.toByteArray();
20751    }
20752
20753    @Override
20754    public void restoreDefaultApps(byte[] backup, int userId) {
20755        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20756            throw new SecurityException("Only the system may call restoreDefaultApps()");
20757        }
20758
20759        try {
20760            final XmlPullParser parser = Xml.newPullParser();
20761            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20762            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20763                    new BlobXmlRestorer() {
20764                        @Override
20765                        public void apply(XmlPullParser parser, int userId)
20766                                throws XmlPullParserException, IOException {
20767                            synchronized (mPackages) {
20768                                mSettings.readDefaultAppsLPw(parser, userId);
20769                            }
20770                        }
20771                    } );
20772        } catch (Exception e) {
20773            if (DEBUG_BACKUP) {
20774                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20775            }
20776        }
20777    }
20778
20779    @Override
20780    public byte[] getIntentFilterVerificationBackup(int userId) {
20781        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20782            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20783        }
20784
20785        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20786        try {
20787            final XmlSerializer serializer = new FastXmlSerializer();
20788            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20789            serializer.startDocument(null, true);
20790            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20791
20792            synchronized (mPackages) {
20793                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20794            }
20795
20796            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20797            serializer.endDocument();
20798            serializer.flush();
20799        } catch (Exception e) {
20800            if (DEBUG_BACKUP) {
20801                Slog.e(TAG, "Unable to write default apps for backup", e);
20802            }
20803            return null;
20804        }
20805
20806        return dataStream.toByteArray();
20807    }
20808
20809    @Override
20810    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20811        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20812            throw new SecurityException("Only the system may call restorePreferredActivities()");
20813        }
20814
20815        try {
20816            final XmlPullParser parser = Xml.newPullParser();
20817            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20818            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20819                    new BlobXmlRestorer() {
20820                        @Override
20821                        public void apply(XmlPullParser parser, int userId)
20822                                throws XmlPullParserException, IOException {
20823                            synchronized (mPackages) {
20824                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20825                                mSettings.writeLPr();
20826                            }
20827                        }
20828                    } );
20829        } catch (Exception e) {
20830            if (DEBUG_BACKUP) {
20831                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20832            }
20833        }
20834    }
20835
20836    @Override
20837    public byte[] getPermissionGrantBackup(int userId) {
20838        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20839            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20840        }
20841
20842        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20843        try {
20844            final XmlSerializer serializer = new FastXmlSerializer();
20845            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20846            serializer.startDocument(null, true);
20847            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20848
20849            synchronized (mPackages) {
20850                serializeRuntimePermissionGrantsLPr(serializer, userId);
20851            }
20852
20853            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20854            serializer.endDocument();
20855            serializer.flush();
20856        } catch (Exception e) {
20857            if (DEBUG_BACKUP) {
20858                Slog.e(TAG, "Unable to write default apps for backup", e);
20859            }
20860            return null;
20861        }
20862
20863        return dataStream.toByteArray();
20864    }
20865
20866    @Override
20867    public void restorePermissionGrants(byte[] backup, int userId) {
20868        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20869            throw new SecurityException("Only the system may call restorePermissionGrants()");
20870        }
20871
20872        try {
20873            final XmlPullParser parser = Xml.newPullParser();
20874            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20875            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20876                    new BlobXmlRestorer() {
20877                        @Override
20878                        public void apply(XmlPullParser parser, int userId)
20879                                throws XmlPullParserException, IOException {
20880                            synchronized (mPackages) {
20881                                processRestoredPermissionGrantsLPr(parser, userId);
20882                            }
20883                        }
20884                    } );
20885        } catch (Exception e) {
20886            if (DEBUG_BACKUP) {
20887                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20888            }
20889        }
20890    }
20891
20892    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20893            throws IOException {
20894        serializer.startTag(null, TAG_ALL_GRANTS);
20895
20896        final int N = mSettings.mPackages.size();
20897        for (int i = 0; i < N; i++) {
20898            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20899            boolean pkgGrantsKnown = false;
20900
20901            PermissionsState packagePerms = ps.getPermissionsState();
20902
20903            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20904                final int grantFlags = state.getFlags();
20905                // only look at grants that are not system/policy fixed
20906                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20907                    final boolean isGranted = state.isGranted();
20908                    // And only back up the user-twiddled state bits
20909                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20910                        final String packageName = mSettings.mPackages.keyAt(i);
20911                        if (!pkgGrantsKnown) {
20912                            serializer.startTag(null, TAG_GRANT);
20913                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20914                            pkgGrantsKnown = true;
20915                        }
20916
20917                        final boolean userSet =
20918                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20919                        final boolean userFixed =
20920                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20921                        final boolean revoke =
20922                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20923
20924                        serializer.startTag(null, TAG_PERMISSION);
20925                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20926                        if (isGranted) {
20927                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20928                        }
20929                        if (userSet) {
20930                            serializer.attribute(null, ATTR_USER_SET, "true");
20931                        }
20932                        if (userFixed) {
20933                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20934                        }
20935                        if (revoke) {
20936                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20937                        }
20938                        serializer.endTag(null, TAG_PERMISSION);
20939                    }
20940                }
20941            }
20942
20943            if (pkgGrantsKnown) {
20944                serializer.endTag(null, TAG_GRANT);
20945            }
20946        }
20947
20948        serializer.endTag(null, TAG_ALL_GRANTS);
20949    }
20950
20951    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20952            throws XmlPullParserException, IOException {
20953        String pkgName = null;
20954        int outerDepth = parser.getDepth();
20955        int type;
20956        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20957                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20958            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20959                continue;
20960            }
20961
20962            final String tagName = parser.getName();
20963            if (tagName.equals(TAG_GRANT)) {
20964                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20965                if (DEBUG_BACKUP) {
20966                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20967                }
20968            } else if (tagName.equals(TAG_PERMISSION)) {
20969
20970                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20971                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20972
20973                int newFlagSet = 0;
20974                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20975                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20976                }
20977                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20978                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20979                }
20980                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20981                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20982                }
20983                if (DEBUG_BACKUP) {
20984                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20985                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20986                }
20987                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20988                if (ps != null) {
20989                    // Already installed so we apply the grant immediately
20990                    if (DEBUG_BACKUP) {
20991                        Slog.v(TAG, "        + already installed; applying");
20992                    }
20993                    PermissionsState perms = ps.getPermissionsState();
20994                    BasePermission bp = mSettings.mPermissions.get(permName);
20995                    if (bp != null) {
20996                        if (isGranted) {
20997                            perms.grantRuntimePermission(bp, userId);
20998                        }
20999                        if (newFlagSet != 0) {
21000                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21001                        }
21002                    }
21003                } else {
21004                    // Need to wait for post-restore install to apply the grant
21005                    if (DEBUG_BACKUP) {
21006                        Slog.v(TAG, "        - not yet installed; saving for later");
21007                    }
21008                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21009                            isGranted, newFlagSet, userId);
21010                }
21011            } else {
21012                PackageManagerService.reportSettingsProblem(Log.WARN,
21013                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21014                XmlUtils.skipCurrentTag(parser);
21015            }
21016        }
21017
21018        scheduleWriteSettingsLocked();
21019        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21020    }
21021
21022    @Override
21023    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21024            int sourceUserId, int targetUserId, int flags) {
21025        mContext.enforceCallingOrSelfPermission(
21026                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21027        int callingUid = Binder.getCallingUid();
21028        enforceOwnerRights(ownerPackage, callingUid);
21029        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21030        if (intentFilter.countActions() == 0) {
21031            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21032            return;
21033        }
21034        synchronized (mPackages) {
21035            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21036                    ownerPackage, targetUserId, flags);
21037            CrossProfileIntentResolver resolver =
21038                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21039            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21040            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21041            if (existing != null) {
21042                int size = existing.size();
21043                for (int i = 0; i < size; i++) {
21044                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21045                        return;
21046                    }
21047                }
21048            }
21049            resolver.addFilter(newFilter);
21050            scheduleWritePackageRestrictionsLocked(sourceUserId);
21051        }
21052    }
21053
21054    @Override
21055    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21056        mContext.enforceCallingOrSelfPermission(
21057                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21058        final int callingUid = Binder.getCallingUid();
21059        enforceOwnerRights(ownerPackage, callingUid);
21060        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21061        synchronized (mPackages) {
21062            CrossProfileIntentResolver resolver =
21063                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21064            ArraySet<CrossProfileIntentFilter> set =
21065                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21066            for (CrossProfileIntentFilter filter : set) {
21067                if (filter.getOwnerPackage().equals(ownerPackage)) {
21068                    resolver.removeFilter(filter);
21069                }
21070            }
21071            scheduleWritePackageRestrictionsLocked(sourceUserId);
21072        }
21073    }
21074
21075    // Enforcing that callingUid is owning pkg on userId
21076    private void enforceOwnerRights(String pkg, int callingUid) {
21077        // The system owns everything.
21078        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21079            return;
21080        }
21081        final int callingUserId = UserHandle.getUserId(callingUid);
21082        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21083        if (pi == null) {
21084            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21085                    + callingUserId);
21086        }
21087        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21088            throw new SecurityException("Calling uid " + callingUid
21089                    + " does not own package " + pkg);
21090        }
21091    }
21092
21093    @Override
21094    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21095        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21096            return null;
21097        }
21098        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21099    }
21100
21101    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21102        UserManagerService ums = UserManagerService.getInstance();
21103        if (ums != null) {
21104            final UserInfo parent = ums.getProfileParent(userId);
21105            final int launcherUid = (parent != null) ? parent.id : userId;
21106            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21107            if (launcherComponent != null) {
21108                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21109                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21110                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21111                        .setPackage(launcherComponent.getPackageName());
21112                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21113            }
21114        }
21115    }
21116
21117    /**
21118     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21119     * then reports the most likely home activity or null if there are more than one.
21120     */
21121    private ComponentName getDefaultHomeActivity(int userId) {
21122        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21123        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21124        if (cn != null) {
21125            return cn;
21126        }
21127
21128        // Find the launcher with the highest priority and return that component if there are no
21129        // other home activity with the same priority.
21130        int lastPriority = Integer.MIN_VALUE;
21131        ComponentName lastComponent = null;
21132        final int size = allHomeCandidates.size();
21133        for (int i = 0; i < size; i++) {
21134            final ResolveInfo ri = allHomeCandidates.get(i);
21135            if (ri.priority > lastPriority) {
21136                lastComponent = ri.activityInfo.getComponentName();
21137                lastPriority = ri.priority;
21138            } else if (ri.priority == lastPriority) {
21139                // Two components found with same priority.
21140                lastComponent = null;
21141            }
21142        }
21143        return lastComponent;
21144    }
21145
21146    private Intent getHomeIntent() {
21147        Intent intent = new Intent(Intent.ACTION_MAIN);
21148        intent.addCategory(Intent.CATEGORY_HOME);
21149        intent.addCategory(Intent.CATEGORY_DEFAULT);
21150        return intent;
21151    }
21152
21153    private IntentFilter getHomeFilter() {
21154        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21155        filter.addCategory(Intent.CATEGORY_HOME);
21156        filter.addCategory(Intent.CATEGORY_DEFAULT);
21157        return filter;
21158    }
21159
21160    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21161            int userId) {
21162        Intent intent  = getHomeIntent();
21163        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21164                PackageManager.GET_META_DATA, userId);
21165        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21166                true, false, false, userId);
21167
21168        allHomeCandidates.clear();
21169        if (list != null) {
21170            for (ResolveInfo ri : list) {
21171                allHomeCandidates.add(ri);
21172            }
21173        }
21174        return (preferred == null || preferred.activityInfo == null)
21175                ? null
21176                : new ComponentName(preferred.activityInfo.packageName,
21177                        preferred.activityInfo.name);
21178    }
21179
21180    @Override
21181    public void setHomeActivity(ComponentName comp, int userId) {
21182        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21183            return;
21184        }
21185        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21186        getHomeActivitiesAsUser(homeActivities, userId);
21187
21188        boolean found = false;
21189
21190        final int size = homeActivities.size();
21191        final ComponentName[] set = new ComponentName[size];
21192        for (int i = 0; i < size; i++) {
21193            final ResolveInfo candidate = homeActivities.get(i);
21194            final ActivityInfo info = candidate.activityInfo;
21195            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21196            set[i] = activityName;
21197            if (!found && activityName.equals(comp)) {
21198                found = true;
21199            }
21200        }
21201        if (!found) {
21202            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21203                    + userId);
21204        }
21205        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21206                set, comp, userId);
21207    }
21208
21209    private @Nullable String getSetupWizardPackageName() {
21210        final Intent intent = new Intent(Intent.ACTION_MAIN);
21211        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21212
21213        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21214                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21215                        | MATCH_DISABLED_COMPONENTS,
21216                UserHandle.myUserId());
21217        if (matches.size() == 1) {
21218            return matches.get(0).getComponentInfo().packageName;
21219        } else {
21220            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21221                    + ": matches=" + matches);
21222            return null;
21223        }
21224    }
21225
21226    private @Nullable String getStorageManagerPackageName() {
21227        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21228
21229        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21230                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21231                        | MATCH_DISABLED_COMPONENTS,
21232                UserHandle.myUserId());
21233        if (matches.size() == 1) {
21234            return matches.get(0).getComponentInfo().packageName;
21235        } else {
21236            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21237                    + matches.size() + ": matches=" + matches);
21238            return null;
21239        }
21240    }
21241
21242    @Override
21243    public void setApplicationEnabledSetting(String appPackageName,
21244            int newState, int flags, int userId, String callingPackage) {
21245        if (!sUserManager.exists(userId)) return;
21246        if (callingPackage == null) {
21247            callingPackage = Integer.toString(Binder.getCallingUid());
21248        }
21249        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21250    }
21251
21252    @Override
21253    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21254        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21255        synchronized (mPackages) {
21256            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21257            if (pkgSetting != null) {
21258                pkgSetting.setUpdateAvailable(updateAvailable);
21259            }
21260        }
21261    }
21262
21263    @Override
21264    public void setComponentEnabledSetting(ComponentName componentName,
21265            int newState, int flags, int userId) {
21266        if (!sUserManager.exists(userId)) return;
21267        setEnabledSetting(componentName.getPackageName(),
21268                componentName.getClassName(), newState, flags, userId, null);
21269    }
21270
21271    private void setEnabledSetting(final String packageName, String className, int newState,
21272            final int flags, int userId, String callingPackage) {
21273        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21274              || newState == COMPONENT_ENABLED_STATE_ENABLED
21275              || newState == COMPONENT_ENABLED_STATE_DISABLED
21276              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21277              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21278            throw new IllegalArgumentException("Invalid new component state: "
21279                    + newState);
21280        }
21281        PackageSetting pkgSetting;
21282        final int callingUid = Binder.getCallingUid();
21283        final int permission;
21284        if (callingUid == Process.SYSTEM_UID) {
21285            permission = PackageManager.PERMISSION_GRANTED;
21286        } else {
21287            permission = mContext.checkCallingOrSelfPermission(
21288                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21289        }
21290        enforceCrossUserPermission(callingUid, userId,
21291                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21292        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21293        boolean sendNow = false;
21294        boolean isApp = (className == null);
21295        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21296        String componentName = isApp ? packageName : className;
21297        int packageUid = -1;
21298        ArrayList<String> components;
21299
21300        // reader
21301        synchronized (mPackages) {
21302            pkgSetting = mSettings.mPackages.get(packageName);
21303            if (pkgSetting == null) {
21304                if (!isCallerInstantApp) {
21305                    if (className == null) {
21306                        throw new IllegalArgumentException("Unknown package: " + packageName);
21307                    }
21308                    throw new IllegalArgumentException(
21309                            "Unknown component: " + packageName + "/" + className);
21310                } else {
21311                    // throw SecurityException to prevent leaking package information
21312                    throw new SecurityException(
21313                            "Attempt to change component state; "
21314                            + "pid=" + Binder.getCallingPid()
21315                            + ", uid=" + callingUid
21316                            + (className == null
21317                                    ? ", package=" + packageName
21318                                    : ", component=" + packageName + "/" + className));
21319                }
21320            }
21321        }
21322
21323        // Limit who can change which apps
21324        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21325            // Don't allow apps that don't have permission to modify other apps
21326            if (!allowedByPermission
21327                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21328                throw new SecurityException(
21329                        "Attempt to change component state; "
21330                        + "pid=" + Binder.getCallingPid()
21331                        + ", uid=" + callingUid
21332                        + (className == null
21333                                ? ", package=" + packageName
21334                                : ", component=" + packageName + "/" + className));
21335            }
21336            // Don't allow changing protected packages.
21337            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21338                throw new SecurityException("Cannot disable a protected package: " + packageName);
21339            }
21340        }
21341
21342        synchronized (mPackages) {
21343            if (callingUid == Process.SHELL_UID
21344                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21345                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21346                // unless it is a test package.
21347                int oldState = pkgSetting.getEnabled(userId);
21348                if (className == null
21349                    &&
21350                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21351                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21352                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21353                    &&
21354                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21355                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21356                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21357                    // ok
21358                } else {
21359                    throw new SecurityException(
21360                            "Shell cannot change component state for " + packageName + "/"
21361                            + className + " to " + newState);
21362                }
21363            }
21364            if (className == null) {
21365                // We're dealing with an application/package level state change
21366                if (pkgSetting.getEnabled(userId) == newState) {
21367                    // Nothing to do
21368                    return;
21369                }
21370                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21371                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21372                    // Don't care about who enables an app.
21373                    callingPackage = null;
21374                }
21375                pkgSetting.setEnabled(newState, userId, callingPackage);
21376                // pkgSetting.pkg.mSetEnabled = newState;
21377            } else {
21378                // We're dealing with a component level state change
21379                // First, verify that this is a valid class name.
21380                PackageParser.Package pkg = pkgSetting.pkg;
21381                if (pkg == null || !pkg.hasComponentClassName(className)) {
21382                    if (pkg != null &&
21383                            pkg.applicationInfo.targetSdkVersion >=
21384                                    Build.VERSION_CODES.JELLY_BEAN) {
21385                        throw new IllegalArgumentException("Component class " + className
21386                                + " does not exist in " + packageName);
21387                    } else {
21388                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21389                                + className + " does not exist in " + packageName);
21390                    }
21391                }
21392                switch (newState) {
21393                case COMPONENT_ENABLED_STATE_ENABLED:
21394                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21395                        return;
21396                    }
21397                    break;
21398                case COMPONENT_ENABLED_STATE_DISABLED:
21399                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21400                        return;
21401                    }
21402                    break;
21403                case COMPONENT_ENABLED_STATE_DEFAULT:
21404                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21405                        return;
21406                    }
21407                    break;
21408                default:
21409                    Slog.e(TAG, "Invalid new component state: " + newState);
21410                    return;
21411                }
21412            }
21413            scheduleWritePackageRestrictionsLocked(userId);
21414            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21415            final long callingId = Binder.clearCallingIdentity();
21416            try {
21417                updateInstantAppInstallerLocked(packageName);
21418            } finally {
21419                Binder.restoreCallingIdentity(callingId);
21420            }
21421            components = mPendingBroadcasts.get(userId, packageName);
21422            final boolean newPackage = components == null;
21423            if (newPackage) {
21424                components = new ArrayList<String>();
21425            }
21426            if (!components.contains(componentName)) {
21427                components.add(componentName);
21428            }
21429            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21430                sendNow = true;
21431                // Purge entry from pending broadcast list if another one exists already
21432                // since we are sending one right away.
21433                mPendingBroadcasts.remove(userId, packageName);
21434            } else {
21435                if (newPackage) {
21436                    mPendingBroadcasts.put(userId, packageName, components);
21437                }
21438                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21439                    // Schedule a message
21440                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21441                }
21442            }
21443        }
21444
21445        long callingId = Binder.clearCallingIdentity();
21446        try {
21447            if (sendNow) {
21448                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21449                sendPackageChangedBroadcast(packageName,
21450                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21451            }
21452        } finally {
21453            Binder.restoreCallingIdentity(callingId);
21454        }
21455    }
21456
21457    @Override
21458    public void flushPackageRestrictionsAsUser(int userId) {
21459        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21460            return;
21461        }
21462        if (!sUserManager.exists(userId)) {
21463            return;
21464        }
21465        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21466                false /* checkShell */, "flushPackageRestrictions");
21467        synchronized (mPackages) {
21468            mSettings.writePackageRestrictionsLPr(userId);
21469            mDirtyUsers.remove(userId);
21470            if (mDirtyUsers.isEmpty()) {
21471                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21472            }
21473        }
21474    }
21475
21476    private void sendPackageChangedBroadcast(String packageName,
21477            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21478        if (DEBUG_INSTALL)
21479            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21480                    + componentNames);
21481        Bundle extras = new Bundle(4);
21482        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21483        String nameList[] = new String[componentNames.size()];
21484        componentNames.toArray(nameList);
21485        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21486        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21487        extras.putInt(Intent.EXTRA_UID, packageUid);
21488        // If this is not reporting a change of the overall package, then only send it
21489        // to registered receivers.  We don't want to launch a swath of apps for every
21490        // little component state change.
21491        final int flags = !componentNames.contains(packageName)
21492                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21493        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21494                new int[] {UserHandle.getUserId(packageUid)});
21495    }
21496
21497    @Override
21498    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21499        if (!sUserManager.exists(userId)) return;
21500        final int callingUid = Binder.getCallingUid();
21501        if (getInstantAppPackageName(callingUid) != null) {
21502            return;
21503        }
21504        final int permission = mContext.checkCallingOrSelfPermission(
21505                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21506        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21507        enforceCrossUserPermission(callingUid, userId,
21508                true /* requireFullPermission */, true /* checkShell */, "stop package");
21509        // writer
21510        synchronized (mPackages) {
21511            final PackageSetting ps = mSettings.mPackages.get(packageName);
21512            if (!filterAppAccessLPr(ps, callingUid, userId)
21513                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21514                            allowedByPermission, callingUid, userId)) {
21515                scheduleWritePackageRestrictionsLocked(userId);
21516            }
21517        }
21518    }
21519
21520    @Override
21521    public String getInstallerPackageName(String packageName) {
21522        final int callingUid = Binder.getCallingUid();
21523        if (getInstantAppPackageName(callingUid) != null) {
21524            return null;
21525        }
21526        // reader
21527        synchronized (mPackages) {
21528            final PackageSetting ps = mSettings.mPackages.get(packageName);
21529            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21530                return null;
21531            }
21532            return mSettings.getInstallerPackageNameLPr(packageName);
21533        }
21534    }
21535
21536    public boolean isOrphaned(String packageName) {
21537        // reader
21538        synchronized (mPackages) {
21539            return mSettings.isOrphaned(packageName);
21540        }
21541    }
21542
21543    @Override
21544    public int getApplicationEnabledSetting(String packageName, int userId) {
21545        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21546        int callingUid = Binder.getCallingUid();
21547        enforceCrossUserPermission(callingUid, userId,
21548                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21549        // reader
21550        synchronized (mPackages) {
21551            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21552                return COMPONENT_ENABLED_STATE_DISABLED;
21553            }
21554            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21555        }
21556    }
21557
21558    @Override
21559    public int getComponentEnabledSetting(ComponentName component, int userId) {
21560        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21561        int callingUid = Binder.getCallingUid();
21562        enforceCrossUserPermission(callingUid, userId,
21563                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21564        synchronized (mPackages) {
21565            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21566                    component, TYPE_UNKNOWN, userId)) {
21567                return COMPONENT_ENABLED_STATE_DISABLED;
21568            }
21569            return mSettings.getComponentEnabledSettingLPr(component, userId);
21570        }
21571    }
21572
21573    @Override
21574    public void enterSafeMode() {
21575        enforceSystemOrRoot("Only the system can request entering safe mode");
21576
21577        if (!mSystemReady) {
21578            mSafeMode = true;
21579        }
21580    }
21581
21582    @Override
21583    public void systemReady() {
21584        enforceSystemOrRoot("Only the system can claim the system is ready");
21585
21586        mSystemReady = true;
21587        final ContentResolver resolver = mContext.getContentResolver();
21588        ContentObserver co = new ContentObserver(mHandler) {
21589            @Override
21590            public void onChange(boolean selfChange) {
21591                mEphemeralAppsDisabled =
21592                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21593                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21594            }
21595        };
21596        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21597                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21598                false, co, UserHandle.USER_SYSTEM);
21599        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21600                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21601        co.onChange(true);
21602
21603        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21604        // disabled after already being started.
21605        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21606                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21607
21608        // Read the compatibilty setting when the system is ready.
21609        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21610                mContext.getContentResolver(),
21611                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21612        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21613        if (DEBUG_SETTINGS) {
21614            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21615        }
21616
21617        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21618
21619        synchronized (mPackages) {
21620            // Verify that all of the preferred activity components actually
21621            // exist.  It is possible for applications to be updated and at
21622            // that point remove a previously declared activity component that
21623            // had been set as a preferred activity.  We try to clean this up
21624            // the next time we encounter that preferred activity, but it is
21625            // possible for the user flow to never be able to return to that
21626            // situation so here we do a sanity check to make sure we haven't
21627            // left any junk around.
21628            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21629            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21630                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21631                removed.clear();
21632                for (PreferredActivity pa : pir.filterSet()) {
21633                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21634                        removed.add(pa);
21635                    }
21636                }
21637                if (removed.size() > 0) {
21638                    for (int r=0; r<removed.size(); r++) {
21639                        PreferredActivity pa = removed.get(r);
21640                        Slog.w(TAG, "Removing dangling preferred activity: "
21641                                + pa.mPref.mComponent);
21642                        pir.removeFilter(pa);
21643                    }
21644                    mSettings.writePackageRestrictionsLPr(
21645                            mSettings.mPreferredActivities.keyAt(i));
21646                }
21647            }
21648
21649            for (int userId : UserManagerService.getInstance().getUserIds()) {
21650                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21651                    grantPermissionsUserIds = ArrayUtils.appendInt(
21652                            grantPermissionsUserIds, userId);
21653                }
21654            }
21655        }
21656        sUserManager.systemReady();
21657
21658        // If we upgraded grant all default permissions before kicking off.
21659        for (int userId : grantPermissionsUserIds) {
21660            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21661        }
21662
21663        // If we did not grant default permissions, we preload from this the
21664        // default permission exceptions lazily to ensure we don't hit the
21665        // disk on a new user creation.
21666        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21667            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21668        }
21669
21670        // Kick off any messages waiting for system ready
21671        if (mPostSystemReadyMessages != null) {
21672            for (Message msg : mPostSystemReadyMessages) {
21673                msg.sendToTarget();
21674            }
21675            mPostSystemReadyMessages = null;
21676        }
21677
21678        // Watch for external volumes that come and go over time
21679        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21680        storage.registerListener(mStorageListener);
21681
21682        mInstallerService.systemReady();
21683        mPackageDexOptimizer.systemReady();
21684
21685        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21686                StorageManagerInternal.class);
21687        StorageManagerInternal.addExternalStoragePolicy(
21688                new StorageManagerInternal.ExternalStorageMountPolicy() {
21689            @Override
21690            public int getMountMode(int uid, String packageName) {
21691                if (Process.isIsolated(uid)) {
21692                    return Zygote.MOUNT_EXTERNAL_NONE;
21693                }
21694                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21695                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21696                }
21697                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21698                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21699                }
21700                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21701                    return Zygote.MOUNT_EXTERNAL_READ;
21702                }
21703                return Zygote.MOUNT_EXTERNAL_WRITE;
21704            }
21705
21706            @Override
21707            public boolean hasExternalStorage(int uid, String packageName) {
21708                return true;
21709            }
21710        });
21711
21712        // Now that we're mostly running, clean up stale users and apps
21713        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21714        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21715
21716        if (mPrivappPermissionsViolations != null) {
21717            Slog.wtf(TAG,"Signature|privileged permissions not in "
21718                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21719            mPrivappPermissionsViolations = null;
21720        }
21721    }
21722
21723    public void waitForAppDataPrepared() {
21724        if (mPrepareAppDataFuture == null) {
21725            return;
21726        }
21727        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21728        mPrepareAppDataFuture = null;
21729    }
21730
21731    @Override
21732    public boolean isSafeMode() {
21733        // allow instant applications
21734        return mSafeMode;
21735    }
21736
21737    @Override
21738    public boolean hasSystemUidErrors() {
21739        // allow instant applications
21740        return mHasSystemUidErrors;
21741    }
21742
21743    static String arrayToString(int[] array) {
21744        StringBuffer buf = new StringBuffer(128);
21745        buf.append('[');
21746        if (array != null) {
21747            for (int i=0; i<array.length; i++) {
21748                if (i > 0) buf.append(", ");
21749                buf.append(array[i]);
21750            }
21751        }
21752        buf.append(']');
21753        return buf.toString();
21754    }
21755
21756    static class DumpState {
21757        public static final int DUMP_LIBS = 1 << 0;
21758        public static final int DUMP_FEATURES = 1 << 1;
21759        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21760        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21761        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21762        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21763        public static final int DUMP_PERMISSIONS = 1 << 6;
21764        public static final int DUMP_PACKAGES = 1 << 7;
21765        public static final int DUMP_SHARED_USERS = 1 << 8;
21766        public static final int DUMP_MESSAGES = 1 << 9;
21767        public static final int DUMP_PROVIDERS = 1 << 10;
21768        public static final int DUMP_VERIFIERS = 1 << 11;
21769        public static final int DUMP_PREFERRED = 1 << 12;
21770        public static final int DUMP_PREFERRED_XML = 1 << 13;
21771        public static final int DUMP_KEYSETS = 1 << 14;
21772        public static final int DUMP_VERSION = 1 << 15;
21773        public static final int DUMP_INSTALLS = 1 << 16;
21774        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21775        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21776        public static final int DUMP_FROZEN = 1 << 19;
21777        public static final int DUMP_DEXOPT = 1 << 20;
21778        public static final int DUMP_COMPILER_STATS = 1 << 21;
21779        public static final int DUMP_CHANGES = 1 << 22;
21780
21781        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21782
21783        private int mTypes;
21784
21785        private int mOptions;
21786
21787        private boolean mTitlePrinted;
21788
21789        private SharedUserSetting mSharedUser;
21790
21791        public boolean isDumping(int type) {
21792            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21793                return true;
21794            }
21795
21796            return (mTypes & type) != 0;
21797        }
21798
21799        public void setDump(int type) {
21800            mTypes |= type;
21801        }
21802
21803        public boolean isOptionEnabled(int option) {
21804            return (mOptions & option) != 0;
21805        }
21806
21807        public void setOptionEnabled(int option) {
21808            mOptions |= option;
21809        }
21810
21811        public boolean onTitlePrinted() {
21812            final boolean printed = mTitlePrinted;
21813            mTitlePrinted = true;
21814            return printed;
21815        }
21816
21817        public boolean getTitlePrinted() {
21818            return mTitlePrinted;
21819        }
21820
21821        public void setTitlePrinted(boolean enabled) {
21822            mTitlePrinted = enabled;
21823        }
21824
21825        public SharedUserSetting getSharedUser() {
21826            return mSharedUser;
21827        }
21828
21829        public void setSharedUser(SharedUserSetting user) {
21830            mSharedUser = user;
21831        }
21832    }
21833
21834    @Override
21835    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21836            FileDescriptor err, String[] args, ShellCallback callback,
21837            ResultReceiver resultReceiver) {
21838        (new PackageManagerShellCommand(this)).exec(
21839                this, in, out, err, args, callback, resultReceiver);
21840    }
21841
21842    @Override
21843    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21844        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21845
21846        DumpState dumpState = new DumpState();
21847        boolean fullPreferred = false;
21848        boolean checkin = false;
21849
21850        String packageName = null;
21851        ArraySet<String> permissionNames = null;
21852
21853        int opti = 0;
21854        while (opti < args.length) {
21855            String opt = args[opti];
21856            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21857                break;
21858            }
21859            opti++;
21860
21861            if ("-a".equals(opt)) {
21862                // Right now we only know how to print all.
21863            } else if ("-h".equals(opt)) {
21864                pw.println("Package manager dump options:");
21865                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21866                pw.println("    --checkin: dump for a checkin");
21867                pw.println("    -f: print details of intent filters");
21868                pw.println("    -h: print this help");
21869                pw.println("  cmd may be one of:");
21870                pw.println("    l[ibraries]: list known shared libraries");
21871                pw.println("    f[eatures]: list device features");
21872                pw.println("    k[eysets]: print known keysets");
21873                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21874                pw.println("    perm[issions]: dump permissions");
21875                pw.println("    permission [name ...]: dump declaration and use of given permission");
21876                pw.println("    pref[erred]: print preferred package settings");
21877                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21878                pw.println("    prov[iders]: dump content providers");
21879                pw.println("    p[ackages]: dump installed packages");
21880                pw.println("    s[hared-users]: dump shared user IDs");
21881                pw.println("    m[essages]: print collected runtime messages");
21882                pw.println("    v[erifiers]: print package verifier info");
21883                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21884                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21885                pw.println("    version: print database version info");
21886                pw.println("    write: write current settings now");
21887                pw.println("    installs: details about install sessions");
21888                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21889                pw.println("    dexopt: dump dexopt state");
21890                pw.println("    compiler-stats: dump compiler statistics");
21891                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21892                pw.println("    <package.name>: info about given package");
21893                return;
21894            } else if ("--checkin".equals(opt)) {
21895                checkin = true;
21896            } else if ("-f".equals(opt)) {
21897                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21898            } else if ("--proto".equals(opt)) {
21899                dumpProto(fd);
21900                return;
21901            } else {
21902                pw.println("Unknown argument: " + opt + "; use -h for help");
21903            }
21904        }
21905
21906        // Is the caller requesting to dump a particular piece of data?
21907        if (opti < args.length) {
21908            String cmd = args[opti];
21909            opti++;
21910            // Is this a package name?
21911            if ("android".equals(cmd) || cmd.contains(".")) {
21912                packageName = cmd;
21913                // When dumping a single package, we always dump all of its
21914                // filter information since the amount of data will be reasonable.
21915                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21916            } else if ("check-permission".equals(cmd)) {
21917                if (opti >= args.length) {
21918                    pw.println("Error: check-permission missing permission argument");
21919                    return;
21920                }
21921                String perm = args[opti];
21922                opti++;
21923                if (opti >= args.length) {
21924                    pw.println("Error: check-permission missing package argument");
21925                    return;
21926                }
21927
21928                String pkg = args[opti];
21929                opti++;
21930                int user = UserHandle.getUserId(Binder.getCallingUid());
21931                if (opti < args.length) {
21932                    try {
21933                        user = Integer.parseInt(args[opti]);
21934                    } catch (NumberFormatException e) {
21935                        pw.println("Error: check-permission user argument is not a number: "
21936                                + args[opti]);
21937                        return;
21938                    }
21939                }
21940
21941                // Normalize package name to handle renamed packages and static libs
21942                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21943
21944                pw.println(checkPermission(perm, pkg, user));
21945                return;
21946            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21947                dumpState.setDump(DumpState.DUMP_LIBS);
21948            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21949                dumpState.setDump(DumpState.DUMP_FEATURES);
21950            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21951                if (opti >= args.length) {
21952                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21953                            | DumpState.DUMP_SERVICE_RESOLVERS
21954                            | DumpState.DUMP_RECEIVER_RESOLVERS
21955                            | DumpState.DUMP_CONTENT_RESOLVERS);
21956                } else {
21957                    while (opti < args.length) {
21958                        String name = args[opti];
21959                        if ("a".equals(name) || "activity".equals(name)) {
21960                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21961                        } else if ("s".equals(name) || "service".equals(name)) {
21962                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21963                        } else if ("r".equals(name) || "receiver".equals(name)) {
21964                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21965                        } else if ("c".equals(name) || "content".equals(name)) {
21966                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21967                        } else {
21968                            pw.println("Error: unknown resolver table type: " + name);
21969                            return;
21970                        }
21971                        opti++;
21972                    }
21973                }
21974            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21975                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21976            } else if ("permission".equals(cmd)) {
21977                if (opti >= args.length) {
21978                    pw.println("Error: permission requires permission name");
21979                    return;
21980                }
21981                permissionNames = new ArraySet<>();
21982                while (opti < args.length) {
21983                    permissionNames.add(args[opti]);
21984                    opti++;
21985                }
21986                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21987                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21988            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21989                dumpState.setDump(DumpState.DUMP_PREFERRED);
21990            } else if ("preferred-xml".equals(cmd)) {
21991                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21992                if (opti < args.length && "--full".equals(args[opti])) {
21993                    fullPreferred = true;
21994                    opti++;
21995                }
21996            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21997                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21998            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21999                dumpState.setDump(DumpState.DUMP_PACKAGES);
22000            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22001                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22002            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22003                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22004            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22005                dumpState.setDump(DumpState.DUMP_MESSAGES);
22006            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22007                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22008            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22009                    || "intent-filter-verifiers".equals(cmd)) {
22010                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22011            } else if ("version".equals(cmd)) {
22012                dumpState.setDump(DumpState.DUMP_VERSION);
22013            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22014                dumpState.setDump(DumpState.DUMP_KEYSETS);
22015            } else if ("installs".equals(cmd)) {
22016                dumpState.setDump(DumpState.DUMP_INSTALLS);
22017            } else if ("frozen".equals(cmd)) {
22018                dumpState.setDump(DumpState.DUMP_FROZEN);
22019            } else if ("dexopt".equals(cmd)) {
22020                dumpState.setDump(DumpState.DUMP_DEXOPT);
22021            } else if ("compiler-stats".equals(cmd)) {
22022                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22023            } else if ("changes".equals(cmd)) {
22024                dumpState.setDump(DumpState.DUMP_CHANGES);
22025            } else if ("write".equals(cmd)) {
22026                synchronized (mPackages) {
22027                    mSettings.writeLPr();
22028                    pw.println("Settings written.");
22029                    return;
22030                }
22031            }
22032        }
22033
22034        if (checkin) {
22035            pw.println("vers,1");
22036        }
22037
22038        // reader
22039        synchronized (mPackages) {
22040            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22041                if (!checkin) {
22042                    if (dumpState.onTitlePrinted())
22043                        pw.println();
22044                    pw.println("Database versions:");
22045                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22046                }
22047            }
22048
22049            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22050                if (!checkin) {
22051                    if (dumpState.onTitlePrinted())
22052                        pw.println();
22053                    pw.println("Verifiers:");
22054                    pw.print("  Required: ");
22055                    pw.print(mRequiredVerifierPackage);
22056                    pw.print(" (uid=");
22057                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22058                            UserHandle.USER_SYSTEM));
22059                    pw.println(")");
22060                } else if (mRequiredVerifierPackage != null) {
22061                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22062                    pw.print(",");
22063                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22064                            UserHandle.USER_SYSTEM));
22065                }
22066            }
22067
22068            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22069                    packageName == null) {
22070                if (mIntentFilterVerifierComponent != null) {
22071                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22072                    if (!checkin) {
22073                        if (dumpState.onTitlePrinted())
22074                            pw.println();
22075                        pw.println("Intent Filter Verifier:");
22076                        pw.print("  Using: ");
22077                        pw.print(verifierPackageName);
22078                        pw.print(" (uid=");
22079                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22080                                UserHandle.USER_SYSTEM));
22081                        pw.println(")");
22082                    } else if (verifierPackageName != null) {
22083                        pw.print("ifv,"); pw.print(verifierPackageName);
22084                        pw.print(",");
22085                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22086                                UserHandle.USER_SYSTEM));
22087                    }
22088                } else {
22089                    pw.println();
22090                    pw.println("No Intent Filter Verifier available!");
22091                }
22092            }
22093
22094            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22095                boolean printedHeader = false;
22096                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22097                while (it.hasNext()) {
22098                    String libName = it.next();
22099                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22100                    if (versionedLib == null) {
22101                        continue;
22102                    }
22103                    final int versionCount = versionedLib.size();
22104                    for (int i = 0; i < versionCount; i++) {
22105                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22106                        if (!checkin) {
22107                            if (!printedHeader) {
22108                                if (dumpState.onTitlePrinted())
22109                                    pw.println();
22110                                pw.println("Libraries:");
22111                                printedHeader = true;
22112                            }
22113                            pw.print("  ");
22114                        } else {
22115                            pw.print("lib,");
22116                        }
22117                        pw.print(libEntry.info.getName());
22118                        if (libEntry.info.isStatic()) {
22119                            pw.print(" version=" + libEntry.info.getVersion());
22120                        }
22121                        if (!checkin) {
22122                            pw.print(" -> ");
22123                        }
22124                        if (libEntry.path != null) {
22125                            pw.print(" (jar) ");
22126                            pw.print(libEntry.path);
22127                        } else {
22128                            pw.print(" (apk) ");
22129                            pw.print(libEntry.apk);
22130                        }
22131                        pw.println();
22132                    }
22133                }
22134            }
22135
22136            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22137                if (dumpState.onTitlePrinted())
22138                    pw.println();
22139                if (!checkin) {
22140                    pw.println("Features:");
22141                }
22142
22143                synchronized (mAvailableFeatures) {
22144                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22145                        if (checkin) {
22146                            pw.print("feat,");
22147                            pw.print(feat.name);
22148                            pw.print(",");
22149                            pw.println(feat.version);
22150                        } else {
22151                            pw.print("  ");
22152                            pw.print(feat.name);
22153                            if (feat.version > 0) {
22154                                pw.print(" version=");
22155                                pw.print(feat.version);
22156                            }
22157                            pw.println();
22158                        }
22159                    }
22160                }
22161            }
22162
22163            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22164                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22165                        : "Activity Resolver Table:", "  ", packageName,
22166                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22167                    dumpState.setTitlePrinted(true);
22168                }
22169            }
22170            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22171                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22172                        : "Receiver Resolver Table:", "  ", packageName,
22173                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22174                    dumpState.setTitlePrinted(true);
22175                }
22176            }
22177            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22178                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22179                        : "Service Resolver Table:", "  ", packageName,
22180                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22181                    dumpState.setTitlePrinted(true);
22182                }
22183            }
22184            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22185                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22186                        : "Provider Resolver Table:", "  ", packageName,
22187                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22188                    dumpState.setTitlePrinted(true);
22189                }
22190            }
22191
22192            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22193                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22194                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22195                    int user = mSettings.mPreferredActivities.keyAt(i);
22196                    if (pir.dump(pw,
22197                            dumpState.getTitlePrinted()
22198                                ? "\nPreferred Activities User " + user + ":"
22199                                : "Preferred Activities User " + user + ":", "  ",
22200                            packageName, true, false)) {
22201                        dumpState.setTitlePrinted(true);
22202                    }
22203                }
22204            }
22205
22206            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22207                pw.flush();
22208                FileOutputStream fout = new FileOutputStream(fd);
22209                BufferedOutputStream str = new BufferedOutputStream(fout);
22210                XmlSerializer serializer = new FastXmlSerializer();
22211                try {
22212                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22213                    serializer.startDocument(null, true);
22214                    serializer.setFeature(
22215                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22216                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22217                    serializer.endDocument();
22218                    serializer.flush();
22219                } catch (IllegalArgumentException e) {
22220                    pw.println("Failed writing: " + e);
22221                } catch (IllegalStateException e) {
22222                    pw.println("Failed writing: " + e);
22223                } catch (IOException e) {
22224                    pw.println("Failed writing: " + e);
22225                }
22226            }
22227
22228            if (!checkin
22229                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22230                    && packageName == null) {
22231                pw.println();
22232                int count = mSettings.mPackages.size();
22233                if (count == 0) {
22234                    pw.println("No applications!");
22235                    pw.println();
22236                } else {
22237                    final String prefix = "  ";
22238                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22239                    if (allPackageSettings.size() == 0) {
22240                        pw.println("No domain preferred apps!");
22241                        pw.println();
22242                    } else {
22243                        pw.println("App verification status:");
22244                        pw.println();
22245                        count = 0;
22246                        for (PackageSetting ps : allPackageSettings) {
22247                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22248                            if (ivi == null || ivi.getPackageName() == null) continue;
22249                            pw.println(prefix + "Package: " + ivi.getPackageName());
22250                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22251                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22252                            pw.println();
22253                            count++;
22254                        }
22255                        if (count == 0) {
22256                            pw.println(prefix + "No app verification established.");
22257                            pw.println();
22258                        }
22259                        for (int userId : sUserManager.getUserIds()) {
22260                            pw.println("App linkages for user " + userId + ":");
22261                            pw.println();
22262                            count = 0;
22263                            for (PackageSetting ps : allPackageSettings) {
22264                                final long status = ps.getDomainVerificationStatusForUser(userId);
22265                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22266                                        && !DEBUG_DOMAIN_VERIFICATION) {
22267                                    continue;
22268                                }
22269                                pw.println(prefix + "Package: " + ps.name);
22270                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22271                                String statusStr = IntentFilterVerificationInfo.
22272                                        getStatusStringFromValue(status);
22273                                pw.println(prefix + "Status:  " + statusStr);
22274                                pw.println();
22275                                count++;
22276                            }
22277                            if (count == 0) {
22278                                pw.println(prefix + "No configured app linkages.");
22279                                pw.println();
22280                            }
22281                        }
22282                    }
22283                }
22284            }
22285
22286            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22287                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22288                if (packageName == null && permissionNames == null) {
22289                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22290                        if (iperm == 0) {
22291                            if (dumpState.onTitlePrinted())
22292                                pw.println();
22293                            pw.println("AppOp Permissions:");
22294                        }
22295                        pw.print("  AppOp Permission ");
22296                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22297                        pw.println(":");
22298                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22299                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22300                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22301                        }
22302                    }
22303                }
22304            }
22305
22306            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22307                boolean printedSomething = false;
22308                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22309                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22310                        continue;
22311                    }
22312                    if (!printedSomething) {
22313                        if (dumpState.onTitlePrinted())
22314                            pw.println();
22315                        pw.println("Registered ContentProviders:");
22316                        printedSomething = true;
22317                    }
22318                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22319                    pw.print("    "); pw.println(p.toString());
22320                }
22321                printedSomething = false;
22322                for (Map.Entry<String, PackageParser.Provider> entry :
22323                        mProvidersByAuthority.entrySet()) {
22324                    PackageParser.Provider p = entry.getValue();
22325                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22326                        continue;
22327                    }
22328                    if (!printedSomething) {
22329                        if (dumpState.onTitlePrinted())
22330                            pw.println();
22331                        pw.println("ContentProvider Authorities:");
22332                        printedSomething = true;
22333                    }
22334                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22335                    pw.print("    "); pw.println(p.toString());
22336                    if (p.info != null && p.info.applicationInfo != null) {
22337                        final String appInfo = p.info.applicationInfo.toString();
22338                        pw.print("      applicationInfo="); pw.println(appInfo);
22339                    }
22340                }
22341            }
22342
22343            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22344                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22345            }
22346
22347            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22348                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22349            }
22350
22351            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22352                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22353            }
22354
22355            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22356                if (dumpState.onTitlePrinted()) pw.println();
22357                pw.println("Package Changes:");
22358                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22359                final int K = mChangedPackages.size();
22360                for (int i = 0; i < K; i++) {
22361                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22362                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22363                    final int N = changes.size();
22364                    if (N == 0) {
22365                        pw.print("    "); pw.println("No packages changed");
22366                    } else {
22367                        for (int j = 0; j < N; j++) {
22368                            final String pkgName = changes.valueAt(j);
22369                            final int sequenceNumber = changes.keyAt(j);
22370                            pw.print("    ");
22371                            pw.print("seq=");
22372                            pw.print(sequenceNumber);
22373                            pw.print(", package=");
22374                            pw.println(pkgName);
22375                        }
22376                    }
22377                }
22378            }
22379
22380            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22381                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22382            }
22383
22384            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22385                // XXX should handle packageName != null by dumping only install data that
22386                // the given package is involved with.
22387                if (dumpState.onTitlePrinted()) pw.println();
22388
22389                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22390                ipw.println();
22391                ipw.println("Frozen packages:");
22392                ipw.increaseIndent();
22393                if (mFrozenPackages.size() == 0) {
22394                    ipw.println("(none)");
22395                } else {
22396                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22397                        ipw.println(mFrozenPackages.valueAt(i));
22398                    }
22399                }
22400                ipw.decreaseIndent();
22401            }
22402
22403            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22404                if (dumpState.onTitlePrinted()) pw.println();
22405                dumpDexoptStateLPr(pw, packageName);
22406            }
22407
22408            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22409                if (dumpState.onTitlePrinted()) pw.println();
22410                dumpCompilerStatsLPr(pw, packageName);
22411            }
22412
22413            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22414                if (dumpState.onTitlePrinted()) pw.println();
22415                mSettings.dumpReadMessagesLPr(pw, dumpState);
22416
22417                pw.println();
22418                pw.println("Package warning messages:");
22419                BufferedReader in = null;
22420                String line = null;
22421                try {
22422                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22423                    while ((line = in.readLine()) != null) {
22424                        if (line.contains("ignored: updated version")) continue;
22425                        pw.println(line);
22426                    }
22427                } catch (IOException ignored) {
22428                } finally {
22429                    IoUtils.closeQuietly(in);
22430                }
22431            }
22432
22433            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22434                BufferedReader in = null;
22435                String line = null;
22436                try {
22437                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22438                    while ((line = in.readLine()) != null) {
22439                        if (line.contains("ignored: updated version")) continue;
22440                        pw.print("msg,");
22441                        pw.println(line);
22442                    }
22443                } catch (IOException ignored) {
22444                } finally {
22445                    IoUtils.closeQuietly(in);
22446                }
22447            }
22448        }
22449
22450        // PackageInstaller should be called outside of mPackages lock
22451        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22452            // XXX should handle packageName != null by dumping only install data that
22453            // the given package is involved with.
22454            if (dumpState.onTitlePrinted()) pw.println();
22455            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22456        }
22457    }
22458
22459    private void dumpProto(FileDescriptor fd) {
22460        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22461
22462        synchronized (mPackages) {
22463            final long requiredVerifierPackageToken =
22464                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22465            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22466            proto.write(
22467                    PackageServiceDumpProto.PackageShortProto.UID,
22468                    getPackageUid(
22469                            mRequiredVerifierPackage,
22470                            MATCH_DEBUG_TRIAGED_MISSING,
22471                            UserHandle.USER_SYSTEM));
22472            proto.end(requiredVerifierPackageToken);
22473
22474            if (mIntentFilterVerifierComponent != null) {
22475                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22476                final long verifierPackageToken =
22477                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22478                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22479                proto.write(
22480                        PackageServiceDumpProto.PackageShortProto.UID,
22481                        getPackageUid(
22482                                verifierPackageName,
22483                                MATCH_DEBUG_TRIAGED_MISSING,
22484                                UserHandle.USER_SYSTEM));
22485                proto.end(verifierPackageToken);
22486            }
22487
22488            dumpSharedLibrariesProto(proto);
22489            dumpFeaturesProto(proto);
22490            mSettings.dumpPackagesProto(proto);
22491            mSettings.dumpSharedUsersProto(proto);
22492            dumpMessagesProto(proto);
22493        }
22494        proto.flush();
22495    }
22496
22497    private void dumpMessagesProto(ProtoOutputStream proto) {
22498        BufferedReader in = null;
22499        String line = null;
22500        try {
22501            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22502            while ((line = in.readLine()) != null) {
22503                if (line.contains("ignored: updated version")) continue;
22504                proto.write(PackageServiceDumpProto.MESSAGES, line);
22505            }
22506        } catch (IOException ignored) {
22507        } finally {
22508            IoUtils.closeQuietly(in);
22509        }
22510    }
22511
22512    private void dumpFeaturesProto(ProtoOutputStream proto) {
22513        synchronized (mAvailableFeatures) {
22514            final int count = mAvailableFeatures.size();
22515            for (int i = 0; i < count; i++) {
22516                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22517                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22518                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22519                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22520                proto.end(featureToken);
22521            }
22522        }
22523    }
22524
22525    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22526        final int count = mSharedLibraries.size();
22527        for (int i = 0; i < count; i++) {
22528            final String libName = mSharedLibraries.keyAt(i);
22529            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22530            if (versionedLib == null) {
22531                continue;
22532            }
22533            final int versionCount = versionedLib.size();
22534            for (int j = 0; j < versionCount; j++) {
22535                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22536                final long sharedLibraryToken =
22537                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22538                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22539                final boolean isJar = (libEntry.path != null);
22540                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22541                if (isJar) {
22542                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22543                } else {
22544                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22545                }
22546                proto.end(sharedLibraryToken);
22547            }
22548        }
22549    }
22550
22551    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22552        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22553        ipw.println();
22554        ipw.println("Dexopt state:");
22555        ipw.increaseIndent();
22556        Collection<PackageParser.Package> packages = null;
22557        if (packageName != null) {
22558            PackageParser.Package targetPackage = mPackages.get(packageName);
22559            if (targetPackage != null) {
22560                packages = Collections.singletonList(targetPackage);
22561            } else {
22562                ipw.println("Unable to find package: " + packageName);
22563                return;
22564            }
22565        } else {
22566            packages = mPackages.values();
22567        }
22568
22569        for (PackageParser.Package pkg : packages) {
22570            ipw.println("[" + pkg.packageName + "]");
22571            ipw.increaseIndent();
22572            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
22573                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
22574            ipw.decreaseIndent();
22575        }
22576    }
22577
22578    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22579        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22580        ipw.println();
22581        ipw.println("Compiler stats:");
22582        ipw.increaseIndent();
22583        Collection<PackageParser.Package> packages = null;
22584        if (packageName != null) {
22585            PackageParser.Package targetPackage = mPackages.get(packageName);
22586            if (targetPackage != null) {
22587                packages = Collections.singletonList(targetPackage);
22588            } else {
22589                ipw.println("Unable to find package: " + packageName);
22590                return;
22591            }
22592        } else {
22593            packages = mPackages.values();
22594        }
22595
22596        for (PackageParser.Package pkg : packages) {
22597            ipw.println("[" + pkg.packageName + "]");
22598            ipw.increaseIndent();
22599
22600            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22601            if (stats == null) {
22602                ipw.println("(No recorded stats)");
22603            } else {
22604                stats.dump(ipw);
22605            }
22606            ipw.decreaseIndent();
22607        }
22608    }
22609
22610    private String dumpDomainString(String packageName) {
22611        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22612                .getList();
22613        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22614
22615        ArraySet<String> result = new ArraySet<>();
22616        if (iviList.size() > 0) {
22617            for (IntentFilterVerificationInfo ivi : iviList) {
22618                for (String host : ivi.getDomains()) {
22619                    result.add(host);
22620                }
22621            }
22622        }
22623        if (filters != null && filters.size() > 0) {
22624            for (IntentFilter filter : filters) {
22625                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22626                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22627                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22628                    result.addAll(filter.getHostsList());
22629                }
22630            }
22631        }
22632
22633        StringBuilder sb = new StringBuilder(result.size() * 16);
22634        for (String domain : result) {
22635            if (sb.length() > 0) sb.append(" ");
22636            sb.append(domain);
22637        }
22638        return sb.toString();
22639    }
22640
22641    // ------- apps on sdcard specific code -------
22642    static final boolean DEBUG_SD_INSTALL = false;
22643
22644    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22645
22646    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22647
22648    private boolean mMediaMounted = false;
22649
22650    static String getEncryptKey() {
22651        try {
22652            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22653                    SD_ENCRYPTION_KEYSTORE_NAME);
22654            if (sdEncKey == null) {
22655                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22656                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22657                if (sdEncKey == null) {
22658                    Slog.e(TAG, "Failed to create encryption keys");
22659                    return null;
22660                }
22661            }
22662            return sdEncKey;
22663        } catch (NoSuchAlgorithmException nsae) {
22664            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22665            return null;
22666        } catch (IOException ioe) {
22667            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22668            return null;
22669        }
22670    }
22671
22672    /*
22673     * Update media status on PackageManager.
22674     */
22675    @Override
22676    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22677        enforceSystemOrRoot("Media status can only be updated by the system");
22678        // reader; this apparently protects mMediaMounted, but should probably
22679        // be a different lock in that case.
22680        synchronized (mPackages) {
22681            Log.i(TAG, "Updating external media status from "
22682                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22683                    + (mediaStatus ? "mounted" : "unmounted"));
22684            if (DEBUG_SD_INSTALL)
22685                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22686                        + ", mMediaMounted=" + mMediaMounted);
22687            if (mediaStatus == mMediaMounted) {
22688                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22689                        : 0, -1);
22690                mHandler.sendMessage(msg);
22691                return;
22692            }
22693            mMediaMounted = mediaStatus;
22694        }
22695        // Queue up an async operation since the package installation may take a
22696        // little while.
22697        mHandler.post(new Runnable() {
22698            public void run() {
22699                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22700            }
22701        });
22702    }
22703
22704    /**
22705     * Called by StorageManagerService when the initial ASECs to scan are available.
22706     * Should block until all the ASEC containers are finished being scanned.
22707     */
22708    public void scanAvailableAsecs() {
22709        updateExternalMediaStatusInner(true, false, false);
22710    }
22711
22712    /*
22713     * Collect information of applications on external media, map them against
22714     * existing containers and update information based on current mount status.
22715     * Please note that we always have to report status if reportStatus has been
22716     * set to true especially when unloading packages.
22717     */
22718    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22719            boolean externalStorage) {
22720        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22721        int[] uidArr = EmptyArray.INT;
22722
22723        final String[] list = PackageHelper.getSecureContainerList();
22724        if (ArrayUtils.isEmpty(list)) {
22725            Log.i(TAG, "No secure containers found");
22726        } else {
22727            // Process list of secure containers and categorize them
22728            // as active or stale based on their package internal state.
22729
22730            // reader
22731            synchronized (mPackages) {
22732                for (String cid : list) {
22733                    // Leave stages untouched for now; installer service owns them
22734                    if (PackageInstallerService.isStageName(cid)) continue;
22735
22736                    if (DEBUG_SD_INSTALL)
22737                        Log.i(TAG, "Processing container " + cid);
22738                    String pkgName = getAsecPackageName(cid);
22739                    if (pkgName == null) {
22740                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22741                        continue;
22742                    }
22743                    if (DEBUG_SD_INSTALL)
22744                        Log.i(TAG, "Looking for pkg : " + pkgName);
22745
22746                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22747                    if (ps == null) {
22748                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22749                        continue;
22750                    }
22751
22752                    /*
22753                     * Skip packages that are not external if we're unmounting
22754                     * external storage.
22755                     */
22756                    if (externalStorage && !isMounted && !isExternal(ps)) {
22757                        continue;
22758                    }
22759
22760                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22761                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22762                    // The package status is changed only if the code path
22763                    // matches between settings and the container id.
22764                    if (ps.codePathString != null
22765                            && ps.codePathString.startsWith(args.getCodePath())) {
22766                        if (DEBUG_SD_INSTALL) {
22767                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22768                                    + " at code path: " + ps.codePathString);
22769                        }
22770
22771                        // We do have a valid package installed on sdcard
22772                        processCids.put(args, ps.codePathString);
22773                        final int uid = ps.appId;
22774                        if (uid != -1) {
22775                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22776                        }
22777                    } else {
22778                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22779                                + ps.codePathString);
22780                    }
22781                }
22782            }
22783
22784            Arrays.sort(uidArr);
22785        }
22786
22787        // Process packages with valid entries.
22788        if (isMounted) {
22789            if (DEBUG_SD_INSTALL)
22790                Log.i(TAG, "Loading packages");
22791            loadMediaPackages(processCids, uidArr, externalStorage);
22792            startCleaningPackages();
22793            mInstallerService.onSecureContainersAvailable();
22794        } else {
22795            if (DEBUG_SD_INSTALL)
22796                Log.i(TAG, "Unloading packages");
22797            unloadMediaPackages(processCids, uidArr, reportStatus);
22798        }
22799    }
22800
22801    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22802            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22803        final int size = infos.size();
22804        final String[] packageNames = new String[size];
22805        final int[] packageUids = new int[size];
22806        for (int i = 0; i < size; i++) {
22807            final ApplicationInfo info = infos.get(i);
22808            packageNames[i] = info.packageName;
22809            packageUids[i] = info.uid;
22810        }
22811        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22812                finishedReceiver);
22813    }
22814
22815    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22816            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22817        sendResourcesChangedBroadcast(mediaStatus, replacing,
22818                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22819    }
22820
22821    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22822            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22823        int size = pkgList.length;
22824        if (size > 0) {
22825            // Send broadcasts here
22826            Bundle extras = new Bundle();
22827            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22828            if (uidArr != null) {
22829                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22830            }
22831            if (replacing) {
22832                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22833            }
22834            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22835                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22836            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22837        }
22838    }
22839
22840   /*
22841     * Look at potentially valid container ids from processCids If package
22842     * information doesn't match the one on record or package scanning fails,
22843     * the cid is added to list of removeCids. We currently don't delete stale
22844     * containers.
22845     */
22846    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22847            boolean externalStorage) {
22848        ArrayList<String> pkgList = new ArrayList<String>();
22849        Set<AsecInstallArgs> keys = processCids.keySet();
22850
22851        for (AsecInstallArgs args : keys) {
22852            String codePath = processCids.get(args);
22853            if (DEBUG_SD_INSTALL)
22854                Log.i(TAG, "Loading container : " + args.cid);
22855            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22856            try {
22857                // Make sure there are no container errors first.
22858                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22859                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22860                            + " when installing from sdcard");
22861                    continue;
22862                }
22863                // Check code path here.
22864                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22865                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22866                            + " does not match one in settings " + codePath);
22867                    continue;
22868                }
22869                // Parse package
22870                int parseFlags = mDefParseFlags;
22871                if (args.isExternalAsec()) {
22872                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22873                }
22874                if (args.isFwdLocked()) {
22875                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22876                }
22877
22878                synchronized (mInstallLock) {
22879                    PackageParser.Package pkg = null;
22880                    try {
22881                        // Sadly we don't know the package name yet to freeze it
22882                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22883                                SCAN_IGNORE_FROZEN, 0, null);
22884                    } catch (PackageManagerException e) {
22885                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22886                    }
22887                    // Scan the package
22888                    if (pkg != null) {
22889                        /*
22890                         * TODO why is the lock being held? doPostInstall is
22891                         * called in other places without the lock. This needs
22892                         * to be straightened out.
22893                         */
22894                        // writer
22895                        synchronized (mPackages) {
22896                            retCode = PackageManager.INSTALL_SUCCEEDED;
22897                            pkgList.add(pkg.packageName);
22898                            // Post process args
22899                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22900                                    pkg.applicationInfo.uid);
22901                        }
22902                    } else {
22903                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22904                    }
22905                }
22906
22907            } finally {
22908                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22909                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22910                }
22911            }
22912        }
22913        // writer
22914        synchronized (mPackages) {
22915            // If the platform SDK has changed since the last time we booted,
22916            // we need to re-grant app permission to catch any new ones that
22917            // appear. This is really a hack, and means that apps can in some
22918            // cases get permissions that the user didn't initially explicitly
22919            // allow... it would be nice to have some better way to handle
22920            // this situation.
22921            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22922                    : mSettings.getInternalVersion();
22923            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22924                    : StorageManager.UUID_PRIVATE_INTERNAL;
22925
22926            int updateFlags = UPDATE_PERMISSIONS_ALL;
22927            if (ver.sdkVersion != mSdkVersion) {
22928                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22929                        + mSdkVersion + "; regranting permissions for external");
22930                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22931            }
22932            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22933
22934            // Yay, everything is now upgraded
22935            ver.forceCurrent();
22936
22937            // can downgrade to reader
22938            // Persist settings
22939            mSettings.writeLPr();
22940        }
22941        // Send a broadcast to let everyone know we are done processing
22942        if (pkgList.size() > 0) {
22943            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22944        }
22945    }
22946
22947   /*
22948     * Utility method to unload a list of specified containers
22949     */
22950    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22951        // Just unmount all valid containers.
22952        for (AsecInstallArgs arg : cidArgs) {
22953            synchronized (mInstallLock) {
22954                arg.doPostDeleteLI(false);
22955           }
22956       }
22957   }
22958
22959    /*
22960     * Unload packages mounted on external media. This involves deleting package
22961     * data from internal structures, sending broadcasts about disabled packages,
22962     * gc'ing to free up references, unmounting all secure containers
22963     * corresponding to packages on external media, and posting a
22964     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22965     * that we always have to post this message if status has been requested no
22966     * matter what.
22967     */
22968    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22969            final boolean reportStatus) {
22970        if (DEBUG_SD_INSTALL)
22971            Log.i(TAG, "unloading media packages");
22972        ArrayList<String> pkgList = new ArrayList<String>();
22973        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22974        final Set<AsecInstallArgs> keys = processCids.keySet();
22975        for (AsecInstallArgs args : keys) {
22976            String pkgName = args.getPackageName();
22977            if (DEBUG_SD_INSTALL)
22978                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22979            // Delete package internally
22980            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22981            synchronized (mInstallLock) {
22982                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22983                final boolean res;
22984                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22985                        "unloadMediaPackages")) {
22986                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22987                            null);
22988                }
22989                if (res) {
22990                    pkgList.add(pkgName);
22991                } else {
22992                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22993                    failedList.add(args);
22994                }
22995            }
22996        }
22997
22998        // reader
22999        synchronized (mPackages) {
23000            // We didn't update the settings after removing each package;
23001            // write them now for all packages.
23002            mSettings.writeLPr();
23003        }
23004
23005        // We have to absolutely send UPDATED_MEDIA_STATUS only
23006        // after confirming that all the receivers processed the ordered
23007        // broadcast when packages get disabled, force a gc to clean things up.
23008        // and unload all the containers.
23009        if (pkgList.size() > 0) {
23010            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23011                    new IIntentReceiver.Stub() {
23012                public void performReceive(Intent intent, int resultCode, String data,
23013                        Bundle extras, boolean ordered, boolean sticky,
23014                        int sendingUser) throws RemoteException {
23015                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23016                            reportStatus ? 1 : 0, 1, keys);
23017                    mHandler.sendMessage(msg);
23018                }
23019            });
23020        } else {
23021            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23022                    keys);
23023            mHandler.sendMessage(msg);
23024        }
23025    }
23026
23027    private void loadPrivatePackages(final VolumeInfo vol) {
23028        mHandler.post(new Runnable() {
23029            @Override
23030            public void run() {
23031                loadPrivatePackagesInner(vol);
23032            }
23033        });
23034    }
23035
23036    private void loadPrivatePackagesInner(VolumeInfo vol) {
23037        final String volumeUuid = vol.fsUuid;
23038        if (TextUtils.isEmpty(volumeUuid)) {
23039            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23040            return;
23041        }
23042
23043        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23044        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23045        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23046
23047        final VersionInfo ver;
23048        final List<PackageSetting> packages;
23049        synchronized (mPackages) {
23050            ver = mSettings.findOrCreateVersion(volumeUuid);
23051            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23052        }
23053
23054        for (PackageSetting ps : packages) {
23055            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23056            synchronized (mInstallLock) {
23057                final PackageParser.Package pkg;
23058                try {
23059                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23060                    loaded.add(pkg.applicationInfo);
23061
23062                } catch (PackageManagerException e) {
23063                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23064                }
23065
23066                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23067                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23068                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23069                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23070                }
23071            }
23072        }
23073
23074        // Reconcile app data for all started/unlocked users
23075        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23076        final UserManager um = mContext.getSystemService(UserManager.class);
23077        UserManagerInternal umInternal = getUserManagerInternal();
23078        for (UserInfo user : um.getUsers()) {
23079            final int flags;
23080            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23081                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23082            } else if (umInternal.isUserRunning(user.id)) {
23083                flags = StorageManager.FLAG_STORAGE_DE;
23084            } else {
23085                continue;
23086            }
23087
23088            try {
23089                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23090                synchronized (mInstallLock) {
23091                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23092                }
23093            } catch (IllegalStateException e) {
23094                // Device was probably ejected, and we'll process that event momentarily
23095                Slog.w(TAG, "Failed to prepare storage: " + e);
23096            }
23097        }
23098
23099        synchronized (mPackages) {
23100            int updateFlags = UPDATE_PERMISSIONS_ALL;
23101            if (ver.sdkVersion != mSdkVersion) {
23102                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23103                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23104                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23105            }
23106            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23107
23108            // Yay, everything is now upgraded
23109            ver.forceCurrent();
23110
23111            mSettings.writeLPr();
23112        }
23113
23114        for (PackageFreezer freezer : freezers) {
23115            freezer.close();
23116        }
23117
23118        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23119        sendResourcesChangedBroadcast(true, false, loaded, null);
23120    }
23121
23122    private void unloadPrivatePackages(final VolumeInfo vol) {
23123        mHandler.post(new Runnable() {
23124            @Override
23125            public void run() {
23126                unloadPrivatePackagesInner(vol);
23127            }
23128        });
23129    }
23130
23131    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23132        final String volumeUuid = vol.fsUuid;
23133        if (TextUtils.isEmpty(volumeUuid)) {
23134            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23135            return;
23136        }
23137
23138        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23139        synchronized (mInstallLock) {
23140        synchronized (mPackages) {
23141            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23142            for (PackageSetting ps : packages) {
23143                if (ps.pkg == null) continue;
23144
23145                final ApplicationInfo info = ps.pkg.applicationInfo;
23146                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23147                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23148
23149                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23150                        "unloadPrivatePackagesInner")) {
23151                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23152                            false, null)) {
23153                        unloaded.add(info);
23154                    } else {
23155                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23156                    }
23157                }
23158
23159                // Try very hard to release any references to this package
23160                // so we don't risk the system server being killed due to
23161                // open FDs
23162                AttributeCache.instance().removePackage(ps.name);
23163            }
23164
23165            mSettings.writeLPr();
23166        }
23167        }
23168
23169        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23170        sendResourcesChangedBroadcast(false, false, unloaded, null);
23171
23172        // Try very hard to release any references to this path so we don't risk
23173        // the system server being killed due to open FDs
23174        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23175
23176        for (int i = 0; i < 3; i++) {
23177            System.gc();
23178            System.runFinalization();
23179        }
23180    }
23181
23182    private void assertPackageKnown(String volumeUuid, String packageName)
23183            throws PackageManagerException {
23184        synchronized (mPackages) {
23185            // Normalize package name to handle renamed packages
23186            packageName = normalizePackageNameLPr(packageName);
23187
23188            final PackageSetting ps = mSettings.mPackages.get(packageName);
23189            if (ps == null) {
23190                throw new PackageManagerException("Package " + packageName + " is unknown");
23191            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23192                throw new PackageManagerException(
23193                        "Package " + packageName + " found on unknown volume " + volumeUuid
23194                                + "; expected volume " + ps.volumeUuid);
23195            }
23196        }
23197    }
23198
23199    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23200            throws PackageManagerException {
23201        synchronized (mPackages) {
23202            // Normalize package name to handle renamed packages
23203            packageName = normalizePackageNameLPr(packageName);
23204
23205            final PackageSetting ps = mSettings.mPackages.get(packageName);
23206            if (ps == null) {
23207                throw new PackageManagerException("Package " + packageName + " is unknown");
23208            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23209                throw new PackageManagerException(
23210                        "Package " + packageName + " found on unknown volume " + volumeUuid
23211                                + "; expected volume " + ps.volumeUuid);
23212            } else if (!ps.getInstalled(userId)) {
23213                throw new PackageManagerException(
23214                        "Package " + packageName + " not installed for user " + userId);
23215            }
23216        }
23217    }
23218
23219    private List<String> collectAbsoluteCodePaths() {
23220        synchronized (mPackages) {
23221            List<String> codePaths = new ArrayList<>();
23222            final int packageCount = mSettings.mPackages.size();
23223            for (int i = 0; i < packageCount; i++) {
23224                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23225                codePaths.add(ps.codePath.getAbsolutePath());
23226            }
23227            return codePaths;
23228        }
23229    }
23230
23231    /**
23232     * Examine all apps present on given mounted volume, and destroy apps that
23233     * aren't expected, either due to uninstallation or reinstallation on
23234     * another volume.
23235     */
23236    private void reconcileApps(String volumeUuid) {
23237        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23238        List<File> filesToDelete = null;
23239
23240        final File[] files = FileUtils.listFilesOrEmpty(
23241                Environment.getDataAppDirectory(volumeUuid));
23242        for (File file : files) {
23243            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23244                    && !PackageInstallerService.isStageName(file.getName());
23245            if (!isPackage) {
23246                // Ignore entries which are not packages
23247                continue;
23248            }
23249
23250            String absolutePath = file.getAbsolutePath();
23251
23252            boolean pathValid = false;
23253            final int absoluteCodePathCount = absoluteCodePaths.size();
23254            for (int i = 0; i < absoluteCodePathCount; i++) {
23255                String absoluteCodePath = absoluteCodePaths.get(i);
23256                if (absolutePath.startsWith(absoluteCodePath)) {
23257                    pathValid = true;
23258                    break;
23259                }
23260            }
23261
23262            if (!pathValid) {
23263                if (filesToDelete == null) {
23264                    filesToDelete = new ArrayList<>();
23265                }
23266                filesToDelete.add(file);
23267            }
23268        }
23269
23270        if (filesToDelete != null) {
23271            final int fileToDeleteCount = filesToDelete.size();
23272            for (int i = 0; i < fileToDeleteCount; i++) {
23273                File fileToDelete = filesToDelete.get(i);
23274                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23275                synchronized (mInstallLock) {
23276                    removeCodePathLI(fileToDelete);
23277                }
23278            }
23279        }
23280    }
23281
23282    /**
23283     * Reconcile all app data for the given user.
23284     * <p>
23285     * Verifies that directories exist and that ownership and labeling is
23286     * correct for all installed apps on all mounted volumes.
23287     */
23288    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23289        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23290        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23291            final String volumeUuid = vol.getFsUuid();
23292            synchronized (mInstallLock) {
23293                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23294            }
23295        }
23296    }
23297
23298    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23299            boolean migrateAppData) {
23300        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23301    }
23302
23303    /**
23304     * Reconcile all app data on given mounted volume.
23305     * <p>
23306     * Destroys app data that isn't expected, either due to uninstallation or
23307     * reinstallation on another volume.
23308     * <p>
23309     * Verifies that directories exist and that ownership and labeling is
23310     * correct for all installed apps.
23311     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23312     */
23313    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23314            boolean migrateAppData, boolean onlyCoreApps) {
23315        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23316                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23317        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23318
23319        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23320        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23321
23322        // First look for stale data that doesn't belong, and check if things
23323        // have changed since we did our last restorecon
23324        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23325            if (StorageManager.isFileEncryptedNativeOrEmulated()
23326                    && !StorageManager.isUserKeyUnlocked(userId)) {
23327                throw new RuntimeException(
23328                        "Yikes, someone asked us to reconcile CE storage while " + userId
23329                                + " was still locked; this would have caused massive data loss!");
23330            }
23331
23332            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23333            for (File file : files) {
23334                final String packageName = file.getName();
23335                try {
23336                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23337                } catch (PackageManagerException e) {
23338                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23339                    try {
23340                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23341                                StorageManager.FLAG_STORAGE_CE, 0);
23342                    } catch (InstallerException e2) {
23343                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23344                    }
23345                }
23346            }
23347        }
23348        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23349            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23350            for (File file : files) {
23351                final String packageName = file.getName();
23352                try {
23353                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23354                } catch (PackageManagerException e) {
23355                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23356                    try {
23357                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23358                                StorageManager.FLAG_STORAGE_DE, 0);
23359                    } catch (InstallerException e2) {
23360                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23361                    }
23362                }
23363            }
23364        }
23365
23366        // Ensure that data directories are ready to roll for all packages
23367        // installed for this volume and user
23368        final List<PackageSetting> packages;
23369        synchronized (mPackages) {
23370            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23371        }
23372        int preparedCount = 0;
23373        for (PackageSetting ps : packages) {
23374            final String packageName = ps.name;
23375            if (ps.pkg == null) {
23376                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23377                // TODO: might be due to legacy ASEC apps; we should circle back
23378                // and reconcile again once they're scanned
23379                continue;
23380            }
23381            // Skip non-core apps if requested
23382            if (onlyCoreApps && !ps.pkg.coreApp) {
23383                result.add(packageName);
23384                continue;
23385            }
23386
23387            if (ps.getInstalled(userId)) {
23388                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23389                preparedCount++;
23390            }
23391        }
23392
23393        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23394        return result;
23395    }
23396
23397    /**
23398     * Prepare app data for the given app just after it was installed or
23399     * upgraded. This method carefully only touches users that it's installed
23400     * for, and it forces a restorecon to handle any seinfo changes.
23401     * <p>
23402     * Verifies that directories exist and that ownership and labeling is
23403     * correct for all installed apps. If there is an ownership mismatch, it
23404     * will try recovering system apps by wiping data; third-party app data is
23405     * left intact.
23406     * <p>
23407     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23408     */
23409    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23410        final PackageSetting ps;
23411        synchronized (mPackages) {
23412            ps = mSettings.mPackages.get(pkg.packageName);
23413            mSettings.writeKernelMappingLPr(ps);
23414        }
23415
23416        final UserManager um = mContext.getSystemService(UserManager.class);
23417        UserManagerInternal umInternal = getUserManagerInternal();
23418        for (UserInfo user : um.getUsers()) {
23419            final int flags;
23420            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23421                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23422            } else if (umInternal.isUserRunning(user.id)) {
23423                flags = StorageManager.FLAG_STORAGE_DE;
23424            } else {
23425                continue;
23426            }
23427
23428            if (ps.getInstalled(user.id)) {
23429                // TODO: when user data is locked, mark that we're still dirty
23430                prepareAppDataLIF(pkg, user.id, flags);
23431            }
23432        }
23433    }
23434
23435    /**
23436     * Prepare app data for the given app.
23437     * <p>
23438     * Verifies that directories exist and that ownership and labeling is
23439     * correct for all installed apps. If there is an ownership mismatch, this
23440     * will try recovering system apps by wiping data; third-party app data is
23441     * left intact.
23442     */
23443    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23444        if (pkg == null) {
23445            Slog.wtf(TAG, "Package was null!", new Throwable());
23446            return;
23447        }
23448        prepareAppDataLeafLIF(pkg, userId, flags);
23449        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23450        for (int i = 0; i < childCount; i++) {
23451            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23452        }
23453    }
23454
23455    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23456            boolean maybeMigrateAppData) {
23457        prepareAppDataLIF(pkg, userId, flags);
23458
23459        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23460            // We may have just shuffled around app data directories, so
23461            // prepare them one more time
23462            prepareAppDataLIF(pkg, userId, flags);
23463        }
23464    }
23465
23466    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23467        if (DEBUG_APP_DATA) {
23468            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23469                    + Integer.toHexString(flags));
23470        }
23471
23472        final String volumeUuid = pkg.volumeUuid;
23473        final String packageName = pkg.packageName;
23474        final ApplicationInfo app = pkg.applicationInfo;
23475        final int appId = UserHandle.getAppId(app.uid);
23476
23477        Preconditions.checkNotNull(app.seInfo);
23478
23479        long ceDataInode = -1;
23480        try {
23481            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23482                    appId, app.seInfo, app.targetSdkVersion);
23483        } catch (InstallerException e) {
23484            if (app.isSystemApp()) {
23485                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23486                        + ", but trying to recover: " + e);
23487                destroyAppDataLeafLIF(pkg, userId, flags);
23488                try {
23489                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23490                            appId, app.seInfo, app.targetSdkVersion);
23491                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23492                } catch (InstallerException e2) {
23493                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23494                }
23495            } else {
23496                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23497            }
23498        }
23499
23500        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23501            // TODO: mark this structure as dirty so we persist it!
23502            synchronized (mPackages) {
23503                final PackageSetting ps = mSettings.mPackages.get(packageName);
23504                if (ps != null) {
23505                    ps.setCeDataInode(ceDataInode, userId);
23506                }
23507            }
23508        }
23509
23510        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23511    }
23512
23513    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23514        if (pkg == null) {
23515            Slog.wtf(TAG, "Package was null!", new Throwable());
23516            return;
23517        }
23518        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23519        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23520        for (int i = 0; i < childCount; i++) {
23521            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23522        }
23523    }
23524
23525    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23526        final String volumeUuid = pkg.volumeUuid;
23527        final String packageName = pkg.packageName;
23528        final ApplicationInfo app = pkg.applicationInfo;
23529
23530        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23531            // Create a native library symlink only if we have native libraries
23532            // and if the native libraries are 32 bit libraries. We do not provide
23533            // this symlink for 64 bit libraries.
23534            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23535                final String nativeLibPath = app.nativeLibraryDir;
23536                try {
23537                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23538                            nativeLibPath, userId);
23539                } catch (InstallerException e) {
23540                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23541                }
23542            }
23543        }
23544    }
23545
23546    /**
23547     * For system apps on non-FBE devices, this method migrates any existing
23548     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23549     * requested by the app.
23550     */
23551    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23552        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23553                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23554            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23555                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23556            try {
23557                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23558                        storageTarget);
23559            } catch (InstallerException e) {
23560                logCriticalInfo(Log.WARN,
23561                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23562            }
23563            return true;
23564        } else {
23565            return false;
23566        }
23567    }
23568
23569    public PackageFreezer freezePackage(String packageName, String killReason) {
23570        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23571    }
23572
23573    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23574        return new PackageFreezer(packageName, userId, killReason);
23575    }
23576
23577    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23578            String killReason) {
23579        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23580    }
23581
23582    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23583            String killReason) {
23584        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23585            return new PackageFreezer();
23586        } else {
23587            return freezePackage(packageName, userId, killReason);
23588        }
23589    }
23590
23591    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23592            String killReason) {
23593        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23594    }
23595
23596    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23597            String killReason) {
23598        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23599            return new PackageFreezer();
23600        } else {
23601            return freezePackage(packageName, userId, killReason);
23602        }
23603    }
23604
23605    /**
23606     * Class that freezes and kills the given package upon creation, and
23607     * unfreezes it upon closing. This is typically used when doing surgery on
23608     * app code/data to prevent the app from running while you're working.
23609     */
23610    private class PackageFreezer implements AutoCloseable {
23611        private final String mPackageName;
23612        private final PackageFreezer[] mChildren;
23613
23614        private final boolean mWeFroze;
23615
23616        private final AtomicBoolean mClosed = new AtomicBoolean();
23617        private final CloseGuard mCloseGuard = CloseGuard.get();
23618
23619        /**
23620         * Create and return a stub freezer that doesn't actually do anything,
23621         * typically used when someone requested
23622         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23623         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23624         */
23625        public PackageFreezer() {
23626            mPackageName = null;
23627            mChildren = null;
23628            mWeFroze = false;
23629            mCloseGuard.open("close");
23630        }
23631
23632        public PackageFreezer(String packageName, int userId, String killReason) {
23633            synchronized (mPackages) {
23634                mPackageName = packageName;
23635                mWeFroze = mFrozenPackages.add(mPackageName);
23636
23637                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23638                if (ps != null) {
23639                    killApplication(ps.name, ps.appId, userId, killReason);
23640                }
23641
23642                final PackageParser.Package p = mPackages.get(packageName);
23643                if (p != null && p.childPackages != null) {
23644                    final int N = p.childPackages.size();
23645                    mChildren = new PackageFreezer[N];
23646                    for (int i = 0; i < N; i++) {
23647                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23648                                userId, killReason);
23649                    }
23650                } else {
23651                    mChildren = null;
23652                }
23653            }
23654            mCloseGuard.open("close");
23655        }
23656
23657        @Override
23658        protected void finalize() throws Throwable {
23659            try {
23660                if (mCloseGuard != null) {
23661                    mCloseGuard.warnIfOpen();
23662                }
23663
23664                close();
23665            } finally {
23666                super.finalize();
23667            }
23668        }
23669
23670        @Override
23671        public void close() {
23672            mCloseGuard.close();
23673            if (mClosed.compareAndSet(false, true)) {
23674                synchronized (mPackages) {
23675                    if (mWeFroze) {
23676                        mFrozenPackages.remove(mPackageName);
23677                    }
23678
23679                    if (mChildren != null) {
23680                        for (PackageFreezer freezer : mChildren) {
23681                            freezer.close();
23682                        }
23683                    }
23684                }
23685            }
23686        }
23687    }
23688
23689    /**
23690     * Verify that given package is currently frozen.
23691     */
23692    private void checkPackageFrozen(String packageName) {
23693        synchronized (mPackages) {
23694            if (!mFrozenPackages.contains(packageName)) {
23695                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23696            }
23697        }
23698    }
23699
23700    @Override
23701    public int movePackage(final String packageName, final String volumeUuid) {
23702        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23703
23704        final int callingUid = Binder.getCallingUid();
23705        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23706        final int moveId = mNextMoveId.getAndIncrement();
23707        mHandler.post(new Runnable() {
23708            @Override
23709            public void run() {
23710                try {
23711                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23712                } catch (PackageManagerException e) {
23713                    Slog.w(TAG, "Failed to move " + packageName, e);
23714                    mMoveCallbacks.notifyStatusChanged(moveId,
23715                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23716                }
23717            }
23718        });
23719        return moveId;
23720    }
23721
23722    private void movePackageInternal(final String packageName, final String volumeUuid,
23723            final int moveId, final int callingUid, UserHandle user)
23724                    throws PackageManagerException {
23725        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23726        final PackageManager pm = mContext.getPackageManager();
23727
23728        final boolean currentAsec;
23729        final String currentVolumeUuid;
23730        final File codeFile;
23731        final String installerPackageName;
23732        final String packageAbiOverride;
23733        final int appId;
23734        final String seinfo;
23735        final String label;
23736        final int targetSdkVersion;
23737        final PackageFreezer freezer;
23738        final int[] installedUserIds;
23739
23740        // reader
23741        synchronized (mPackages) {
23742            final PackageParser.Package pkg = mPackages.get(packageName);
23743            final PackageSetting ps = mSettings.mPackages.get(packageName);
23744            if (pkg == null
23745                    || ps == null
23746                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23747                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23748            }
23749            if (pkg.applicationInfo.isSystemApp()) {
23750                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23751                        "Cannot move system application");
23752            }
23753
23754            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23755            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23756                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23757            if (isInternalStorage && !allow3rdPartyOnInternal) {
23758                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23759                        "3rd party apps are not allowed on internal storage");
23760            }
23761
23762            if (pkg.applicationInfo.isExternalAsec()) {
23763                currentAsec = true;
23764                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23765            } else if (pkg.applicationInfo.isForwardLocked()) {
23766                currentAsec = true;
23767                currentVolumeUuid = "forward_locked";
23768            } else {
23769                currentAsec = false;
23770                currentVolumeUuid = ps.volumeUuid;
23771
23772                final File probe = new File(pkg.codePath);
23773                final File probeOat = new File(probe, "oat");
23774                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23775                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23776                            "Move only supported for modern cluster style installs");
23777                }
23778            }
23779
23780            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23781                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23782                        "Package already moved to " + volumeUuid);
23783            }
23784            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23785                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23786                        "Device admin cannot be moved");
23787            }
23788
23789            if (mFrozenPackages.contains(packageName)) {
23790                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23791                        "Failed to move already frozen package");
23792            }
23793
23794            codeFile = new File(pkg.codePath);
23795            installerPackageName = ps.installerPackageName;
23796            packageAbiOverride = ps.cpuAbiOverrideString;
23797            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23798            seinfo = pkg.applicationInfo.seInfo;
23799            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23800            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23801            freezer = freezePackage(packageName, "movePackageInternal");
23802            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23803        }
23804
23805        final Bundle extras = new Bundle();
23806        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23807        extras.putString(Intent.EXTRA_TITLE, label);
23808        mMoveCallbacks.notifyCreated(moveId, extras);
23809
23810        int installFlags;
23811        final boolean moveCompleteApp;
23812        final File measurePath;
23813
23814        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23815            installFlags = INSTALL_INTERNAL;
23816            moveCompleteApp = !currentAsec;
23817            measurePath = Environment.getDataAppDirectory(volumeUuid);
23818        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23819            installFlags = INSTALL_EXTERNAL;
23820            moveCompleteApp = false;
23821            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23822        } else {
23823            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23824            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23825                    || !volume.isMountedWritable()) {
23826                freezer.close();
23827                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23828                        "Move location not mounted private volume");
23829            }
23830
23831            Preconditions.checkState(!currentAsec);
23832
23833            installFlags = INSTALL_INTERNAL;
23834            moveCompleteApp = true;
23835            measurePath = Environment.getDataAppDirectory(volumeUuid);
23836        }
23837
23838        final PackageStats stats = new PackageStats(null, -1);
23839        synchronized (mInstaller) {
23840            for (int userId : installedUserIds) {
23841                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23842                    freezer.close();
23843                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23844                            "Failed to measure package size");
23845                }
23846            }
23847        }
23848
23849        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23850                + stats.dataSize);
23851
23852        final long startFreeBytes = measurePath.getUsableSpace();
23853        final long sizeBytes;
23854        if (moveCompleteApp) {
23855            sizeBytes = stats.codeSize + stats.dataSize;
23856        } else {
23857            sizeBytes = stats.codeSize;
23858        }
23859
23860        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23861            freezer.close();
23862            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23863                    "Not enough free space to move");
23864        }
23865
23866        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23867
23868        final CountDownLatch installedLatch = new CountDownLatch(1);
23869        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23870            @Override
23871            public void onUserActionRequired(Intent intent) throws RemoteException {
23872                throw new IllegalStateException();
23873            }
23874
23875            @Override
23876            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23877                    Bundle extras) throws RemoteException {
23878                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23879                        + PackageManager.installStatusToString(returnCode, msg));
23880
23881                installedLatch.countDown();
23882                freezer.close();
23883
23884                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23885                switch (status) {
23886                    case PackageInstaller.STATUS_SUCCESS:
23887                        mMoveCallbacks.notifyStatusChanged(moveId,
23888                                PackageManager.MOVE_SUCCEEDED);
23889                        break;
23890                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23891                        mMoveCallbacks.notifyStatusChanged(moveId,
23892                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23893                        break;
23894                    default:
23895                        mMoveCallbacks.notifyStatusChanged(moveId,
23896                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23897                        break;
23898                }
23899            }
23900        };
23901
23902        final MoveInfo move;
23903        if (moveCompleteApp) {
23904            // Kick off a thread to report progress estimates
23905            new Thread() {
23906                @Override
23907                public void run() {
23908                    while (true) {
23909                        try {
23910                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23911                                break;
23912                            }
23913                        } catch (InterruptedException ignored) {
23914                        }
23915
23916                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23917                        final int progress = 10 + (int) MathUtils.constrain(
23918                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23919                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23920                    }
23921                }
23922            }.start();
23923
23924            final String dataAppName = codeFile.getName();
23925            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23926                    dataAppName, appId, seinfo, targetSdkVersion);
23927        } else {
23928            move = null;
23929        }
23930
23931        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23932
23933        final Message msg = mHandler.obtainMessage(INIT_COPY);
23934        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23935        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23936                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23937                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23938                PackageManager.INSTALL_REASON_UNKNOWN);
23939        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23940        msg.obj = params;
23941
23942        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23943                System.identityHashCode(msg.obj));
23944        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23945                System.identityHashCode(msg.obj));
23946
23947        mHandler.sendMessage(msg);
23948    }
23949
23950    @Override
23951    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23952        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23953
23954        final int realMoveId = mNextMoveId.getAndIncrement();
23955        final Bundle extras = new Bundle();
23956        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23957        mMoveCallbacks.notifyCreated(realMoveId, extras);
23958
23959        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23960            @Override
23961            public void onCreated(int moveId, Bundle extras) {
23962                // Ignored
23963            }
23964
23965            @Override
23966            public void onStatusChanged(int moveId, int status, long estMillis) {
23967                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23968            }
23969        };
23970
23971        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23972        storage.setPrimaryStorageUuid(volumeUuid, callback);
23973        return realMoveId;
23974    }
23975
23976    @Override
23977    public int getMoveStatus(int moveId) {
23978        mContext.enforceCallingOrSelfPermission(
23979                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23980        return mMoveCallbacks.mLastStatus.get(moveId);
23981    }
23982
23983    @Override
23984    public void registerMoveCallback(IPackageMoveObserver callback) {
23985        mContext.enforceCallingOrSelfPermission(
23986                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23987        mMoveCallbacks.register(callback);
23988    }
23989
23990    @Override
23991    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23992        mContext.enforceCallingOrSelfPermission(
23993                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23994        mMoveCallbacks.unregister(callback);
23995    }
23996
23997    @Override
23998    public boolean setInstallLocation(int loc) {
23999        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24000                null);
24001        if (getInstallLocation() == loc) {
24002            return true;
24003        }
24004        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24005                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24006            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24007                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24008            return true;
24009        }
24010        return false;
24011   }
24012
24013    @Override
24014    public int getInstallLocation() {
24015        // allow instant app access
24016        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24017                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24018                PackageHelper.APP_INSTALL_AUTO);
24019    }
24020
24021    /** Called by UserManagerService */
24022    void cleanUpUser(UserManagerService userManager, int userHandle) {
24023        synchronized (mPackages) {
24024            mDirtyUsers.remove(userHandle);
24025            mUserNeedsBadging.delete(userHandle);
24026            mSettings.removeUserLPw(userHandle);
24027            mPendingBroadcasts.remove(userHandle);
24028            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24029            removeUnusedPackagesLPw(userManager, userHandle);
24030        }
24031    }
24032
24033    /**
24034     * We're removing userHandle and would like to remove any downloaded packages
24035     * that are no longer in use by any other user.
24036     * @param userHandle the user being removed
24037     */
24038    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24039        final boolean DEBUG_CLEAN_APKS = false;
24040        int [] users = userManager.getUserIds();
24041        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24042        while (psit.hasNext()) {
24043            PackageSetting ps = psit.next();
24044            if (ps.pkg == null) {
24045                continue;
24046            }
24047            final String packageName = ps.pkg.packageName;
24048            // Skip over if system app
24049            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24050                continue;
24051            }
24052            if (DEBUG_CLEAN_APKS) {
24053                Slog.i(TAG, "Checking package " + packageName);
24054            }
24055            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24056            if (keep) {
24057                if (DEBUG_CLEAN_APKS) {
24058                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24059                }
24060            } else {
24061                for (int i = 0; i < users.length; i++) {
24062                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24063                        keep = true;
24064                        if (DEBUG_CLEAN_APKS) {
24065                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24066                                    + users[i]);
24067                        }
24068                        break;
24069                    }
24070                }
24071            }
24072            if (!keep) {
24073                if (DEBUG_CLEAN_APKS) {
24074                    Slog.i(TAG, "  Removing package " + packageName);
24075                }
24076                mHandler.post(new Runnable() {
24077                    public void run() {
24078                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24079                                userHandle, 0);
24080                    } //end run
24081                });
24082            }
24083        }
24084    }
24085
24086    /** Called by UserManagerService */
24087    void createNewUser(int userId, String[] disallowedPackages) {
24088        synchronized (mInstallLock) {
24089            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24090        }
24091        synchronized (mPackages) {
24092            scheduleWritePackageRestrictionsLocked(userId);
24093            scheduleWritePackageListLocked(userId);
24094            applyFactoryDefaultBrowserLPw(userId);
24095            primeDomainVerificationsLPw(userId);
24096        }
24097    }
24098
24099    void onNewUserCreated(final int userId) {
24100        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24101        // If permission review for legacy apps is required, we represent
24102        // dagerous permissions for such apps as always granted runtime
24103        // permissions to keep per user flag state whether review is needed.
24104        // Hence, if a new user is added we have to propagate dangerous
24105        // permission grants for these legacy apps.
24106        if (mPermissionReviewRequired) {
24107            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24108                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24109        }
24110    }
24111
24112    @Override
24113    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24114        mContext.enforceCallingOrSelfPermission(
24115                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24116                "Only package verification agents can read the verifier device identity");
24117
24118        synchronized (mPackages) {
24119            return mSettings.getVerifierDeviceIdentityLPw();
24120        }
24121    }
24122
24123    @Override
24124    public void setPermissionEnforced(String permission, boolean enforced) {
24125        // TODO: Now that we no longer change GID for storage, this should to away.
24126        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24127                "setPermissionEnforced");
24128        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24129            synchronized (mPackages) {
24130                if (mSettings.mReadExternalStorageEnforced == null
24131                        || mSettings.mReadExternalStorageEnforced != enforced) {
24132                    mSettings.mReadExternalStorageEnforced = enforced;
24133                    mSettings.writeLPr();
24134                }
24135            }
24136            // kill any non-foreground processes so we restart them and
24137            // grant/revoke the GID.
24138            final IActivityManager am = ActivityManager.getService();
24139            if (am != null) {
24140                final long token = Binder.clearCallingIdentity();
24141                try {
24142                    am.killProcessesBelowForeground("setPermissionEnforcement");
24143                } catch (RemoteException e) {
24144                } finally {
24145                    Binder.restoreCallingIdentity(token);
24146                }
24147            }
24148        } else {
24149            throw new IllegalArgumentException("No selective enforcement for " + permission);
24150        }
24151    }
24152
24153    @Override
24154    @Deprecated
24155    public boolean isPermissionEnforced(String permission) {
24156        // allow instant applications
24157        return true;
24158    }
24159
24160    @Override
24161    public boolean isStorageLow() {
24162        // allow instant applications
24163        final long token = Binder.clearCallingIdentity();
24164        try {
24165            final DeviceStorageMonitorInternal
24166                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24167            if (dsm != null) {
24168                return dsm.isMemoryLow();
24169            } else {
24170                return false;
24171            }
24172        } finally {
24173            Binder.restoreCallingIdentity(token);
24174        }
24175    }
24176
24177    @Override
24178    public IPackageInstaller getPackageInstaller() {
24179        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24180            return null;
24181        }
24182        return mInstallerService;
24183    }
24184
24185    private boolean userNeedsBadging(int userId) {
24186        int index = mUserNeedsBadging.indexOfKey(userId);
24187        if (index < 0) {
24188            final UserInfo userInfo;
24189            final long token = Binder.clearCallingIdentity();
24190            try {
24191                userInfo = sUserManager.getUserInfo(userId);
24192            } finally {
24193                Binder.restoreCallingIdentity(token);
24194            }
24195            final boolean b;
24196            if (userInfo != null && userInfo.isManagedProfile()) {
24197                b = true;
24198            } else {
24199                b = false;
24200            }
24201            mUserNeedsBadging.put(userId, b);
24202            return b;
24203        }
24204        return mUserNeedsBadging.valueAt(index);
24205    }
24206
24207    @Override
24208    public KeySet getKeySetByAlias(String packageName, String alias) {
24209        if (packageName == null || alias == null) {
24210            return null;
24211        }
24212        synchronized(mPackages) {
24213            final PackageParser.Package pkg = mPackages.get(packageName);
24214            if (pkg == null) {
24215                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24216                throw new IllegalArgumentException("Unknown package: " + packageName);
24217            }
24218            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24219            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24220                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24221                throw new IllegalArgumentException("Unknown package: " + packageName);
24222            }
24223            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24224            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24225        }
24226    }
24227
24228    @Override
24229    public KeySet getSigningKeySet(String packageName) {
24230        if (packageName == null) {
24231            return null;
24232        }
24233        synchronized(mPackages) {
24234            final int callingUid = Binder.getCallingUid();
24235            final int callingUserId = UserHandle.getUserId(callingUid);
24236            final PackageParser.Package pkg = mPackages.get(packageName);
24237            if (pkg == null) {
24238                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24239                throw new IllegalArgumentException("Unknown package: " + packageName);
24240            }
24241            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24242            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24243                // filter and pretend the package doesn't exist
24244                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24245                        + ", uid:" + callingUid);
24246                throw new IllegalArgumentException("Unknown package: " + packageName);
24247            }
24248            if (pkg.applicationInfo.uid != callingUid
24249                    && Process.SYSTEM_UID != callingUid) {
24250                throw new SecurityException("May not access signing KeySet of other apps.");
24251            }
24252            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24253            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24254        }
24255    }
24256
24257    @Override
24258    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24259        final int callingUid = Binder.getCallingUid();
24260        if (getInstantAppPackageName(callingUid) != null) {
24261            return false;
24262        }
24263        if (packageName == null || ks == null) {
24264            return false;
24265        }
24266        synchronized(mPackages) {
24267            final PackageParser.Package pkg = mPackages.get(packageName);
24268            if (pkg == null
24269                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24270                            UserHandle.getUserId(callingUid))) {
24271                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24272                throw new IllegalArgumentException("Unknown package: " + packageName);
24273            }
24274            IBinder ksh = ks.getToken();
24275            if (ksh instanceof KeySetHandle) {
24276                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24277                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24278            }
24279            return false;
24280        }
24281    }
24282
24283    @Override
24284    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24285        final int callingUid = Binder.getCallingUid();
24286        if (getInstantAppPackageName(callingUid) != null) {
24287            return false;
24288        }
24289        if (packageName == null || ks == null) {
24290            return false;
24291        }
24292        synchronized(mPackages) {
24293            final PackageParser.Package pkg = mPackages.get(packageName);
24294            if (pkg == null
24295                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24296                            UserHandle.getUserId(callingUid))) {
24297                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24298                throw new IllegalArgumentException("Unknown package: " + packageName);
24299            }
24300            IBinder ksh = ks.getToken();
24301            if (ksh instanceof KeySetHandle) {
24302                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24303                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24304            }
24305            return false;
24306        }
24307    }
24308
24309    private void deletePackageIfUnusedLPr(final String packageName) {
24310        PackageSetting ps = mSettings.mPackages.get(packageName);
24311        if (ps == null) {
24312            return;
24313        }
24314        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24315            // TODO Implement atomic delete if package is unused
24316            // It is currently possible that the package will be deleted even if it is installed
24317            // after this method returns.
24318            mHandler.post(new Runnable() {
24319                public void run() {
24320                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24321                            0, PackageManager.DELETE_ALL_USERS);
24322                }
24323            });
24324        }
24325    }
24326
24327    /**
24328     * Check and throw if the given before/after packages would be considered a
24329     * downgrade.
24330     */
24331    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24332            throws PackageManagerException {
24333        if (after.versionCode < before.mVersionCode) {
24334            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24335                    "Update version code " + after.versionCode + " is older than current "
24336                    + before.mVersionCode);
24337        } else if (after.versionCode == before.mVersionCode) {
24338            if (after.baseRevisionCode < before.baseRevisionCode) {
24339                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24340                        "Update base revision code " + after.baseRevisionCode
24341                        + " is older than current " + before.baseRevisionCode);
24342            }
24343
24344            if (!ArrayUtils.isEmpty(after.splitNames)) {
24345                for (int i = 0; i < after.splitNames.length; i++) {
24346                    final String splitName = after.splitNames[i];
24347                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24348                    if (j != -1) {
24349                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24350                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24351                                    "Update split " + splitName + " revision code "
24352                                    + after.splitRevisionCodes[i] + " is older than current "
24353                                    + before.splitRevisionCodes[j]);
24354                        }
24355                    }
24356                }
24357            }
24358        }
24359    }
24360
24361    private static class MoveCallbacks extends Handler {
24362        private static final int MSG_CREATED = 1;
24363        private static final int MSG_STATUS_CHANGED = 2;
24364
24365        private final RemoteCallbackList<IPackageMoveObserver>
24366                mCallbacks = new RemoteCallbackList<>();
24367
24368        private final SparseIntArray mLastStatus = new SparseIntArray();
24369
24370        public MoveCallbacks(Looper looper) {
24371            super(looper);
24372        }
24373
24374        public void register(IPackageMoveObserver callback) {
24375            mCallbacks.register(callback);
24376        }
24377
24378        public void unregister(IPackageMoveObserver callback) {
24379            mCallbacks.unregister(callback);
24380        }
24381
24382        @Override
24383        public void handleMessage(Message msg) {
24384            final SomeArgs args = (SomeArgs) msg.obj;
24385            final int n = mCallbacks.beginBroadcast();
24386            for (int i = 0; i < n; i++) {
24387                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24388                try {
24389                    invokeCallback(callback, msg.what, args);
24390                } catch (RemoteException ignored) {
24391                }
24392            }
24393            mCallbacks.finishBroadcast();
24394            args.recycle();
24395        }
24396
24397        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24398                throws RemoteException {
24399            switch (what) {
24400                case MSG_CREATED: {
24401                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24402                    break;
24403                }
24404                case MSG_STATUS_CHANGED: {
24405                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24406                    break;
24407                }
24408            }
24409        }
24410
24411        private void notifyCreated(int moveId, Bundle extras) {
24412            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24413
24414            final SomeArgs args = SomeArgs.obtain();
24415            args.argi1 = moveId;
24416            args.arg2 = extras;
24417            obtainMessage(MSG_CREATED, args).sendToTarget();
24418        }
24419
24420        private void notifyStatusChanged(int moveId, int status) {
24421            notifyStatusChanged(moveId, status, -1);
24422        }
24423
24424        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24425            Slog.v(TAG, "Move " + moveId + " status " + status);
24426
24427            final SomeArgs args = SomeArgs.obtain();
24428            args.argi1 = moveId;
24429            args.argi2 = status;
24430            args.arg3 = estMillis;
24431            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24432
24433            synchronized (mLastStatus) {
24434                mLastStatus.put(moveId, status);
24435            }
24436        }
24437    }
24438
24439    private final static class OnPermissionChangeListeners extends Handler {
24440        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24441
24442        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24443                new RemoteCallbackList<>();
24444
24445        public OnPermissionChangeListeners(Looper looper) {
24446            super(looper);
24447        }
24448
24449        @Override
24450        public void handleMessage(Message msg) {
24451            switch (msg.what) {
24452                case MSG_ON_PERMISSIONS_CHANGED: {
24453                    final int uid = msg.arg1;
24454                    handleOnPermissionsChanged(uid);
24455                } break;
24456            }
24457        }
24458
24459        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24460            mPermissionListeners.register(listener);
24461
24462        }
24463
24464        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24465            mPermissionListeners.unregister(listener);
24466        }
24467
24468        public void onPermissionsChanged(int uid) {
24469            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24470                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24471            }
24472        }
24473
24474        private void handleOnPermissionsChanged(int uid) {
24475            final int count = mPermissionListeners.beginBroadcast();
24476            try {
24477                for (int i = 0; i < count; i++) {
24478                    IOnPermissionsChangeListener callback = mPermissionListeners
24479                            .getBroadcastItem(i);
24480                    try {
24481                        callback.onPermissionsChanged(uid);
24482                    } catch (RemoteException e) {
24483                        Log.e(TAG, "Permission listener is dead", e);
24484                    }
24485                }
24486            } finally {
24487                mPermissionListeners.finishBroadcast();
24488            }
24489        }
24490    }
24491
24492    private class PackageManagerInternalImpl extends PackageManagerInternal {
24493        @Override
24494        public void setLocationPackagesProvider(PackagesProvider provider) {
24495            synchronized (mPackages) {
24496                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24497            }
24498        }
24499
24500        @Override
24501        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24502            synchronized (mPackages) {
24503                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24504            }
24505        }
24506
24507        @Override
24508        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24509            synchronized (mPackages) {
24510                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24511            }
24512        }
24513
24514        @Override
24515        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24516            synchronized (mPackages) {
24517                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24518            }
24519        }
24520
24521        @Override
24522        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24523            synchronized (mPackages) {
24524                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24525            }
24526        }
24527
24528        @Override
24529        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24530            synchronized (mPackages) {
24531                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24532            }
24533        }
24534
24535        @Override
24536        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24537            synchronized (mPackages) {
24538                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24539                        packageName, userId);
24540            }
24541        }
24542
24543        @Override
24544        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24545            synchronized (mPackages) {
24546                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24547                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24548                        packageName, userId);
24549            }
24550        }
24551
24552        @Override
24553        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24554            synchronized (mPackages) {
24555                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24556                        packageName, userId);
24557            }
24558        }
24559
24560        @Override
24561        public void setKeepUninstalledPackages(final List<String> packageList) {
24562            Preconditions.checkNotNull(packageList);
24563            List<String> removedFromList = null;
24564            synchronized (mPackages) {
24565                if (mKeepUninstalledPackages != null) {
24566                    final int packagesCount = mKeepUninstalledPackages.size();
24567                    for (int i = 0; i < packagesCount; i++) {
24568                        String oldPackage = mKeepUninstalledPackages.get(i);
24569                        if (packageList != null && packageList.contains(oldPackage)) {
24570                            continue;
24571                        }
24572                        if (removedFromList == null) {
24573                            removedFromList = new ArrayList<>();
24574                        }
24575                        removedFromList.add(oldPackage);
24576                    }
24577                }
24578                mKeepUninstalledPackages = new ArrayList<>(packageList);
24579                if (removedFromList != null) {
24580                    final int removedCount = removedFromList.size();
24581                    for (int i = 0; i < removedCount; i++) {
24582                        deletePackageIfUnusedLPr(removedFromList.get(i));
24583                    }
24584                }
24585            }
24586        }
24587
24588        @Override
24589        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24590            synchronized (mPackages) {
24591                // If we do not support permission review, done.
24592                if (!mPermissionReviewRequired) {
24593                    return false;
24594                }
24595
24596                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24597                if (packageSetting == null) {
24598                    return false;
24599                }
24600
24601                // Permission review applies only to apps not supporting the new permission model.
24602                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24603                    return false;
24604                }
24605
24606                // Legacy apps have the permission and get user consent on launch.
24607                PermissionsState permissionsState = packageSetting.getPermissionsState();
24608                return permissionsState.isPermissionReviewRequired(userId);
24609            }
24610        }
24611
24612        @Override
24613        public PackageInfo getPackageInfo(
24614                String packageName, int flags, int filterCallingUid, int userId) {
24615            return PackageManagerService.this
24616                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24617                            flags, filterCallingUid, userId);
24618        }
24619
24620        @Override
24621        public ApplicationInfo getApplicationInfo(
24622                String packageName, int flags, int filterCallingUid, int userId) {
24623            return PackageManagerService.this
24624                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24625        }
24626
24627        @Override
24628        public ActivityInfo getActivityInfo(
24629                ComponentName component, int flags, int filterCallingUid, int userId) {
24630            return PackageManagerService.this
24631                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24632        }
24633
24634        @Override
24635        public List<ResolveInfo> queryIntentActivities(
24636                Intent intent, int flags, int filterCallingUid, int userId) {
24637            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24638            return PackageManagerService.this
24639                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24640                            userId, false /*resolveForStart*/);
24641        }
24642
24643        @Override
24644        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24645                int userId) {
24646            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24647        }
24648
24649        @Override
24650        public void setDeviceAndProfileOwnerPackages(
24651                int deviceOwnerUserId, String deviceOwnerPackage,
24652                SparseArray<String> profileOwnerPackages) {
24653            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24654                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24655        }
24656
24657        @Override
24658        public boolean isPackageDataProtected(int userId, String packageName) {
24659            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24660        }
24661
24662        @Override
24663        public boolean isPackageEphemeral(int userId, String packageName) {
24664            synchronized (mPackages) {
24665                final PackageSetting ps = mSettings.mPackages.get(packageName);
24666                return ps != null ? ps.getInstantApp(userId) : false;
24667            }
24668        }
24669
24670        @Override
24671        public boolean wasPackageEverLaunched(String packageName, int userId) {
24672            synchronized (mPackages) {
24673                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24674            }
24675        }
24676
24677        @Override
24678        public void grantRuntimePermission(String packageName, String name, int userId,
24679                boolean overridePolicy) {
24680            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24681                    overridePolicy);
24682        }
24683
24684        @Override
24685        public void revokeRuntimePermission(String packageName, String name, int userId,
24686                boolean overridePolicy) {
24687            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24688                    overridePolicy);
24689        }
24690
24691        @Override
24692        public String getNameForUid(int uid) {
24693            return PackageManagerService.this.getNameForUid(uid);
24694        }
24695
24696        @Override
24697        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24698                Intent origIntent, String resolvedType, String callingPackage,
24699                Bundle verificationBundle, int userId) {
24700            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24701                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24702                    userId);
24703        }
24704
24705        @Override
24706        public void grantEphemeralAccess(int userId, Intent intent,
24707                int targetAppId, int ephemeralAppId) {
24708            synchronized (mPackages) {
24709                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24710                        targetAppId, ephemeralAppId);
24711            }
24712        }
24713
24714        @Override
24715        public boolean isInstantAppInstallerComponent(ComponentName component) {
24716            synchronized (mPackages) {
24717                return mInstantAppInstallerActivity != null
24718                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24719            }
24720        }
24721
24722        @Override
24723        public void pruneInstantApps() {
24724            mInstantAppRegistry.pruneInstantApps();
24725        }
24726
24727        @Override
24728        public String getSetupWizardPackageName() {
24729            return mSetupWizardPackage;
24730        }
24731
24732        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24733            if (policy != null) {
24734                mExternalSourcesPolicy = policy;
24735            }
24736        }
24737
24738        @Override
24739        public boolean isPackagePersistent(String packageName) {
24740            synchronized (mPackages) {
24741                PackageParser.Package pkg = mPackages.get(packageName);
24742                return pkg != null
24743                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24744                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24745                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24746                        : false;
24747            }
24748        }
24749
24750        @Override
24751        public List<PackageInfo> getOverlayPackages(int userId) {
24752            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24753            synchronized (mPackages) {
24754                for (PackageParser.Package p : mPackages.values()) {
24755                    if (p.mOverlayTarget != null) {
24756                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24757                        if (pkg != null) {
24758                            overlayPackages.add(pkg);
24759                        }
24760                    }
24761                }
24762            }
24763            return overlayPackages;
24764        }
24765
24766        @Override
24767        public List<String> getTargetPackageNames(int userId) {
24768            List<String> targetPackages = new ArrayList<>();
24769            synchronized (mPackages) {
24770                for (PackageParser.Package p : mPackages.values()) {
24771                    if (p.mOverlayTarget == null) {
24772                        targetPackages.add(p.packageName);
24773                    }
24774                }
24775            }
24776            return targetPackages;
24777        }
24778
24779        @Override
24780        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24781                @Nullable List<String> overlayPackageNames) {
24782            synchronized (mPackages) {
24783                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24784                    Slog.e(TAG, "failed to find package " + targetPackageName);
24785                    return false;
24786                }
24787                ArrayList<String> overlayPaths = null;
24788                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24789                    final int N = overlayPackageNames.size();
24790                    overlayPaths = new ArrayList<>(N);
24791                    for (int i = 0; i < N; i++) {
24792                        final String packageName = overlayPackageNames.get(i);
24793                        final PackageParser.Package pkg = mPackages.get(packageName);
24794                        if (pkg == null) {
24795                            Slog.e(TAG, "failed to find package " + packageName);
24796                            return false;
24797                        }
24798                        overlayPaths.add(pkg.baseCodePath);
24799                    }
24800                }
24801
24802                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24803                ps.setOverlayPaths(overlayPaths, userId);
24804                return true;
24805            }
24806        }
24807
24808        @Override
24809        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24810                int flags, int userId) {
24811            return resolveIntentInternal(
24812                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24813        }
24814
24815        @Override
24816        public ResolveInfo resolveService(Intent intent, String resolvedType,
24817                int flags, int userId, int callingUid) {
24818            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24819        }
24820
24821        @Override
24822        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24823            synchronized (mPackages) {
24824                mIsolatedOwners.put(isolatedUid, ownerUid);
24825            }
24826        }
24827
24828        @Override
24829        public void removeIsolatedUid(int isolatedUid) {
24830            synchronized (mPackages) {
24831                mIsolatedOwners.delete(isolatedUid);
24832            }
24833        }
24834
24835        @Override
24836        public int getUidTargetSdkVersion(int uid) {
24837            synchronized (mPackages) {
24838                return getUidTargetSdkVersionLockedLPr(uid);
24839            }
24840        }
24841
24842        @Override
24843        public boolean canAccessInstantApps(int callingUid, int userId) {
24844            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24845        }
24846    }
24847
24848    @Override
24849    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24850        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24851        synchronized (mPackages) {
24852            final long identity = Binder.clearCallingIdentity();
24853            try {
24854                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24855                        packageNames, userId);
24856            } finally {
24857                Binder.restoreCallingIdentity(identity);
24858            }
24859        }
24860    }
24861
24862    @Override
24863    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24864        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24865        synchronized (mPackages) {
24866            final long identity = Binder.clearCallingIdentity();
24867            try {
24868                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24869                        packageNames, userId);
24870            } finally {
24871                Binder.restoreCallingIdentity(identity);
24872            }
24873        }
24874    }
24875
24876    private static void enforceSystemOrPhoneCaller(String tag) {
24877        int callingUid = Binder.getCallingUid();
24878        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24879            throw new SecurityException(
24880                    "Cannot call " + tag + " from UID " + callingUid);
24881        }
24882    }
24883
24884    boolean isHistoricalPackageUsageAvailable() {
24885        return mPackageUsage.isHistoricalPackageUsageAvailable();
24886    }
24887
24888    /**
24889     * Return a <b>copy</b> of the collection of packages known to the package manager.
24890     * @return A copy of the values of mPackages.
24891     */
24892    Collection<PackageParser.Package> getPackages() {
24893        synchronized (mPackages) {
24894            return new ArrayList<>(mPackages.values());
24895        }
24896    }
24897
24898    /**
24899     * Logs process start information (including base APK hash) to the security log.
24900     * @hide
24901     */
24902    @Override
24903    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24904            String apkFile, int pid) {
24905        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24906            return;
24907        }
24908        if (!SecurityLog.isLoggingEnabled()) {
24909            return;
24910        }
24911        Bundle data = new Bundle();
24912        data.putLong("startTimestamp", System.currentTimeMillis());
24913        data.putString("processName", processName);
24914        data.putInt("uid", uid);
24915        data.putString("seinfo", seinfo);
24916        data.putString("apkFile", apkFile);
24917        data.putInt("pid", pid);
24918        Message msg = mProcessLoggingHandler.obtainMessage(
24919                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24920        msg.setData(data);
24921        mProcessLoggingHandler.sendMessage(msg);
24922    }
24923
24924    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24925        return mCompilerStats.getPackageStats(pkgName);
24926    }
24927
24928    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24929        return getOrCreateCompilerPackageStats(pkg.packageName);
24930    }
24931
24932    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24933        return mCompilerStats.getOrCreatePackageStats(pkgName);
24934    }
24935
24936    public void deleteCompilerPackageStats(String pkgName) {
24937        mCompilerStats.deletePackageStats(pkgName);
24938    }
24939
24940    @Override
24941    public int getInstallReason(String packageName, int userId) {
24942        final int callingUid = Binder.getCallingUid();
24943        enforceCrossUserPermission(callingUid, userId,
24944                true /* requireFullPermission */, false /* checkShell */,
24945                "get install reason");
24946        synchronized (mPackages) {
24947            final PackageSetting ps = mSettings.mPackages.get(packageName);
24948            if (filterAppAccessLPr(ps, callingUid, userId)) {
24949                return PackageManager.INSTALL_REASON_UNKNOWN;
24950            }
24951            if (ps != null) {
24952                return ps.getInstallReason(userId);
24953            }
24954        }
24955        return PackageManager.INSTALL_REASON_UNKNOWN;
24956    }
24957
24958    @Override
24959    public boolean canRequestPackageInstalls(String packageName, int userId) {
24960        return canRequestPackageInstallsInternal(packageName, 0, userId,
24961                true /* throwIfPermNotDeclared*/);
24962    }
24963
24964    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24965            boolean throwIfPermNotDeclared) {
24966        int callingUid = Binder.getCallingUid();
24967        int uid = getPackageUid(packageName, 0, userId);
24968        if (callingUid != uid && callingUid != Process.ROOT_UID
24969                && callingUid != Process.SYSTEM_UID) {
24970            throw new SecurityException(
24971                    "Caller uid " + callingUid + " does not own package " + packageName);
24972        }
24973        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24974        if (info == null) {
24975            return false;
24976        }
24977        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24978            return false;
24979        }
24980        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24981        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24982        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24983            if (throwIfPermNotDeclared) {
24984                throw new SecurityException("Need to declare " + appOpPermission
24985                        + " to call this api");
24986            } else {
24987                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24988                return false;
24989            }
24990        }
24991        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24992            return false;
24993        }
24994        if (mExternalSourcesPolicy != null) {
24995            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24996            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24997                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24998            }
24999        }
25000        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25001    }
25002
25003    @Override
25004    public ComponentName getInstantAppResolverSettingsComponent() {
25005        return mInstantAppResolverSettingsComponent;
25006    }
25007
25008    @Override
25009    public ComponentName getInstantAppInstallerComponent() {
25010        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25011            return null;
25012        }
25013        return mInstantAppInstallerActivity == null
25014                ? null : mInstantAppInstallerActivity.getComponentName();
25015    }
25016
25017    @Override
25018    public String getInstantAppAndroidId(String packageName, int userId) {
25019        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25020                "getInstantAppAndroidId");
25021        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25022                true /* requireFullPermission */, false /* checkShell */,
25023                "getInstantAppAndroidId");
25024        // Make sure the target is an Instant App.
25025        if (!isInstantApp(packageName, userId)) {
25026            return null;
25027        }
25028        synchronized (mPackages) {
25029            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25030        }
25031    }
25032
25033    boolean canHaveOatDir(String packageName) {
25034        synchronized (mPackages) {
25035            PackageParser.Package p = mPackages.get(packageName);
25036            if (p == null) {
25037                return false;
25038            }
25039            return p.canHaveOatDir();
25040        }
25041    }
25042
25043    private String getOatDir(PackageParser.Package pkg) {
25044        if (!pkg.canHaveOatDir()) {
25045            return null;
25046        }
25047        File codePath = new File(pkg.codePath);
25048        if (codePath.isDirectory()) {
25049            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25050        }
25051        return null;
25052    }
25053
25054    void deleteOatArtifactsOfPackage(String packageName) {
25055        final String[] instructionSets;
25056        final List<String> codePaths;
25057        final String oatDir;
25058        final PackageParser.Package pkg;
25059        synchronized (mPackages) {
25060            pkg = mPackages.get(packageName);
25061        }
25062        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25063        codePaths = pkg.getAllCodePaths();
25064        oatDir = getOatDir(pkg);
25065
25066        for (String codePath : codePaths) {
25067            for (String isa : instructionSets) {
25068                try {
25069                    mInstaller.deleteOdex(codePath, isa, oatDir);
25070                } catch (InstallerException e) {
25071                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25072                }
25073            }
25074        }
25075    }
25076
25077    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25078        Set<String> unusedPackages = new HashSet<>();
25079        long currentTimeInMillis = System.currentTimeMillis();
25080        synchronized (mPackages) {
25081            for (PackageParser.Package pkg : mPackages.values()) {
25082                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25083                if (ps == null) {
25084                    continue;
25085                }
25086                PackageDexUsage.PackageUseInfo packageUseInfo =
25087                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25088                if (PackageManagerServiceUtils
25089                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25090                                downgradeTimeThresholdMillis, packageUseInfo,
25091                                pkg.getLatestPackageUseTimeInMills(),
25092                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25093                    unusedPackages.add(pkg.packageName);
25094                }
25095            }
25096        }
25097        return unusedPackages;
25098    }
25099}
25100
25101interface PackageSender {
25102    void sendPackageBroadcast(final String action, final String pkg,
25103        final Bundle extras, final int flags, final String targetPkg,
25104        final IIntentReceiver finishedReceiver, final int[] userIds);
25105    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
25106        int appId, int... userIds);
25107}
25108