PackageManagerService.java revision c606627e6c931d4d1e60ce29f7802d7bd9f4403d
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
106
107import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
108
109import android.Manifest;
110import android.annotation.IntDef;
111import android.annotation.NonNull;
112import android.annotation.Nullable;
113import android.app.ActivityManager;
114import android.app.AppOpsManager;
115import android.app.IActivityManager;
116import android.app.ResourcesManager;
117import android.app.admin.IDevicePolicyManager;
118import android.app.admin.SecurityLog;
119import android.app.backup.IBackupManager;
120import android.content.BroadcastReceiver;
121import android.content.ComponentName;
122import android.content.ContentResolver;
123import android.content.Context;
124import android.content.IIntentReceiver;
125import android.content.Intent;
126import android.content.IntentFilter;
127import android.content.IntentSender;
128import android.content.IntentSender.SendIntentException;
129import android.content.ServiceConnection;
130import android.content.pm.ActivityInfo;
131import android.content.pm.ApplicationInfo;
132import android.content.pm.AppsQueryHelper;
133import android.content.pm.AuxiliaryResolveInfo;
134import android.content.pm.ChangedPackages;
135import android.content.pm.ComponentInfo;
136import android.content.pm.FallbackCategoryProvider;
137import android.content.pm.FeatureInfo;
138import android.content.pm.IDexModuleRegisterCallback;
139import android.content.pm.IOnPermissionsChangeListener;
140import android.content.pm.IPackageDataObserver;
141import android.content.pm.IPackageDeleteObserver;
142import android.content.pm.IPackageDeleteObserver2;
143import android.content.pm.IPackageInstallObserver2;
144import android.content.pm.IPackageInstaller;
145import android.content.pm.IPackageManager;
146import android.content.pm.IPackageMoveObserver;
147import android.content.pm.IPackageStatsObserver;
148import android.content.pm.InstantAppInfo;
149import android.content.pm.InstantAppRequest;
150import android.content.pm.InstantAppResolveInfo;
151import android.content.pm.InstrumentationInfo;
152import android.content.pm.IntentFilterVerificationInfo;
153import android.content.pm.KeySet;
154import android.content.pm.PackageCleanItem;
155import android.content.pm.PackageInfo;
156import android.content.pm.PackageInfoLite;
157import android.content.pm.PackageInstaller;
158import android.content.pm.PackageManager;
159import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
160import android.content.pm.PackageManagerInternal;
161import android.content.pm.PackageParser;
162import android.content.pm.PackageParser.ActivityIntentInfo;
163import android.content.pm.PackageParser.PackageLite;
164import android.content.pm.PackageParser.PackageParserException;
165import android.content.pm.PackageStats;
166import android.content.pm.PackageUserState;
167import android.content.pm.ParceledListSlice;
168import android.content.pm.PermissionGroupInfo;
169import android.content.pm.PermissionInfo;
170import android.content.pm.ProviderInfo;
171import android.content.pm.ResolveInfo;
172import android.content.pm.ServiceInfo;
173import android.content.pm.SharedLibraryInfo;
174import android.content.pm.Signature;
175import android.content.pm.UserInfo;
176import android.content.pm.VerifierDeviceIdentity;
177import android.content.pm.VerifierInfo;
178import android.content.pm.VersionedPackage;
179import android.content.res.Resources;
180import android.database.ContentObserver;
181import android.graphics.Bitmap;
182import android.hardware.display.DisplayManager;
183import android.net.Uri;
184import android.os.Binder;
185import android.os.Build;
186import android.os.Bundle;
187import android.os.Debug;
188import android.os.Environment;
189import android.os.Environment.UserEnvironment;
190import android.os.FileUtils;
191import android.os.Handler;
192import android.os.IBinder;
193import android.os.Looper;
194import android.os.Message;
195import android.os.Parcel;
196import android.os.ParcelFileDescriptor;
197import android.os.PatternMatcher;
198import android.os.Process;
199import android.os.RemoteCallbackList;
200import android.os.RemoteException;
201import android.os.ResultReceiver;
202import android.os.SELinux;
203import android.os.ServiceManager;
204import android.os.ShellCallback;
205import android.os.SystemClock;
206import android.os.SystemProperties;
207import android.os.Trace;
208import android.os.UserHandle;
209import android.os.UserManager;
210import android.os.UserManagerInternal;
211import android.os.storage.IStorageManager;
212import android.os.storage.StorageEventListener;
213import android.os.storage.StorageManager;
214import android.os.storage.StorageManagerInternal;
215import android.os.storage.VolumeInfo;
216import android.os.storage.VolumeRecord;
217import android.provider.Settings.Global;
218import android.provider.Settings.Secure;
219import android.security.KeyStore;
220import android.security.SystemKeyStore;
221import android.service.pm.PackageServiceDumpProto;
222import android.system.ErrnoException;
223import android.system.Os;
224import android.text.TextUtils;
225import android.text.format.DateUtils;
226import android.util.ArrayMap;
227import android.util.ArraySet;
228import android.util.Base64;
229import android.util.BootTimingsTraceLog;
230import android.util.DisplayMetrics;
231import android.util.EventLog;
232import android.util.ExceptionUtils;
233import android.util.Log;
234import android.util.LogPrinter;
235import android.util.MathUtils;
236import android.util.PackageUtils;
237import android.util.Pair;
238import android.util.PrintStreamPrinter;
239import android.util.Slog;
240import android.util.SparseArray;
241import android.util.SparseBooleanArray;
242import android.util.SparseIntArray;
243import android.util.Xml;
244import android.util.jar.StrictJarFile;
245import android.util.proto.ProtoOutputStream;
246import android.view.Display;
247
248import com.android.internal.R;
249import com.android.internal.annotations.GuardedBy;
250import com.android.internal.app.IMediaContainerService;
251import com.android.internal.app.ResolverActivity;
252import com.android.internal.content.NativeLibraryHelper;
253import com.android.internal.content.PackageHelper;
254import com.android.internal.logging.MetricsLogger;
255import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
256import com.android.internal.os.IParcelFileDescriptorFactory;
257import com.android.internal.os.RoSystemProperties;
258import com.android.internal.os.SomeArgs;
259import com.android.internal.os.Zygote;
260import com.android.internal.telephony.CarrierAppUtils;
261import com.android.internal.util.ArrayUtils;
262import com.android.internal.util.ConcurrentUtils;
263import com.android.internal.util.DumpUtils;
264import com.android.internal.util.FastPrintWriter;
265import com.android.internal.util.FastXmlSerializer;
266import com.android.internal.util.IndentingPrintWriter;
267import com.android.internal.util.Preconditions;
268import com.android.internal.util.XmlUtils;
269import com.android.server.AttributeCache;
270import com.android.server.DeviceIdleController;
271import com.android.server.EventLogTags;
272import com.android.server.FgThread;
273import com.android.server.IntentResolver;
274import com.android.server.LocalServices;
275import com.android.server.LockGuard;
276import com.android.server.ServiceThread;
277import com.android.server.SystemConfig;
278import com.android.server.SystemServerInitThreadPool;
279import com.android.server.Watchdog;
280import com.android.server.net.NetworkPolicyManagerInternal;
281import com.android.server.pm.Installer.InstallerException;
282import com.android.server.pm.PermissionsState.PermissionState;
283import com.android.server.pm.Settings.DatabaseVersion;
284import com.android.server.pm.Settings.VersionInfo;
285import com.android.server.pm.dex.DexManager;
286import com.android.server.pm.dex.PackageDexUsage;
287import com.android.server.storage.DeviceStorageMonitorInternal;
288
289import dalvik.system.CloseGuard;
290import dalvik.system.DexFile;
291import dalvik.system.VMRuntime;
292
293import libcore.io.IoUtils;
294import libcore.util.EmptyArray;
295
296import org.xmlpull.v1.XmlPullParser;
297import org.xmlpull.v1.XmlPullParserException;
298import org.xmlpull.v1.XmlSerializer;
299
300import java.io.BufferedOutputStream;
301import java.io.BufferedReader;
302import java.io.ByteArrayInputStream;
303import java.io.ByteArrayOutputStream;
304import java.io.File;
305import java.io.FileDescriptor;
306import java.io.FileInputStream;
307import java.io.FileOutputStream;
308import java.io.FileReader;
309import java.io.FilenameFilter;
310import java.io.IOException;
311import java.io.PrintWriter;
312import java.lang.annotation.Retention;
313import java.lang.annotation.RetentionPolicy;
314import java.nio.charset.StandardCharsets;
315import java.security.DigestInputStream;
316import java.security.MessageDigest;
317import java.security.NoSuchAlgorithmException;
318import java.security.PublicKey;
319import java.security.SecureRandom;
320import java.security.cert.Certificate;
321import java.security.cert.CertificateEncodingException;
322import java.security.cert.CertificateException;
323import java.text.SimpleDateFormat;
324import java.util.ArrayList;
325import java.util.Arrays;
326import java.util.Collection;
327import java.util.Collections;
328import java.util.Comparator;
329import java.util.Date;
330import java.util.HashMap;
331import java.util.HashSet;
332import java.util.Iterator;
333import java.util.List;
334import java.util.Map;
335import java.util.Objects;
336import java.util.Set;
337import java.util.concurrent.CountDownLatch;
338import java.util.concurrent.Future;
339import java.util.concurrent.TimeUnit;
340import java.util.concurrent.atomic.AtomicBoolean;
341import java.util.concurrent.atomic.AtomicInteger;
342
343/**
344 * Keep track of all those APKs everywhere.
345 * <p>
346 * Internally there are two important locks:
347 * <ul>
348 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
349 * and other related state. It is a fine-grained lock that should only be held
350 * momentarily, as it's one of the most contended locks in the system.
351 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
352 * operations typically involve heavy lifting of application data on disk. Since
353 * {@code installd} is single-threaded, and it's operations can often be slow,
354 * this lock should never be acquired while already holding {@link #mPackages}.
355 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
356 * holding {@link #mInstallLock}.
357 * </ul>
358 * Many internal methods rely on the caller to hold the appropriate locks, and
359 * this contract is expressed through method name suffixes:
360 * <ul>
361 * <li>fooLI(): the caller must hold {@link #mInstallLock}
362 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
363 * being modified must be frozen
364 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
365 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
366 * </ul>
367 * <p>
368 * Because this class is very central to the platform's security; please run all
369 * CTS and unit tests whenever making modifications:
370 *
371 * <pre>
372 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
373 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
374 * </pre>
375 */
376public class PackageManagerService extends IPackageManager.Stub
377        implements PackageSender {
378    static final String TAG = "PackageManager";
379    static final boolean DEBUG_SETTINGS = false;
380    static final boolean DEBUG_PREFERRED = false;
381    static final boolean DEBUG_UPGRADE = false;
382    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
383    private static final boolean DEBUG_BACKUP = false;
384    private static final boolean DEBUG_INSTALL = false;
385    private static final boolean DEBUG_REMOVE = false;
386    private static final boolean DEBUG_BROADCASTS = false;
387    private static final boolean DEBUG_SHOW_INFO = false;
388    private static final boolean DEBUG_PACKAGE_INFO = false;
389    private static final boolean DEBUG_INTENT_MATCHING = false;
390    private static final boolean DEBUG_PACKAGE_SCANNING = false;
391    private static final boolean DEBUG_VERIFY = false;
392    private static final boolean DEBUG_FILTERS = false;
393    private static final boolean DEBUG_PERMISSIONS = false;
394    private static final boolean DEBUG_SHARED_LIBRARIES = false;
395
396    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
397    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
398    // user, but by default initialize to this.
399    public static final boolean DEBUG_DEXOPT = false;
400
401    private static final boolean DEBUG_ABI_SELECTION = false;
402    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
403    private static final boolean DEBUG_TRIAGED_MISSING = false;
404    private static final boolean DEBUG_APP_DATA = false;
405
406    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
407    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
408
409    private static final boolean HIDE_EPHEMERAL_APIS = false;
410
411    private static final boolean ENABLE_FREE_CACHE_V2 =
412            SystemProperties.getBoolean("fw.free_cache_v2", true);
413
414    private static final int RADIO_UID = Process.PHONE_UID;
415    private static final int LOG_UID = Process.LOG_UID;
416    private static final int NFC_UID = Process.NFC_UID;
417    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
418    private static final int SHELL_UID = Process.SHELL_UID;
419
420    // Cap the size of permission trees that 3rd party apps can define
421    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
422
423    // Suffix used during package installation when copying/moving
424    // package apks to install directory.
425    private static final String INSTALL_PACKAGE_SUFFIX = "-";
426
427    static final int SCAN_NO_DEX = 1<<1;
428    static final int SCAN_FORCE_DEX = 1<<2;
429    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
430    static final int SCAN_NEW_INSTALL = 1<<4;
431    static final int SCAN_UPDATE_TIME = 1<<5;
432    static final int SCAN_BOOTING = 1<<6;
433    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
434    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
435    static final int SCAN_REPLACING = 1<<9;
436    static final int SCAN_REQUIRE_KNOWN = 1<<10;
437    static final int SCAN_MOVE = 1<<11;
438    static final int SCAN_INITIAL = 1<<12;
439    static final int SCAN_CHECK_ONLY = 1<<13;
440    static final int SCAN_DONT_KILL_APP = 1<<14;
441    static final int SCAN_IGNORE_FROZEN = 1<<15;
442    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
443    static final int SCAN_AS_INSTANT_APP = 1<<17;
444    static final int SCAN_AS_FULL_APP = 1<<18;
445    /** Should not be with the scan flags */
446    static final int FLAGS_REMOVE_CHATTY = 1<<31;
447
448    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
449
450    private static final int[] EMPTY_INT_ARRAY = new int[0];
451
452    private static final int TYPE_UNKNOWN = 0;
453    private static final int TYPE_ACTIVITY = 1;
454    private static final int TYPE_RECEIVER = 2;
455    private static final int TYPE_SERVICE = 3;
456    private static final int TYPE_PROVIDER = 4;
457    @IntDef(prefix = { "TYPE_" }, value = {
458            TYPE_UNKNOWN,
459            TYPE_ACTIVITY,
460            TYPE_RECEIVER,
461            TYPE_SERVICE,
462            TYPE_PROVIDER,
463    })
464    @Retention(RetentionPolicy.SOURCE)
465    public @interface ComponentType {}
466
467    /**
468     * Timeout (in milliseconds) after which the watchdog should declare that
469     * our handler thread is wedged.  The usual default for such things is one
470     * minute but we sometimes do very lengthy I/O operations on this thread,
471     * such as installing multi-gigabyte applications, so ours needs to be longer.
472     */
473    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
474
475    /**
476     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
477     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
478     * settings entry if available, otherwise we use the hardcoded default.  If it's been
479     * more than this long since the last fstrim, we force one during the boot sequence.
480     *
481     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
482     * one gets run at the next available charging+idle time.  This final mandatory
483     * no-fstrim check kicks in only of the other scheduling criteria is never met.
484     */
485    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
486
487    /**
488     * Whether verification is enabled by default.
489     */
490    private static final boolean DEFAULT_VERIFY_ENABLE = true;
491
492    /**
493     * The default maximum time to wait for the verification agent to return in
494     * milliseconds.
495     */
496    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
497
498    /**
499     * The default response for package verification timeout.
500     *
501     * This can be either PackageManager.VERIFICATION_ALLOW or
502     * PackageManager.VERIFICATION_REJECT.
503     */
504    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
505
506    static final String PLATFORM_PACKAGE_NAME = "android";
507
508    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
509
510    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
511            DEFAULT_CONTAINER_PACKAGE,
512            "com.android.defcontainer.DefaultContainerService");
513
514    private static final String KILL_APP_REASON_GIDS_CHANGED =
515            "permission grant or revoke changed gids";
516
517    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
518            "permissions revoked";
519
520    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
521
522    private static final String PACKAGE_SCHEME = "package";
523
524    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
525
526    /** Permission grant: not grant the permission. */
527    private static final int GRANT_DENIED = 1;
528
529    /** Permission grant: grant the permission as an install permission. */
530    private static final int GRANT_INSTALL = 2;
531
532    /** Permission grant: grant the permission as a runtime one. */
533    private static final int GRANT_RUNTIME = 3;
534
535    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
536    private static final int GRANT_UPGRADE = 4;
537
538    /** Canonical intent used to identify what counts as a "web browser" app */
539    private static final Intent sBrowserIntent;
540    static {
541        sBrowserIntent = new Intent();
542        sBrowserIntent.setAction(Intent.ACTION_VIEW);
543        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
544        sBrowserIntent.setData(Uri.parse("http:"));
545    }
546
547    /**
548     * The set of all protected actions [i.e. those actions for which a high priority
549     * intent filter is disallowed].
550     */
551    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
552    static {
553        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
554        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
555        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
556        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
557    }
558
559    // Compilation reasons.
560    public static final int REASON_FIRST_BOOT = 0;
561    public static final int REASON_BOOT = 1;
562    public static final int REASON_INSTALL = 2;
563    public static final int REASON_BACKGROUND_DEXOPT = 3;
564    public static final int REASON_AB_OTA = 4;
565    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
566
567    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
568
569    /** All dangerous permission names in the same order as the events in MetricsEvent */
570    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
571            Manifest.permission.READ_CALENDAR,
572            Manifest.permission.WRITE_CALENDAR,
573            Manifest.permission.CAMERA,
574            Manifest.permission.READ_CONTACTS,
575            Manifest.permission.WRITE_CONTACTS,
576            Manifest.permission.GET_ACCOUNTS,
577            Manifest.permission.ACCESS_FINE_LOCATION,
578            Manifest.permission.ACCESS_COARSE_LOCATION,
579            Manifest.permission.RECORD_AUDIO,
580            Manifest.permission.READ_PHONE_STATE,
581            Manifest.permission.CALL_PHONE,
582            Manifest.permission.READ_CALL_LOG,
583            Manifest.permission.WRITE_CALL_LOG,
584            Manifest.permission.ADD_VOICEMAIL,
585            Manifest.permission.USE_SIP,
586            Manifest.permission.PROCESS_OUTGOING_CALLS,
587            Manifest.permission.READ_CELL_BROADCASTS,
588            Manifest.permission.BODY_SENSORS,
589            Manifest.permission.SEND_SMS,
590            Manifest.permission.RECEIVE_SMS,
591            Manifest.permission.READ_SMS,
592            Manifest.permission.RECEIVE_WAP_PUSH,
593            Manifest.permission.RECEIVE_MMS,
594            Manifest.permission.READ_EXTERNAL_STORAGE,
595            Manifest.permission.WRITE_EXTERNAL_STORAGE,
596            Manifest.permission.READ_PHONE_NUMBERS,
597            Manifest.permission.ANSWER_PHONE_CALLS);
598
599
600    /**
601     * Version number for the package parser cache. Increment this whenever the format or
602     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
603     */
604    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
605
606    /**
607     * Whether the package parser cache is enabled.
608     */
609    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
610
611    final ServiceThread mHandlerThread;
612
613    final PackageHandler mHandler;
614
615    private final ProcessLoggingHandler mProcessLoggingHandler;
616
617    /**
618     * Messages for {@link #mHandler} that need to wait for system ready before
619     * being dispatched.
620     */
621    private ArrayList<Message> mPostSystemReadyMessages;
622
623    final int mSdkVersion = Build.VERSION.SDK_INT;
624
625    final Context mContext;
626    final boolean mFactoryTest;
627    final boolean mOnlyCore;
628    final DisplayMetrics mMetrics;
629    final int mDefParseFlags;
630    final String[] mSeparateProcesses;
631    final boolean mIsUpgrade;
632    final boolean mIsPreNUpgrade;
633    final boolean mIsPreNMR1Upgrade;
634
635    // Have we told the Activity Manager to whitelist the default container service by uid yet?
636    @GuardedBy("mPackages")
637    boolean mDefaultContainerWhitelisted = false;
638
639    @GuardedBy("mPackages")
640    private boolean mDexOptDialogShown;
641
642    /** The location for ASEC container files on internal storage. */
643    final String mAsecInternalPath;
644
645    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
646    // LOCK HELD.  Can be called with mInstallLock held.
647    @GuardedBy("mInstallLock")
648    final Installer mInstaller;
649
650    /** Directory where installed third-party apps stored */
651    final File mAppInstallDir;
652
653    /**
654     * Directory to which applications installed internally have their
655     * 32 bit native libraries copied.
656     */
657    private File mAppLib32InstallDir;
658
659    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
660    // apps.
661    final File mDrmAppPrivateInstallDir;
662
663    // ----------------------------------------------------------------
664
665    // Lock for state used when installing and doing other long running
666    // operations.  Methods that must be called with this lock held have
667    // the suffix "LI".
668    final Object mInstallLock = new Object();
669
670    // ----------------------------------------------------------------
671
672    // Keys are String (package name), values are Package.  This also serves
673    // as the lock for the global state.  Methods that must be called with
674    // this lock held have the prefix "LP".
675    @GuardedBy("mPackages")
676    final ArrayMap<String, PackageParser.Package> mPackages =
677            new ArrayMap<String, PackageParser.Package>();
678
679    final ArrayMap<String, Set<String>> mKnownCodebase =
680            new ArrayMap<String, Set<String>>();
681
682    // Keys are isolated uids and values are the uid of the application
683    // that created the isolated proccess.
684    @GuardedBy("mPackages")
685    final SparseIntArray mIsolatedOwners = new SparseIntArray();
686
687    /**
688     * Tracks new system packages [received in an OTA] that we expect to
689     * find updated user-installed versions. Keys are package name, values
690     * are package location.
691     */
692    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
693    /**
694     * Tracks high priority intent filters for protected actions. During boot, certain
695     * filter actions are protected and should never be allowed to have a high priority
696     * intent filter for them. However, there is one, and only one exception -- the
697     * setup wizard. It must be able to define a high priority intent filter for these
698     * actions to ensure there are no escapes from the wizard. We need to delay processing
699     * of these during boot as we need to look at all of the system packages in order
700     * to know which component is the setup wizard.
701     */
702    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
703    /**
704     * Whether or not processing protected filters should be deferred.
705     */
706    private boolean mDeferProtectedFilters = true;
707
708    /**
709     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
710     */
711    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
712    /**
713     * Whether or not system app permissions should be promoted from install to runtime.
714     */
715    boolean mPromoteSystemApps;
716
717    @GuardedBy("mPackages")
718    final Settings mSettings;
719
720    /**
721     * Set of package names that are currently "frozen", which means active
722     * surgery is being done on the code/data for that package. The platform
723     * will refuse to launch frozen packages to avoid race conditions.
724     *
725     * @see PackageFreezer
726     */
727    @GuardedBy("mPackages")
728    final ArraySet<String> mFrozenPackages = new ArraySet<>();
729
730    final ProtectedPackages mProtectedPackages;
731
732    @GuardedBy("mLoadedVolumes")
733    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
734
735    boolean mFirstBoot;
736
737    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
738
739    // System configuration read by SystemConfig.
740    final int[] mGlobalGids;
741    final SparseArray<ArraySet<String>> mSystemPermissions;
742    @GuardedBy("mAvailableFeatures")
743    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
744
745    // If mac_permissions.xml was found for seinfo labeling.
746    boolean mFoundPolicyFile;
747
748    private final InstantAppRegistry mInstantAppRegistry;
749
750    @GuardedBy("mPackages")
751    int mChangedPackagesSequenceNumber;
752    /**
753     * List of changed [installed, removed or updated] packages.
754     * mapping from user id -> sequence number -> package name
755     */
756    @GuardedBy("mPackages")
757    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
758    /**
759     * The sequence number of the last change to a package.
760     * mapping from user id -> package name -> sequence number
761     */
762    @GuardedBy("mPackages")
763    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
764
765    class PackageParserCallback implements PackageParser.Callback {
766        @Override public final boolean hasFeature(String feature) {
767            return PackageManagerService.this.hasSystemFeature(feature, 0);
768        }
769
770        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
771                Collection<PackageParser.Package> allPackages, String targetPackageName) {
772            List<PackageParser.Package> overlayPackages = null;
773            for (PackageParser.Package p : allPackages) {
774                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
775                    if (overlayPackages == null) {
776                        overlayPackages = new ArrayList<PackageParser.Package>();
777                    }
778                    overlayPackages.add(p);
779                }
780            }
781            if (overlayPackages != null) {
782                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
783                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
784                        return p1.mOverlayPriority - p2.mOverlayPriority;
785                    }
786                };
787                Collections.sort(overlayPackages, cmp);
788            }
789            return overlayPackages;
790        }
791
792        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
793                String targetPackageName, String targetPath) {
794            if ("android".equals(targetPackageName)) {
795                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
796                // native AssetManager.
797                return null;
798            }
799            List<PackageParser.Package> overlayPackages =
800                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
801            if (overlayPackages == null || overlayPackages.isEmpty()) {
802                return null;
803            }
804            List<String> overlayPathList = null;
805            for (PackageParser.Package overlayPackage : overlayPackages) {
806                if (targetPath == null) {
807                    if (overlayPathList == null) {
808                        overlayPathList = new ArrayList<String>();
809                    }
810                    overlayPathList.add(overlayPackage.baseCodePath);
811                    continue;
812                }
813
814                try {
815                    // Creates idmaps for system to parse correctly the Android manifest of the
816                    // target package.
817                    //
818                    // OverlayManagerService will update each of them with a correct gid from its
819                    // target package app id.
820                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
821                            UserHandle.getSharedAppGid(
822                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
823                    if (overlayPathList == null) {
824                        overlayPathList = new ArrayList<String>();
825                    }
826                    overlayPathList.add(overlayPackage.baseCodePath);
827                } catch (InstallerException e) {
828                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
829                            overlayPackage.baseCodePath);
830                }
831            }
832            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
833        }
834
835        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
836            synchronized (mPackages) {
837                return getStaticOverlayPathsLocked(
838                        mPackages.values(), targetPackageName, targetPath);
839            }
840        }
841
842        @Override public final String[] getOverlayApks(String targetPackageName) {
843            return getStaticOverlayPaths(targetPackageName, null);
844        }
845
846        @Override public final String[] getOverlayPaths(String targetPackageName,
847                String targetPath) {
848            return getStaticOverlayPaths(targetPackageName, targetPath);
849        }
850    };
851
852    class ParallelPackageParserCallback extends PackageParserCallback {
853        List<PackageParser.Package> mOverlayPackages = null;
854
855        void findStaticOverlayPackages() {
856            synchronized (mPackages) {
857                for (PackageParser.Package p : mPackages.values()) {
858                    if (p.mIsStaticOverlay) {
859                        if (mOverlayPackages == null) {
860                            mOverlayPackages = new ArrayList<PackageParser.Package>();
861                        }
862                        mOverlayPackages.add(p);
863                    }
864                }
865            }
866        }
867
868        @Override
869        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
870            // We can trust mOverlayPackages without holding mPackages because package uninstall
871            // can't happen while running parallel parsing.
872            // Moreover holding mPackages on each parsing thread causes dead-lock.
873            return mOverlayPackages == null ? null :
874                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
875        }
876    }
877
878    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
879    final ParallelPackageParserCallback mParallelPackageParserCallback =
880            new ParallelPackageParserCallback();
881
882    public static final class SharedLibraryEntry {
883        public final @Nullable String path;
884        public final @Nullable String apk;
885        public final @NonNull SharedLibraryInfo info;
886
887        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
888                String declaringPackageName, int declaringPackageVersionCode) {
889            path = _path;
890            apk = _apk;
891            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
892                    declaringPackageName, declaringPackageVersionCode), null);
893        }
894    }
895
896    // Currently known shared libraries.
897    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
898    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
899            new ArrayMap<>();
900
901    // All available activities, for your resolving pleasure.
902    final ActivityIntentResolver mActivities =
903            new ActivityIntentResolver();
904
905    // All available receivers, for your resolving pleasure.
906    final ActivityIntentResolver mReceivers =
907            new ActivityIntentResolver();
908
909    // All available services, for your resolving pleasure.
910    final ServiceIntentResolver mServices = new ServiceIntentResolver();
911
912    // All available providers, for your resolving pleasure.
913    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
914
915    // Mapping from provider base names (first directory in content URI codePath)
916    // to the provider information.
917    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
918            new ArrayMap<String, PackageParser.Provider>();
919
920    // Mapping from instrumentation class names to info about them.
921    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
922            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
923
924    // Mapping from permission names to info about them.
925    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
926            new ArrayMap<String, PackageParser.PermissionGroup>();
927
928    // Packages whose data we have transfered into another package, thus
929    // should no longer exist.
930    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
931
932    // Broadcast actions that are only available to the system.
933    @GuardedBy("mProtectedBroadcasts")
934    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
935
936    /** List of packages waiting for verification. */
937    final SparseArray<PackageVerificationState> mPendingVerification
938            = new SparseArray<PackageVerificationState>();
939
940    /** Set of packages associated with each app op permission. */
941    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
942
943    final PackageInstallerService mInstallerService;
944
945    private final PackageDexOptimizer mPackageDexOptimizer;
946    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
947    // is used by other apps).
948    private final DexManager mDexManager;
949
950    private AtomicInteger mNextMoveId = new AtomicInteger();
951    private final MoveCallbacks mMoveCallbacks;
952
953    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
954
955    // Cache of users who need badging.
956    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
957
958    /** Token for keys in mPendingVerification. */
959    private int mPendingVerificationToken = 0;
960
961    volatile boolean mSystemReady;
962    volatile boolean mSafeMode;
963    volatile boolean mHasSystemUidErrors;
964    private volatile boolean mEphemeralAppsDisabled;
965
966    ApplicationInfo mAndroidApplication;
967    final ActivityInfo mResolveActivity = new ActivityInfo();
968    final ResolveInfo mResolveInfo = new ResolveInfo();
969    ComponentName mResolveComponentName;
970    PackageParser.Package mPlatformPackage;
971    ComponentName mCustomResolverComponentName;
972
973    boolean mResolverReplaced = false;
974
975    private final @Nullable ComponentName mIntentFilterVerifierComponent;
976    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
977
978    private int mIntentFilterVerificationToken = 0;
979
980    /** The service connection to the ephemeral resolver */
981    final EphemeralResolverConnection mInstantAppResolverConnection;
982    /** Component used to show resolver settings for Instant Apps */
983    final ComponentName mInstantAppResolverSettingsComponent;
984
985    /** Activity used to install instant applications */
986    ActivityInfo mInstantAppInstallerActivity;
987    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
988
989    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
990            = new SparseArray<IntentFilterVerificationState>();
991
992    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
993
994    // List of packages names to keep cached, even if they are uninstalled for all users
995    private List<String> mKeepUninstalledPackages;
996
997    private UserManagerInternal mUserManagerInternal;
998
999    private DeviceIdleController.LocalService mDeviceIdleController;
1000
1001    private File mCacheDir;
1002
1003    private ArraySet<String> mPrivappPermissionsViolations;
1004
1005    private Future<?> mPrepareAppDataFuture;
1006
1007    private static class IFVerificationParams {
1008        PackageParser.Package pkg;
1009        boolean replacing;
1010        int userId;
1011        int verifierUid;
1012
1013        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1014                int _userId, int _verifierUid) {
1015            pkg = _pkg;
1016            replacing = _replacing;
1017            userId = _userId;
1018            replacing = _replacing;
1019            verifierUid = _verifierUid;
1020        }
1021    }
1022
1023    private interface IntentFilterVerifier<T extends IntentFilter> {
1024        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1025                                               T filter, String packageName);
1026        void startVerifications(int userId);
1027        void receiveVerificationResponse(int verificationId);
1028    }
1029
1030    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1031        private Context mContext;
1032        private ComponentName mIntentFilterVerifierComponent;
1033        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1034
1035        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1036            mContext = context;
1037            mIntentFilterVerifierComponent = verifierComponent;
1038        }
1039
1040        private String getDefaultScheme() {
1041            return IntentFilter.SCHEME_HTTPS;
1042        }
1043
1044        @Override
1045        public void startVerifications(int userId) {
1046            // Launch verifications requests
1047            int count = mCurrentIntentFilterVerifications.size();
1048            for (int n=0; n<count; n++) {
1049                int verificationId = mCurrentIntentFilterVerifications.get(n);
1050                final IntentFilterVerificationState ivs =
1051                        mIntentFilterVerificationStates.get(verificationId);
1052
1053                String packageName = ivs.getPackageName();
1054
1055                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1056                final int filterCount = filters.size();
1057                ArraySet<String> domainsSet = new ArraySet<>();
1058                for (int m=0; m<filterCount; m++) {
1059                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1060                    domainsSet.addAll(filter.getHostsList());
1061                }
1062                synchronized (mPackages) {
1063                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1064                            packageName, domainsSet) != null) {
1065                        scheduleWriteSettingsLocked();
1066                    }
1067                }
1068                sendVerificationRequest(verificationId, ivs);
1069            }
1070            mCurrentIntentFilterVerifications.clear();
1071        }
1072
1073        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1074            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1075            verificationIntent.putExtra(
1076                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1077                    verificationId);
1078            verificationIntent.putExtra(
1079                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1080                    getDefaultScheme());
1081            verificationIntent.putExtra(
1082                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1083                    ivs.getHostsString());
1084            verificationIntent.putExtra(
1085                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1086                    ivs.getPackageName());
1087            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1088            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1089
1090            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1091            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1092                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1093                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1094
1095            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1096            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1097                    "Sending IntentFilter verification broadcast");
1098        }
1099
1100        public void receiveVerificationResponse(int verificationId) {
1101            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1102
1103            final boolean verified = ivs.isVerified();
1104
1105            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1106            final int count = filters.size();
1107            if (DEBUG_DOMAIN_VERIFICATION) {
1108                Slog.i(TAG, "Received verification response " + verificationId
1109                        + " for " + count + " filters, verified=" + verified);
1110            }
1111            for (int n=0; n<count; n++) {
1112                PackageParser.ActivityIntentInfo filter = filters.get(n);
1113                filter.setVerified(verified);
1114
1115                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1116                        + " verified with result:" + verified + " and hosts:"
1117                        + ivs.getHostsString());
1118            }
1119
1120            mIntentFilterVerificationStates.remove(verificationId);
1121
1122            final String packageName = ivs.getPackageName();
1123            IntentFilterVerificationInfo ivi = null;
1124
1125            synchronized (mPackages) {
1126                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1127            }
1128            if (ivi == null) {
1129                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1130                        + verificationId + " packageName:" + packageName);
1131                return;
1132            }
1133            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1134                    "Updating IntentFilterVerificationInfo for package " + packageName
1135                            +" verificationId:" + verificationId);
1136
1137            synchronized (mPackages) {
1138                if (verified) {
1139                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1140                } else {
1141                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1142                }
1143                scheduleWriteSettingsLocked();
1144
1145                final int userId = ivs.getUserId();
1146                if (userId != UserHandle.USER_ALL) {
1147                    final int userStatus =
1148                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1149
1150                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1151                    boolean needUpdate = false;
1152
1153                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1154                    // already been set by the User thru the Disambiguation dialog
1155                    switch (userStatus) {
1156                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1157                            if (verified) {
1158                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1159                            } else {
1160                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1161                            }
1162                            needUpdate = true;
1163                            break;
1164
1165                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1166                            if (verified) {
1167                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1168                                needUpdate = true;
1169                            }
1170                            break;
1171
1172                        default:
1173                            // Nothing to do
1174                    }
1175
1176                    if (needUpdate) {
1177                        mSettings.updateIntentFilterVerificationStatusLPw(
1178                                packageName, updatedStatus, userId);
1179                        scheduleWritePackageRestrictionsLocked(userId);
1180                    }
1181                }
1182            }
1183        }
1184
1185        @Override
1186        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1187                    ActivityIntentInfo filter, String packageName) {
1188            if (!hasValidDomains(filter)) {
1189                return false;
1190            }
1191            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1192            if (ivs == null) {
1193                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1194                        packageName);
1195            }
1196            if (DEBUG_DOMAIN_VERIFICATION) {
1197                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1198            }
1199            ivs.addFilter(filter);
1200            return true;
1201        }
1202
1203        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1204                int userId, int verificationId, String packageName) {
1205            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1206                    verifierUid, userId, packageName);
1207            ivs.setPendingState();
1208            synchronized (mPackages) {
1209                mIntentFilterVerificationStates.append(verificationId, ivs);
1210                mCurrentIntentFilterVerifications.add(verificationId);
1211            }
1212            return ivs;
1213        }
1214    }
1215
1216    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1217        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1218                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1219                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1220    }
1221
1222    // Set of pending broadcasts for aggregating enable/disable of components.
1223    static class PendingPackageBroadcasts {
1224        // for each user id, a map of <package name -> components within that package>
1225        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1226
1227        public PendingPackageBroadcasts() {
1228            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1229        }
1230
1231        public ArrayList<String> get(int userId, String packageName) {
1232            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1233            return packages.get(packageName);
1234        }
1235
1236        public void put(int userId, String packageName, ArrayList<String> components) {
1237            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1238            packages.put(packageName, components);
1239        }
1240
1241        public void remove(int userId, String packageName) {
1242            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1243            if (packages != null) {
1244                packages.remove(packageName);
1245            }
1246        }
1247
1248        public void remove(int userId) {
1249            mUidMap.remove(userId);
1250        }
1251
1252        public int userIdCount() {
1253            return mUidMap.size();
1254        }
1255
1256        public int userIdAt(int n) {
1257            return mUidMap.keyAt(n);
1258        }
1259
1260        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1261            return mUidMap.get(userId);
1262        }
1263
1264        public int size() {
1265            // total number of pending broadcast entries across all userIds
1266            int num = 0;
1267            for (int i = 0; i< mUidMap.size(); i++) {
1268                num += mUidMap.valueAt(i).size();
1269            }
1270            return num;
1271        }
1272
1273        public void clear() {
1274            mUidMap.clear();
1275        }
1276
1277        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1278            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1279            if (map == null) {
1280                map = new ArrayMap<String, ArrayList<String>>();
1281                mUidMap.put(userId, map);
1282            }
1283            return map;
1284        }
1285    }
1286    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1287
1288    // Service Connection to remote media container service to copy
1289    // package uri's from external media onto secure containers
1290    // or internal storage.
1291    private IMediaContainerService mContainerService = null;
1292
1293    static final int SEND_PENDING_BROADCAST = 1;
1294    static final int MCS_BOUND = 3;
1295    static final int END_COPY = 4;
1296    static final int INIT_COPY = 5;
1297    static final int MCS_UNBIND = 6;
1298    static final int START_CLEANING_PACKAGE = 7;
1299    static final int FIND_INSTALL_LOC = 8;
1300    static final int POST_INSTALL = 9;
1301    static final int MCS_RECONNECT = 10;
1302    static final int MCS_GIVE_UP = 11;
1303    static final int UPDATED_MEDIA_STATUS = 12;
1304    static final int WRITE_SETTINGS = 13;
1305    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1306    static final int PACKAGE_VERIFIED = 15;
1307    static final int CHECK_PENDING_VERIFICATION = 16;
1308    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1309    static final int INTENT_FILTER_VERIFIED = 18;
1310    static final int WRITE_PACKAGE_LIST = 19;
1311    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1312
1313    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1314
1315    // Delay time in millisecs
1316    static final int BROADCAST_DELAY = 10 * 1000;
1317
1318    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1319            2 * 60 * 60 * 1000L; /* two hours */
1320
1321    static UserManagerService sUserManager;
1322
1323    // Stores a list of users whose package restrictions file needs to be updated
1324    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1325
1326    final private DefaultContainerConnection mDefContainerConn =
1327            new DefaultContainerConnection();
1328    class DefaultContainerConnection implements ServiceConnection {
1329        public void onServiceConnected(ComponentName name, IBinder service) {
1330            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1331            final IMediaContainerService imcs = IMediaContainerService.Stub
1332                    .asInterface(Binder.allowBlocking(service));
1333            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1334        }
1335
1336        public void onServiceDisconnected(ComponentName name) {
1337            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1338        }
1339    }
1340
1341    // Recordkeeping of restore-after-install operations that are currently in flight
1342    // between the Package Manager and the Backup Manager
1343    static class PostInstallData {
1344        public InstallArgs args;
1345        public PackageInstalledInfo res;
1346
1347        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1348            args = _a;
1349            res = _r;
1350        }
1351    }
1352
1353    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1354    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1355
1356    // XML tags for backup/restore of various bits of state
1357    private static final String TAG_PREFERRED_BACKUP = "pa";
1358    private static final String TAG_DEFAULT_APPS = "da";
1359    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1360
1361    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1362    private static final String TAG_ALL_GRANTS = "rt-grants";
1363    private static final String TAG_GRANT = "grant";
1364    private static final String ATTR_PACKAGE_NAME = "pkg";
1365
1366    private static final String TAG_PERMISSION = "perm";
1367    private static final String ATTR_PERMISSION_NAME = "name";
1368    private static final String ATTR_IS_GRANTED = "g";
1369    private static final String ATTR_USER_SET = "set";
1370    private static final String ATTR_USER_FIXED = "fixed";
1371    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1372
1373    // System/policy permission grants are not backed up
1374    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1375            FLAG_PERMISSION_POLICY_FIXED
1376            | FLAG_PERMISSION_SYSTEM_FIXED
1377            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1378
1379    // And we back up these user-adjusted states
1380    private static final int USER_RUNTIME_GRANT_MASK =
1381            FLAG_PERMISSION_USER_SET
1382            | FLAG_PERMISSION_USER_FIXED
1383            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1384
1385    final @Nullable String mRequiredVerifierPackage;
1386    final @NonNull String mRequiredInstallerPackage;
1387    final @NonNull String mRequiredUninstallerPackage;
1388    final @Nullable String mSetupWizardPackage;
1389    final @Nullable String mStorageManagerPackage;
1390    final @NonNull String mServicesSystemSharedLibraryPackageName;
1391    final @NonNull String mSharedSystemSharedLibraryPackageName;
1392
1393    final boolean mPermissionReviewRequired;
1394
1395    private final PackageUsage mPackageUsage = new PackageUsage();
1396    private final CompilerStats mCompilerStats = new CompilerStats();
1397
1398    class PackageHandler extends Handler {
1399        private boolean mBound = false;
1400        final ArrayList<HandlerParams> mPendingInstalls =
1401            new ArrayList<HandlerParams>();
1402
1403        private boolean connectToService() {
1404            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1405                    " DefaultContainerService");
1406            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1407            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1408            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1409                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1410                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1411                mBound = true;
1412                return true;
1413            }
1414            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1415            return false;
1416        }
1417
1418        private void disconnectService() {
1419            mContainerService = null;
1420            mBound = false;
1421            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1422            mContext.unbindService(mDefContainerConn);
1423            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1424        }
1425
1426        PackageHandler(Looper looper) {
1427            super(looper);
1428        }
1429
1430        public void handleMessage(Message msg) {
1431            try {
1432                doHandleMessage(msg);
1433            } finally {
1434                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1435            }
1436        }
1437
1438        void doHandleMessage(Message msg) {
1439            switch (msg.what) {
1440                case INIT_COPY: {
1441                    HandlerParams params = (HandlerParams) msg.obj;
1442                    int idx = mPendingInstalls.size();
1443                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1444                    // If a bind was already initiated we dont really
1445                    // need to do anything. The pending install
1446                    // will be processed later on.
1447                    if (!mBound) {
1448                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1449                                System.identityHashCode(mHandler));
1450                        // If this is the only one pending we might
1451                        // have to bind to the service again.
1452                        if (!connectToService()) {
1453                            Slog.e(TAG, "Failed to bind to media container service");
1454                            params.serviceError();
1455                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1456                                    System.identityHashCode(mHandler));
1457                            if (params.traceMethod != null) {
1458                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1459                                        params.traceCookie);
1460                            }
1461                            return;
1462                        } else {
1463                            // Once we bind to the service, the first
1464                            // pending request will be processed.
1465                            mPendingInstalls.add(idx, params);
1466                        }
1467                    } else {
1468                        mPendingInstalls.add(idx, params);
1469                        // Already bound to the service. Just make
1470                        // sure we trigger off processing the first request.
1471                        if (idx == 0) {
1472                            mHandler.sendEmptyMessage(MCS_BOUND);
1473                        }
1474                    }
1475                    break;
1476                }
1477                case MCS_BOUND: {
1478                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1479                    if (msg.obj != null) {
1480                        mContainerService = (IMediaContainerService) msg.obj;
1481                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1482                                System.identityHashCode(mHandler));
1483                    }
1484                    if (mContainerService == null) {
1485                        if (!mBound) {
1486                            // Something seriously wrong since we are not bound and we are not
1487                            // waiting for connection. Bail out.
1488                            Slog.e(TAG, "Cannot bind to media container service");
1489                            for (HandlerParams params : mPendingInstalls) {
1490                                // Indicate service bind error
1491                                params.serviceError();
1492                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1493                                        System.identityHashCode(params));
1494                                if (params.traceMethod != null) {
1495                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1496                                            params.traceMethod, params.traceCookie);
1497                                }
1498                                return;
1499                            }
1500                            mPendingInstalls.clear();
1501                        } else {
1502                            Slog.w(TAG, "Waiting to connect to media container service");
1503                        }
1504                    } else if (mPendingInstalls.size() > 0) {
1505                        HandlerParams params = mPendingInstalls.get(0);
1506                        if (params != null) {
1507                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1508                                    System.identityHashCode(params));
1509                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1510                            if (params.startCopy()) {
1511                                // We are done...  look for more work or to
1512                                // go idle.
1513                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1514                                        "Checking for more work or unbind...");
1515                                // Delete pending install
1516                                if (mPendingInstalls.size() > 0) {
1517                                    mPendingInstalls.remove(0);
1518                                }
1519                                if (mPendingInstalls.size() == 0) {
1520                                    if (mBound) {
1521                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1522                                                "Posting delayed MCS_UNBIND");
1523                                        removeMessages(MCS_UNBIND);
1524                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1525                                        // Unbind after a little delay, to avoid
1526                                        // continual thrashing.
1527                                        sendMessageDelayed(ubmsg, 10000);
1528                                    }
1529                                } else {
1530                                    // There are more pending requests in queue.
1531                                    // Just post MCS_BOUND message to trigger processing
1532                                    // of next pending install.
1533                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1534                                            "Posting MCS_BOUND for next work");
1535                                    mHandler.sendEmptyMessage(MCS_BOUND);
1536                                }
1537                            }
1538                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1539                        }
1540                    } else {
1541                        // Should never happen ideally.
1542                        Slog.w(TAG, "Empty queue");
1543                    }
1544                    break;
1545                }
1546                case MCS_RECONNECT: {
1547                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1548                    if (mPendingInstalls.size() > 0) {
1549                        if (mBound) {
1550                            disconnectService();
1551                        }
1552                        if (!connectToService()) {
1553                            Slog.e(TAG, "Failed to bind to media container service");
1554                            for (HandlerParams params : mPendingInstalls) {
1555                                // Indicate service bind error
1556                                params.serviceError();
1557                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1558                                        System.identityHashCode(params));
1559                            }
1560                            mPendingInstalls.clear();
1561                        }
1562                    }
1563                    break;
1564                }
1565                case MCS_UNBIND: {
1566                    // If there is no actual work left, then time to unbind.
1567                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1568
1569                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1570                        if (mBound) {
1571                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1572
1573                            disconnectService();
1574                        }
1575                    } else if (mPendingInstalls.size() > 0) {
1576                        // There are more pending requests in queue.
1577                        // Just post MCS_BOUND message to trigger processing
1578                        // of next pending install.
1579                        mHandler.sendEmptyMessage(MCS_BOUND);
1580                    }
1581
1582                    break;
1583                }
1584                case MCS_GIVE_UP: {
1585                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1586                    HandlerParams params = mPendingInstalls.remove(0);
1587                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1588                            System.identityHashCode(params));
1589                    break;
1590                }
1591                case SEND_PENDING_BROADCAST: {
1592                    String packages[];
1593                    ArrayList<String> components[];
1594                    int size = 0;
1595                    int uids[];
1596                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1597                    synchronized (mPackages) {
1598                        if (mPendingBroadcasts == null) {
1599                            return;
1600                        }
1601                        size = mPendingBroadcasts.size();
1602                        if (size <= 0) {
1603                            // Nothing to be done. Just return
1604                            return;
1605                        }
1606                        packages = new String[size];
1607                        components = new ArrayList[size];
1608                        uids = new int[size];
1609                        int i = 0;  // filling out the above arrays
1610
1611                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1612                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1613                            Iterator<Map.Entry<String, ArrayList<String>>> it
1614                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1615                                            .entrySet().iterator();
1616                            while (it.hasNext() && i < size) {
1617                                Map.Entry<String, ArrayList<String>> ent = it.next();
1618                                packages[i] = ent.getKey();
1619                                components[i] = ent.getValue();
1620                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1621                                uids[i] = (ps != null)
1622                                        ? UserHandle.getUid(packageUserId, ps.appId)
1623                                        : -1;
1624                                i++;
1625                            }
1626                        }
1627                        size = i;
1628                        mPendingBroadcasts.clear();
1629                    }
1630                    // Send broadcasts
1631                    for (int i = 0; i < size; i++) {
1632                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1633                    }
1634                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1635                    break;
1636                }
1637                case START_CLEANING_PACKAGE: {
1638                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1639                    final String packageName = (String)msg.obj;
1640                    final int userId = msg.arg1;
1641                    final boolean andCode = msg.arg2 != 0;
1642                    synchronized (mPackages) {
1643                        if (userId == UserHandle.USER_ALL) {
1644                            int[] users = sUserManager.getUserIds();
1645                            for (int user : users) {
1646                                mSettings.addPackageToCleanLPw(
1647                                        new PackageCleanItem(user, packageName, andCode));
1648                            }
1649                        } else {
1650                            mSettings.addPackageToCleanLPw(
1651                                    new PackageCleanItem(userId, packageName, andCode));
1652                        }
1653                    }
1654                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1655                    startCleaningPackages();
1656                } break;
1657                case POST_INSTALL: {
1658                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1659
1660                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1661                    final boolean didRestore = (msg.arg2 != 0);
1662                    mRunningInstalls.delete(msg.arg1);
1663
1664                    if (data != null) {
1665                        InstallArgs args = data.args;
1666                        PackageInstalledInfo parentRes = data.res;
1667
1668                        final boolean grantPermissions = (args.installFlags
1669                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1670                        final boolean killApp = (args.installFlags
1671                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1672                        final String[] grantedPermissions = args.installGrantPermissions;
1673
1674                        // Handle the parent package
1675                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1676                                grantedPermissions, didRestore, args.installerPackageName,
1677                                args.observer);
1678
1679                        // Handle the child packages
1680                        final int childCount = (parentRes.addedChildPackages != null)
1681                                ? parentRes.addedChildPackages.size() : 0;
1682                        for (int i = 0; i < childCount; i++) {
1683                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1684                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1685                                    grantedPermissions, false, args.installerPackageName,
1686                                    args.observer);
1687                        }
1688
1689                        // Log tracing if needed
1690                        if (args.traceMethod != null) {
1691                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1692                                    args.traceCookie);
1693                        }
1694                    } else {
1695                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1696                    }
1697
1698                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1699                } break;
1700                case UPDATED_MEDIA_STATUS: {
1701                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1702                    boolean reportStatus = msg.arg1 == 1;
1703                    boolean doGc = msg.arg2 == 1;
1704                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1705                    if (doGc) {
1706                        // Force a gc to clear up stale containers.
1707                        Runtime.getRuntime().gc();
1708                    }
1709                    if (msg.obj != null) {
1710                        @SuppressWarnings("unchecked")
1711                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1712                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1713                        // Unload containers
1714                        unloadAllContainers(args);
1715                    }
1716                    if (reportStatus) {
1717                        try {
1718                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1719                                    "Invoking StorageManagerService call back");
1720                            PackageHelper.getStorageManager().finishMediaUpdate();
1721                        } catch (RemoteException e) {
1722                            Log.e(TAG, "StorageManagerService not running?");
1723                        }
1724                    }
1725                } break;
1726                case WRITE_SETTINGS: {
1727                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1728                    synchronized (mPackages) {
1729                        removeMessages(WRITE_SETTINGS);
1730                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1731                        mSettings.writeLPr();
1732                        mDirtyUsers.clear();
1733                    }
1734                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1735                } break;
1736                case WRITE_PACKAGE_RESTRICTIONS: {
1737                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1738                    synchronized (mPackages) {
1739                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1740                        for (int userId : mDirtyUsers) {
1741                            mSettings.writePackageRestrictionsLPr(userId);
1742                        }
1743                        mDirtyUsers.clear();
1744                    }
1745                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1746                } break;
1747                case WRITE_PACKAGE_LIST: {
1748                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1749                    synchronized (mPackages) {
1750                        removeMessages(WRITE_PACKAGE_LIST);
1751                        mSettings.writePackageListLPr(msg.arg1);
1752                    }
1753                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1754                } break;
1755                case CHECK_PENDING_VERIFICATION: {
1756                    final int verificationId = msg.arg1;
1757                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1758
1759                    if ((state != null) && !state.timeoutExtended()) {
1760                        final InstallArgs args = state.getInstallArgs();
1761                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1762
1763                        Slog.i(TAG, "Verification timed out for " + originUri);
1764                        mPendingVerification.remove(verificationId);
1765
1766                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1767
1768                        final UserHandle user = args.getUser();
1769                        if (getDefaultVerificationResponse(user)
1770                                == PackageManager.VERIFICATION_ALLOW) {
1771                            Slog.i(TAG, "Continuing with installation of " + originUri);
1772                            state.setVerifierResponse(Binder.getCallingUid(),
1773                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1774                            broadcastPackageVerified(verificationId, originUri,
1775                                    PackageManager.VERIFICATION_ALLOW, user);
1776                            try {
1777                                ret = args.copyApk(mContainerService, true);
1778                            } catch (RemoteException e) {
1779                                Slog.e(TAG, "Could not contact the ContainerService");
1780                            }
1781                        } else {
1782                            broadcastPackageVerified(verificationId, originUri,
1783                                    PackageManager.VERIFICATION_REJECT, user);
1784                        }
1785
1786                        Trace.asyncTraceEnd(
1787                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1788
1789                        processPendingInstall(args, ret);
1790                        mHandler.sendEmptyMessage(MCS_UNBIND);
1791                    }
1792                    break;
1793                }
1794                case PACKAGE_VERIFIED: {
1795                    final int verificationId = msg.arg1;
1796
1797                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1798                    if (state == null) {
1799                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1800                        break;
1801                    }
1802
1803                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1804
1805                    state.setVerifierResponse(response.callerUid, response.code);
1806
1807                    if (state.isVerificationComplete()) {
1808                        mPendingVerification.remove(verificationId);
1809
1810                        final InstallArgs args = state.getInstallArgs();
1811                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1812
1813                        int ret;
1814                        if (state.isInstallAllowed()) {
1815                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1816                            broadcastPackageVerified(verificationId, originUri,
1817                                    response.code, state.getInstallArgs().getUser());
1818                            try {
1819                                ret = args.copyApk(mContainerService, true);
1820                            } catch (RemoteException e) {
1821                                Slog.e(TAG, "Could not contact the ContainerService");
1822                            }
1823                        } else {
1824                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1825                        }
1826
1827                        Trace.asyncTraceEnd(
1828                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1829
1830                        processPendingInstall(args, ret);
1831                        mHandler.sendEmptyMessage(MCS_UNBIND);
1832                    }
1833
1834                    break;
1835                }
1836                case START_INTENT_FILTER_VERIFICATIONS: {
1837                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1838                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1839                            params.replacing, params.pkg);
1840                    break;
1841                }
1842                case INTENT_FILTER_VERIFIED: {
1843                    final int verificationId = msg.arg1;
1844
1845                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1846                            verificationId);
1847                    if (state == null) {
1848                        Slog.w(TAG, "Invalid IntentFilter verification token "
1849                                + verificationId + " received");
1850                        break;
1851                    }
1852
1853                    final int userId = state.getUserId();
1854
1855                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1856                            "Processing IntentFilter verification with token:"
1857                            + verificationId + " and userId:" + userId);
1858
1859                    final IntentFilterVerificationResponse response =
1860                            (IntentFilterVerificationResponse) msg.obj;
1861
1862                    state.setVerifierResponse(response.callerUid, response.code);
1863
1864                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1865                            "IntentFilter verification with token:" + verificationId
1866                            + " and userId:" + userId
1867                            + " is settings verifier response with response code:"
1868                            + response.code);
1869
1870                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1871                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1872                                + response.getFailedDomainsString());
1873                    }
1874
1875                    if (state.isVerificationComplete()) {
1876                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1877                    } else {
1878                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1879                                "IntentFilter verification with token:" + verificationId
1880                                + " was not said to be complete");
1881                    }
1882
1883                    break;
1884                }
1885                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1886                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1887                            mInstantAppResolverConnection,
1888                            (InstantAppRequest) msg.obj,
1889                            mInstantAppInstallerActivity,
1890                            mHandler);
1891                }
1892            }
1893        }
1894    }
1895
1896    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1897            boolean killApp, String[] grantedPermissions,
1898            boolean launchedForRestore, String installerPackage,
1899            IPackageInstallObserver2 installObserver) {
1900        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1901            // Send the removed broadcasts
1902            if (res.removedInfo != null) {
1903                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1904            }
1905
1906            // Now that we successfully installed the package, grant runtime
1907            // permissions if requested before broadcasting the install. Also
1908            // for legacy apps in permission review mode we clear the permission
1909            // review flag which is used to emulate runtime permissions for
1910            // legacy apps.
1911            if (grantPermissions) {
1912                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1913            }
1914
1915            final boolean update = res.removedInfo != null
1916                    && res.removedInfo.removedPackage != null;
1917            final String origInstallerPackageName = res.removedInfo != null
1918                    ? res.removedInfo.installerPackageName : null;
1919
1920            // If this is the first time we have child packages for a disabled privileged
1921            // app that had no children, we grant requested runtime permissions to the new
1922            // children if the parent on the system image had them already granted.
1923            if (res.pkg.parentPackage != null) {
1924                synchronized (mPackages) {
1925                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1926                }
1927            }
1928
1929            synchronized (mPackages) {
1930                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1931            }
1932
1933            final String packageName = res.pkg.applicationInfo.packageName;
1934
1935            // Determine the set of users who are adding this package for
1936            // the first time vs. those who are seeing an update.
1937            int[] firstUsers = EMPTY_INT_ARRAY;
1938            int[] updateUsers = EMPTY_INT_ARRAY;
1939            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1940            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1941            for (int newUser : res.newUsers) {
1942                if (ps.getInstantApp(newUser)) {
1943                    continue;
1944                }
1945                if (allNewUsers) {
1946                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1947                    continue;
1948                }
1949                boolean isNew = true;
1950                for (int origUser : res.origUsers) {
1951                    if (origUser == newUser) {
1952                        isNew = false;
1953                        break;
1954                    }
1955                }
1956                if (isNew) {
1957                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1958                } else {
1959                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1960                }
1961            }
1962
1963            // Send installed broadcasts if the package is not a static shared lib.
1964            if (res.pkg.staticSharedLibName == null) {
1965                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1966
1967                // Send added for users that see the package for the first time
1968                // sendPackageAddedForNewUsers also deals with system apps
1969                int appId = UserHandle.getAppId(res.uid);
1970                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1971                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1972
1973                // Send added for users that don't see the package for the first time
1974                Bundle extras = new Bundle(1);
1975                extras.putInt(Intent.EXTRA_UID, res.uid);
1976                if (update) {
1977                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1978                }
1979                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1980                        extras, 0 /*flags*/,
1981                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1982                if (origInstallerPackageName != null) {
1983                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1984                            extras, 0 /*flags*/,
1985                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1986                }
1987
1988                // Send replaced for users that don't see the package for the first time
1989                if (update) {
1990                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1991                            packageName, extras, 0 /*flags*/,
1992                            null /*targetPackage*/, null /*finishedReceiver*/,
1993                            updateUsers);
1994                    if (origInstallerPackageName != null) {
1995                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1996                                extras, 0 /*flags*/,
1997                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1998                    }
1999                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2000                            null /*package*/, null /*extras*/, 0 /*flags*/,
2001                            packageName /*targetPackage*/,
2002                            null /*finishedReceiver*/, updateUsers);
2003                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2004                    // First-install and we did a restore, so we're responsible for the
2005                    // first-launch broadcast.
2006                    if (DEBUG_BACKUP) {
2007                        Slog.i(TAG, "Post-restore of " + packageName
2008                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2009                    }
2010                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2011                }
2012
2013                // Send broadcast package appeared if forward locked/external for all users
2014                // treat asec-hosted packages like removable media on upgrade
2015                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2016                    if (DEBUG_INSTALL) {
2017                        Slog.i(TAG, "upgrading pkg " + res.pkg
2018                                + " is ASEC-hosted -> AVAILABLE");
2019                    }
2020                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2021                    ArrayList<String> pkgList = new ArrayList<>(1);
2022                    pkgList.add(packageName);
2023                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2024                }
2025            }
2026
2027            // Work that needs to happen on first install within each user
2028            if (firstUsers != null && firstUsers.length > 0) {
2029                synchronized (mPackages) {
2030                    for (int userId : firstUsers) {
2031                        // If this app is a browser and it's newly-installed for some
2032                        // users, clear any default-browser state in those users. The
2033                        // app's nature doesn't depend on the user, so we can just check
2034                        // its browser nature in any user and generalize.
2035                        if (packageIsBrowser(packageName, userId)) {
2036                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2037                        }
2038
2039                        // We may also need to apply pending (restored) runtime
2040                        // permission grants within these users.
2041                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2042                    }
2043                }
2044            }
2045
2046            // Log current value of "unknown sources" setting
2047            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2048                    getUnknownSourcesSettings());
2049
2050            // Remove the replaced package's older resources safely now
2051            // We delete after a gc for applications  on sdcard.
2052            if (res.removedInfo != null && res.removedInfo.args != null) {
2053                Runtime.getRuntime().gc();
2054                synchronized (mInstallLock) {
2055                    res.removedInfo.args.doPostDeleteLI(true);
2056                }
2057            } else {
2058                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2059                // and not block here.
2060                VMRuntime.getRuntime().requestConcurrentGC();
2061            }
2062
2063            // Notify DexManager that the package was installed for new users.
2064            // The updated users should already be indexed and the package code paths
2065            // should not change.
2066            // Don't notify the manager for ephemeral apps as they are not expected to
2067            // survive long enough to benefit of background optimizations.
2068            for (int userId : firstUsers) {
2069                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2070                // There's a race currently where some install events may interleave with an uninstall.
2071                // This can lead to package info being null (b/36642664).
2072                if (info != null) {
2073                    mDexManager.notifyPackageInstalled(info, userId);
2074                }
2075            }
2076        }
2077
2078        // If someone is watching installs - notify them
2079        if (installObserver != null) {
2080            try {
2081                Bundle extras = extrasForInstallResult(res);
2082                installObserver.onPackageInstalled(res.name, res.returnCode,
2083                        res.returnMsg, extras);
2084            } catch (RemoteException e) {
2085                Slog.i(TAG, "Observer no longer exists.");
2086            }
2087        }
2088    }
2089
2090    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2091            PackageParser.Package pkg) {
2092        if (pkg.parentPackage == null) {
2093            return;
2094        }
2095        if (pkg.requestedPermissions == null) {
2096            return;
2097        }
2098        final PackageSetting disabledSysParentPs = mSettings
2099                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2100        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2101                || !disabledSysParentPs.isPrivileged()
2102                || (disabledSysParentPs.childPackageNames != null
2103                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2104            return;
2105        }
2106        final int[] allUserIds = sUserManager.getUserIds();
2107        final int permCount = pkg.requestedPermissions.size();
2108        for (int i = 0; i < permCount; i++) {
2109            String permission = pkg.requestedPermissions.get(i);
2110            BasePermission bp = mSettings.mPermissions.get(permission);
2111            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2112                continue;
2113            }
2114            for (int userId : allUserIds) {
2115                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2116                        permission, userId)) {
2117                    grantRuntimePermission(pkg.packageName, permission, userId);
2118                }
2119            }
2120        }
2121    }
2122
2123    private StorageEventListener mStorageListener = new StorageEventListener() {
2124        @Override
2125        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2126            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2127                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2128                    final String volumeUuid = vol.getFsUuid();
2129
2130                    // Clean up any users or apps that were removed or recreated
2131                    // while this volume was missing
2132                    sUserManager.reconcileUsers(volumeUuid);
2133                    reconcileApps(volumeUuid);
2134
2135                    // Clean up any install sessions that expired or were
2136                    // cancelled while this volume was missing
2137                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2138
2139                    loadPrivatePackages(vol);
2140
2141                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2142                    unloadPrivatePackages(vol);
2143                }
2144            }
2145
2146            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2147                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2148                    updateExternalMediaStatus(true, false);
2149                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2150                    updateExternalMediaStatus(false, false);
2151                }
2152            }
2153        }
2154
2155        @Override
2156        public void onVolumeForgotten(String fsUuid) {
2157            if (TextUtils.isEmpty(fsUuid)) {
2158                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2159                return;
2160            }
2161
2162            // Remove any apps installed on the forgotten volume
2163            synchronized (mPackages) {
2164                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2165                for (PackageSetting ps : packages) {
2166                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2167                    deletePackageVersioned(new VersionedPackage(ps.name,
2168                            PackageManager.VERSION_CODE_HIGHEST),
2169                            new LegacyPackageDeleteObserver(null).getBinder(),
2170                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2171                    // Try very hard to release any references to this package
2172                    // so we don't risk the system server being killed due to
2173                    // open FDs
2174                    AttributeCache.instance().removePackage(ps.name);
2175                }
2176
2177                mSettings.onVolumeForgotten(fsUuid);
2178                mSettings.writeLPr();
2179            }
2180        }
2181    };
2182
2183    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2184            String[] grantedPermissions) {
2185        for (int userId : userIds) {
2186            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2187        }
2188    }
2189
2190    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2191            String[] grantedPermissions) {
2192        PackageSetting ps = (PackageSetting) pkg.mExtras;
2193        if (ps == null) {
2194            return;
2195        }
2196
2197        PermissionsState permissionsState = ps.getPermissionsState();
2198
2199        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2200                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2201
2202        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2203                >= Build.VERSION_CODES.M;
2204
2205        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2206
2207        for (String permission : pkg.requestedPermissions) {
2208            final BasePermission bp;
2209            synchronized (mPackages) {
2210                bp = mSettings.mPermissions.get(permission);
2211            }
2212            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2213                    && (!instantApp || bp.isInstant())
2214                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2215                    && (grantedPermissions == null
2216                           || ArrayUtils.contains(grantedPermissions, permission))) {
2217                final int flags = permissionsState.getPermissionFlags(permission, userId);
2218                if (supportsRuntimePermissions) {
2219                    // Installer cannot change immutable permissions.
2220                    if ((flags & immutableFlags) == 0) {
2221                        grantRuntimePermission(pkg.packageName, permission, userId);
2222                    }
2223                } else if (mPermissionReviewRequired) {
2224                    // In permission review mode we clear the review flag when we
2225                    // are asked to install the app with all permissions granted.
2226                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2227                        updatePermissionFlags(permission, pkg.packageName,
2228                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2229                    }
2230                }
2231            }
2232        }
2233    }
2234
2235    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2236        Bundle extras = null;
2237        switch (res.returnCode) {
2238            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2239                extras = new Bundle();
2240                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2241                        res.origPermission);
2242                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2243                        res.origPackage);
2244                break;
2245            }
2246            case PackageManager.INSTALL_SUCCEEDED: {
2247                extras = new Bundle();
2248                extras.putBoolean(Intent.EXTRA_REPLACING,
2249                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2250                break;
2251            }
2252        }
2253        return extras;
2254    }
2255
2256    void scheduleWriteSettingsLocked() {
2257        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2258            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2259        }
2260    }
2261
2262    void scheduleWritePackageListLocked(int userId) {
2263        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2264            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2265            msg.arg1 = userId;
2266            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2267        }
2268    }
2269
2270    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2271        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2272        scheduleWritePackageRestrictionsLocked(userId);
2273    }
2274
2275    void scheduleWritePackageRestrictionsLocked(int userId) {
2276        final int[] userIds = (userId == UserHandle.USER_ALL)
2277                ? sUserManager.getUserIds() : new int[]{userId};
2278        for (int nextUserId : userIds) {
2279            if (!sUserManager.exists(nextUserId)) return;
2280            mDirtyUsers.add(nextUserId);
2281            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2282                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2283            }
2284        }
2285    }
2286
2287    public static PackageManagerService main(Context context, Installer installer,
2288            boolean factoryTest, boolean onlyCore) {
2289        // Self-check for initial settings.
2290        PackageManagerServiceCompilerMapping.checkProperties();
2291
2292        PackageManagerService m = new PackageManagerService(context, installer,
2293                factoryTest, onlyCore);
2294        m.enableSystemUserPackages();
2295        ServiceManager.addService("package", m);
2296        return m;
2297    }
2298
2299    private void enableSystemUserPackages() {
2300        if (!UserManager.isSplitSystemUser()) {
2301            return;
2302        }
2303        // For system user, enable apps based on the following conditions:
2304        // - app is whitelisted or belong to one of these groups:
2305        //   -- system app which has no launcher icons
2306        //   -- system app which has INTERACT_ACROSS_USERS permission
2307        //   -- system IME app
2308        // - app is not in the blacklist
2309        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2310        Set<String> enableApps = new ArraySet<>();
2311        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2312                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2313                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2314        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2315        enableApps.addAll(wlApps);
2316        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2317                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2318        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2319        enableApps.removeAll(blApps);
2320        Log.i(TAG, "Applications installed for system user: " + enableApps);
2321        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2322                UserHandle.SYSTEM);
2323        final int allAppsSize = allAps.size();
2324        synchronized (mPackages) {
2325            for (int i = 0; i < allAppsSize; i++) {
2326                String pName = allAps.get(i);
2327                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2328                // Should not happen, but we shouldn't be failing if it does
2329                if (pkgSetting == null) {
2330                    continue;
2331                }
2332                boolean install = enableApps.contains(pName);
2333                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2334                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2335                            + " for system user");
2336                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2337                }
2338            }
2339            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2340        }
2341    }
2342
2343    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2344        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2345                Context.DISPLAY_SERVICE);
2346        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2347    }
2348
2349    /**
2350     * Requests that files preopted on a secondary system partition be copied to the data partition
2351     * if possible.  Note that the actual copying of the files is accomplished by init for security
2352     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2353     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2354     */
2355    private static void requestCopyPreoptedFiles() {
2356        final int WAIT_TIME_MS = 100;
2357        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2358        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2359            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2360            // We will wait for up to 100 seconds.
2361            final long timeStart = SystemClock.uptimeMillis();
2362            final long timeEnd = timeStart + 100 * 1000;
2363            long timeNow = timeStart;
2364            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2365                try {
2366                    Thread.sleep(WAIT_TIME_MS);
2367                } catch (InterruptedException e) {
2368                    // Do nothing
2369                }
2370                timeNow = SystemClock.uptimeMillis();
2371                if (timeNow > timeEnd) {
2372                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2373                    Slog.wtf(TAG, "cppreopt did not finish!");
2374                    break;
2375                }
2376            }
2377
2378            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2379        }
2380    }
2381
2382    public PackageManagerService(Context context, Installer installer,
2383            boolean factoryTest, boolean onlyCore) {
2384        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2385        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2386        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2387                SystemClock.uptimeMillis());
2388
2389        if (mSdkVersion <= 0) {
2390            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2391        }
2392
2393        mContext = context;
2394
2395        mPermissionReviewRequired = context.getResources().getBoolean(
2396                R.bool.config_permissionReviewRequired);
2397
2398        mFactoryTest = factoryTest;
2399        mOnlyCore = onlyCore;
2400        mMetrics = new DisplayMetrics();
2401        mSettings = new Settings(mPackages);
2402        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2407                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2408        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2409                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2410        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2411                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2412        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2413                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2414
2415        String separateProcesses = SystemProperties.get("debug.separate_processes");
2416        if (separateProcesses != null && separateProcesses.length() > 0) {
2417            if ("*".equals(separateProcesses)) {
2418                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2419                mSeparateProcesses = null;
2420                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2421            } else {
2422                mDefParseFlags = 0;
2423                mSeparateProcesses = separateProcesses.split(",");
2424                Slog.w(TAG, "Running with debug.separate_processes: "
2425                        + separateProcesses);
2426            }
2427        } else {
2428            mDefParseFlags = 0;
2429            mSeparateProcesses = null;
2430        }
2431
2432        mInstaller = installer;
2433        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2434                "*dexopt*");
2435        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2436        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2437
2438        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2439                FgThread.get().getLooper());
2440
2441        getDefaultDisplayMetrics(context, mMetrics);
2442
2443        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2444        SystemConfig systemConfig = SystemConfig.getInstance();
2445        mGlobalGids = systemConfig.getGlobalGids();
2446        mSystemPermissions = systemConfig.getSystemPermissions();
2447        mAvailableFeatures = systemConfig.getAvailableFeatures();
2448        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2449
2450        mProtectedPackages = new ProtectedPackages(mContext);
2451
2452        synchronized (mInstallLock) {
2453        // writer
2454        synchronized (mPackages) {
2455            mHandlerThread = new ServiceThread(TAG,
2456                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2457            mHandlerThread.start();
2458            mHandler = new PackageHandler(mHandlerThread.getLooper());
2459            mProcessLoggingHandler = new ProcessLoggingHandler();
2460            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2461
2462            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2463            mInstantAppRegistry = new InstantAppRegistry(this);
2464
2465            File dataDir = Environment.getDataDirectory();
2466            mAppInstallDir = new File(dataDir, "app");
2467            mAppLib32InstallDir = new File(dataDir, "app-lib");
2468            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2469            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2470            sUserManager = new UserManagerService(context, this,
2471                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2472
2473            // Propagate permission configuration in to package manager.
2474            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2475                    = systemConfig.getPermissions();
2476            for (int i=0; i<permConfig.size(); i++) {
2477                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2478                BasePermission bp = mSettings.mPermissions.get(perm.name);
2479                if (bp == null) {
2480                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2481                    mSettings.mPermissions.put(perm.name, bp);
2482                }
2483                if (perm.gids != null) {
2484                    bp.setGids(perm.gids, perm.perUser);
2485                }
2486            }
2487
2488            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2489            final int builtInLibCount = libConfig.size();
2490            for (int i = 0; i < builtInLibCount; i++) {
2491                String name = libConfig.keyAt(i);
2492                String path = libConfig.valueAt(i);
2493                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2494                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2495            }
2496
2497            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2498
2499            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2500            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2501            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2502
2503            // Clean up orphaned packages for which the code path doesn't exist
2504            // and they are an update to a system app - caused by bug/32321269
2505            final int packageSettingCount = mSettings.mPackages.size();
2506            for (int i = packageSettingCount - 1; i >= 0; i--) {
2507                PackageSetting ps = mSettings.mPackages.valueAt(i);
2508                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2509                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2510                    mSettings.mPackages.removeAt(i);
2511                    mSettings.enableSystemPackageLPw(ps.name);
2512                }
2513            }
2514
2515            if (mFirstBoot) {
2516                requestCopyPreoptedFiles();
2517            }
2518
2519            String customResolverActivity = Resources.getSystem().getString(
2520                    R.string.config_customResolverActivity);
2521            if (TextUtils.isEmpty(customResolverActivity)) {
2522                customResolverActivity = null;
2523            } else {
2524                mCustomResolverComponentName = ComponentName.unflattenFromString(
2525                        customResolverActivity);
2526            }
2527
2528            long startTime = SystemClock.uptimeMillis();
2529
2530            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2531                    startTime);
2532
2533            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2534            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2535
2536            if (bootClassPath == null) {
2537                Slog.w(TAG, "No BOOTCLASSPATH found!");
2538            }
2539
2540            if (systemServerClassPath == null) {
2541                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2542            }
2543
2544            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2545
2546            final VersionInfo ver = mSettings.getInternalVersion();
2547            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2548            if (mIsUpgrade) {
2549                logCriticalInfo(Log.INFO,
2550                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2551            }
2552
2553            // when upgrading from pre-M, promote system app permissions from install to runtime
2554            mPromoteSystemApps =
2555                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2556
2557            // When upgrading from pre-N, we need to handle package extraction like first boot,
2558            // as there is no profiling data available.
2559            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2560
2561            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2562
2563            // save off the names of pre-existing system packages prior to scanning; we don't
2564            // want to automatically grant runtime permissions for new system apps
2565            if (mPromoteSystemApps) {
2566                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2567                while (pkgSettingIter.hasNext()) {
2568                    PackageSetting ps = pkgSettingIter.next();
2569                    if (isSystemApp(ps)) {
2570                        mExistingSystemPackages.add(ps.name);
2571                    }
2572                }
2573            }
2574
2575            mCacheDir = preparePackageParserCache(mIsUpgrade);
2576
2577            // Set flag to monitor and not change apk file paths when
2578            // scanning install directories.
2579            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2580
2581            if (mIsUpgrade || mFirstBoot) {
2582                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2583            }
2584
2585            // Collect vendor overlay packages. (Do this before scanning any apps.)
2586            // For security and version matching reason, only consider
2587            // overlay packages if they reside in the right directory.
2588            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2589                    | PackageParser.PARSE_IS_SYSTEM
2590                    | PackageParser.PARSE_IS_SYSTEM_DIR
2591                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2592
2593            mParallelPackageParserCallback.findStaticOverlayPackages();
2594
2595            // Find base frameworks (resource packages without code).
2596            scanDirTracedLI(frameworkDir, mDefParseFlags
2597                    | PackageParser.PARSE_IS_SYSTEM
2598                    | PackageParser.PARSE_IS_SYSTEM_DIR
2599                    | PackageParser.PARSE_IS_PRIVILEGED,
2600                    scanFlags | SCAN_NO_DEX, 0);
2601
2602            // Collected privileged system packages.
2603            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2604            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2605                    | PackageParser.PARSE_IS_SYSTEM
2606                    | PackageParser.PARSE_IS_SYSTEM_DIR
2607                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2608
2609            // Collect ordinary system packages.
2610            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2611            scanDirTracedLI(systemAppDir, mDefParseFlags
2612                    | PackageParser.PARSE_IS_SYSTEM
2613                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2614
2615            // Collect all vendor packages.
2616            File vendorAppDir = new File("/vendor/app");
2617            try {
2618                vendorAppDir = vendorAppDir.getCanonicalFile();
2619            } catch (IOException e) {
2620                // failed to look up canonical path, continue with original one
2621            }
2622            scanDirTracedLI(vendorAppDir, mDefParseFlags
2623                    | PackageParser.PARSE_IS_SYSTEM
2624                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2625
2626            // Collect all OEM packages.
2627            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2628            scanDirTracedLI(oemAppDir, mDefParseFlags
2629                    | PackageParser.PARSE_IS_SYSTEM
2630                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2631
2632            // Prune any system packages that no longer exist.
2633            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2634            if (!mOnlyCore) {
2635                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2636                while (psit.hasNext()) {
2637                    PackageSetting ps = psit.next();
2638
2639                    /*
2640                     * If this is not a system app, it can't be a
2641                     * disable system app.
2642                     */
2643                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2644                        continue;
2645                    }
2646
2647                    /*
2648                     * If the package is scanned, it's not erased.
2649                     */
2650                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2651                    if (scannedPkg != null) {
2652                        /*
2653                         * If the system app is both scanned and in the
2654                         * disabled packages list, then it must have been
2655                         * added via OTA. Remove it from the currently
2656                         * scanned package so the previously user-installed
2657                         * application can be scanned.
2658                         */
2659                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2660                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2661                                    + ps.name + "; removing system app.  Last known codePath="
2662                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2663                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2664                                    + scannedPkg.mVersionCode);
2665                            removePackageLI(scannedPkg, true);
2666                            mExpectingBetter.put(ps.name, ps.codePath);
2667                        }
2668
2669                        continue;
2670                    }
2671
2672                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2673                        psit.remove();
2674                        logCriticalInfo(Log.WARN, "System package " + ps.name
2675                                + " no longer exists; it's data will be wiped");
2676                        // Actual deletion of code and data will be handled by later
2677                        // reconciliation step
2678                    } else {
2679                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2680                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2681                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2682                        }
2683                    }
2684                }
2685            }
2686
2687            //look for any incomplete package installations
2688            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2689            for (int i = 0; i < deletePkgsList.size(); i++) {
2690                // Actual deletion of code and data will be handled by later
2691                // reconciliation step
2692                final String packageName = deletePkgsList.get(i).name;
2693                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2694                synchronized (mPackages) {
2695                    mSettings.removePackageLPw(packageName);
2696                }
2697            }
2698
2699            //delete tmp files
2700            deleteTempPackageFiles();
2701
2702            // Remove any shared userIDs that have no associated packages
2703            mSettings.pruneSharedUsersLPw();
2704            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2705            final int systemPackagesCount = mPackages.size();
2706            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2707                    + " ms, packageCount: " + systemPackagesCount
2708                    + " ms, timePerPackage: "
2709                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount));
2710            if (mIsUpgrade && systemPackagesCount > 0) {
2711                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2712                        ((int) systemScanTime) / systemPackagesCount);
2713            }
2714            if (!mOnlyCore) {
2715                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2716                        SystemClock.uptimeMillis());
2717                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2718
2719                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2720                        | PackageParser.PARSE_FORWARD_LOCK,
2721                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2722
2723                /**
2724                 * Remove disable package settings for any updated system
2725                 * apps that were removed via an OTA. If they're not a
2726                 * previously-updated app, remove them completely.
2727                 * Otherwise, just revoke their system-level permissions.
2728                 */
2729                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2730                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2731                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2732
2733                    String msg;
2734                    if (deletedPkg == null) {
2735                        msg = "Updated system package " + deletedAppName
2736                                + " no longer exists; it's data will be wiped";
2737                        // Actual deletion of code and data will be handled by later
2738                        // reconciliation step
2739                    } else {
2740                        msg = "Updated system app + " + deletedAppName
2741                                + " no longer present; removing system privileges for "
2742                                + deletedAppName;
2743
2744                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2745
2746                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2747                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2748                    }
2749                    logCriticalInfo(Log.WARN, msg);
2750                }
2751
2752                /**
2753                 * Make sure all system apps that we expected to appear on
2754                 * the userdata partition actually showed up. If they never
2755                 * appeared, crawl back and revive the system version.
2756                 */
2757                for (int i = 0; i < mExpectingBetter.size(); i++) {
2758                    final String packageName = mExpectingBetter.keyAt(i);
2759                    if (!mPackages.containsKey(packageName)) {
2760                        final File scanFile = mExpectingBetter.valueAt(i);
2761
2762                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2763                                + " but never showed up; reverting to system");
2764
2765                        int reparseFlags = mDefParseFlags;
2766                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2767                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2768                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2769                                    | PackageParser.PARSE_IS_PRIVILEGED;
2770                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2771                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2772                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2773                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2774                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2775                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2776                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2777                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2778                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2779                        } else {
2780                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2781                            continue;
2782                        }
2783
2784                        mSettings.enableSystemPackageLPw(packageName);
2785
2786                        try {
2787                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2788                        } catch (PackageManagerException e) {
2789                            Slog.e(TAG, "Failed to parse original system package: "
2790                                    + e.getMessage());
2791                        }
2792                    }
2793                }
2794                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2795                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2796                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2797                        + " ms, packageCount: " + dataPackagesCount
2798                        + " ms, timePerPackage: "
2799                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount));
2800                if (mIsUpgrade && dataPackagesCount > 0) {
2801                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2802                            ((int) dataScanTime) / dataPackagesCount);
2803                }
2804            }
2805            mExpectingBetter.clear();
2806
2807            // Resolve the storage manager.
2808            mStorageManagerPackage = getStorageManagerPackageName();
2809
2810            // Resolve protected action filters. Only the setup wizard is allowed to
2811            // have a high priority filter for these actions.
2812            mSetupWizardPackage = getSetupWizardPackageName();
2813            if (mProtectedFilters.size() > 0) {
2814                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2815                    Slog.i(TAG, "No setup wizard;"
2816                        + " All protected intents capped to priority 0");
2817                }
2818                for (ActivityIntentInfo filter : mProtectedFilters) {
2819                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2820                        if (DEBUG_FILTERS) {
2821                            Slog.i(TAG, "Found setup wizard;"
2822                                + " allow priority " + filter.getPriority() + ";"
2823                                + " package: " + filter.activity.info.packageName
2824                                + " activity: " + filter.activity.className
2825                                + " priority: " + filter.getPriority());
2826                        }
2827                        // skip setup wizard; allow it to keep the high priority filter
2828                        continue;
2829                    }
2830                    if (DEBUG_FILTERS) {
2831                        Slog.i(TAG, "Protected action; cap priority to 0;"
2832                                + " package: " + filter.activity.info.packageName
2833                                + " activity: " + filter.activity.className
2834                                + " origPrio: " + filter.getPriority());
2835                    }
2836                    filter.setPriority(0);
2837                }
2838            }
2839            mDeferProtectedFilters = false;
2840            mProtectedFilters.clear();
2841
2842            // Now that we know all of the shared libraries, update all clients to have
2843            // the correct library paths.
2844            updateAllSharedLibrariesLPw(null);
2845
2846            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2847                // NOTE: We ignore potential failures here during a system scan (like
2848                // the rest of the commands above) because there's precious little we
2849                // can do about it. A settings error is reported, though.
2850                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2851            }
2852
2853            // Now that we know all the packages we are keeping,
2854            // read and update their last usage times.
2855            mPackageUsage.read(mPackages);
2856            mCompilerStats.read();
2857
2858            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2859                    SystemClock.uptimeMillis());
2860            Slog.i(TAG, "Time to scan packages: "
2861                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2862                    + " seconds");
2863
2864            // If the platform SDK has changed since the last time we booted,
2865            // we need to re-grant app permission to catch any new ones that
2866            // appear.  This is really a hack, and means that apps can in some
2867            // cases get permissions that the user didn't initially explicitly
2868            // allow...  it would be nice to have some better way to handle
2869            // this situation.
2870            int updateFlags = UPDATE_PERMISSIONS_ALL;
2871            if (ver.sdkVersion != mSdkVersion) {
2872                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2873                        + mSdkVersion + "; regranting permissions for internal storage");
2874                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2875            }
2876            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2877            ver.sdkVersion = mSdkVersion;
2878
2879            // If this is the first boot or an update from pre-M, and it is a normal
2880            // boot, then we need to initialize the default preferred apps across
2881            // all defined users.
2882            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2883                for (UserInfo user : sUserManager.getUsers(true)) {
2884                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2885                    applyFactoryDefaultBrowserLPw(user.id);
2886                    primeDomainVerificationsLPw(user.id);
2887                }
2888            }
2889
2890            // Prepare storage for system user really early during boot,
2891            // since core system apps like SettingsProvider and SystemUI
2892            // can't wait for user to start
2893            final int storageFlags;
2894            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2895                storageFlags = StorageManager.FLAG_STORAGE_DE;
2896            } else {
2897                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2898            }
2899            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2900                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2901                    true /* onlyCoreApps */);
2902            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2903                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2904                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2905                traceLog.traceBegin("AppDataFixup");
2906                try {
2907                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2908                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2909                } catch (InstallerException e) {
2910                    Slog.w(TAG, "Trouble fixing GIDs", e);
2911                }
2912                traceLog.traceEnd();
2913
2914                traceLog.traceBegin("AppDataPrepare");
2915                if (deferPackages == null || deferPackages.isEmpty()) {
2916                    return;
2917                }
2918                int count = 0;
2919                for (String pkgName : deferPackages) {
2920                    PackageParser.Package pkg = null;
2921                    synchronized (mPackages) {
2922                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2923                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2924                            pkg = ps.pkg;
2925                        }
2926                    }
2927                    if (pkg != null) {
2928                        synchronized (mInstallLock) {
2929                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2930                                    true /* maybeMigrateAppData */);
2931                        }
2932                        count++;
2933                    }
2934                }
2935                traceLog.traceEnd();
2936                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2937            }, "prepareAppData");
2938
2939            // If this is first boot after an OTA, and a normal boot, then
2940            // we need to clear code cache directories.
2941            // Note that we do *not* clear the application profiles. These remain valid
2942            // across OTAs and are used to drive profile verification (post OTA) and
2943            // profile compilation (without waiting to collect a fresh set of profiles).
2944            if (mIsUpgrade && !onlyCore) {
2945                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2946                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2947                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2948                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2949                        // No apps are running this early, so no need to freeze
2950                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2951                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2952                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2953                    }
2954                }
2955                ver.fingerprint = Build.FINGERPRINT;
2956            }
2957
2958            checkDefaultBrowser();
2959
2960            // clear only after permissions and other defaults have been updated
2961            mExistingSystemPackages.clear();
2962            mPromoteSystemApps = false;
2963
2964            // All the changes are done during package scanning.
2965            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2966
2967            // can downgrade to reader
2968            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2969            mSettings.writeLPr();
2970            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2971            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2972                    SystemClock.uptimeMillis());
2973
2974            if (!mOnlyCore) {
2975                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2976                mRequiredInstallerPackage = getRequiredInstallerLPr();
2977                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2978                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2979                if (mIntentFilterVerifierComponent != null) {
2980                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2981                            mIntentFilterVerifierComponent);
2982                } else {
2983                    mIntentFilterVerifier = null;
2984                }
2985                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2986                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2987                        SharedLibraryInfo.VERSION_UNDEFINED);
2988                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2989                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2990                        SharedLibraryInfo.VERSION_UNDEFINED);
2991            } else {
2992                mRequiredVerifierPackage = null;
2993                mRequiredInstallerPackage = null;
2994                mRequiredUninstallerPackage = null;
2995                mIntentFilterVerifierComponent = null;
2996                mIntentFilterVerifier = null;
2997                mServicesSystemSharedLibraryPackageName = null;
2998                mSharedSystemSharedLibraryPackageName = null;
2999            }
3000
3001            mInstallerService = new PackageInstallerService(context, this);
3002            final Pair<ComponentName, String> instantAppResolverComponent =
3003                    getInstantAppResolverLPr();
3004            if (instantAppResolverComponent != null) {
3005                if (DEBUG_EPHEMERAL) {
3006                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3007                }
3008                mInstantAppResolverConnection = new EphemeralResolverConnection(
3009                        mContext, instantAppResolverComponent.first,
3010                        instantAppResolverComponent.second);
3011                mInstantAppResolverSettingsComponent =
3012                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3013            } else {
3014                mInstantAppResolverConnection = null;
3015                mInstantAppResolverSettingsComponent = null;
3016            }
3017            updateInstantAppInstallerLocked(null);
3018
3019            // Read and update the usage of dex files.
3020            // Do this at the end of PM init so that all the packages have their
3021            // data directory reconciled.
3022            // At this point we know the code paths of the packages, so we can validate
3023            // the disk file and build the internal cache.
3024            // The usage file is expected to be small so loading and verifying it
3025            // should take a fairly small time compare to the other activities (e.g. package
3026            // scanning).
3027            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3028            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3029            for (int userId : currentUserIds) {
3030                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3031            }
3032            mDexManager.load(userPackages);
3033            if (mIsUpgrade) {
3034                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3035                        (int) (SystemClock.uptimeMillis() - startTime));
3036            }
3037        } // synchronized (mPackages)
3038        } // synchronized (mInstallLock)
3039
3040        // Now after opening every single application zip, make sure they
3041        // are all flushed.  Not really needed, but keeps things nice and
3042        // tidy.
3043        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3044        Runtime.getRuntime().gc();
3045        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3046
3047        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3048        FallbackCategoryProvider.loadFallbacks();
3049        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3050
3051        // The initial scanning above does many calls into installd while
3052        // holding the mPackages lock, but we're mostly interested in yelling
3053        // once we have a booted system.
3054        mInstaller.setWarnIfHeld(mPackages);
3055
3056        // Expose private service for system components to use.
3057        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3058        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3059    }
3060
3061    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3062        // we're only interested in updating the installer appliction when 1) it's not
3063        // already set or 2) the modified package is the installer
3064        if (mInstantAppInstallerActivity != null
3065                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3066                        .equals(modifiedPackage)) {
3067            return;
3068        }
3069        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3070    }
3071
3072    private static File preparePackageParserCache(boolean isUpgrade) {
3073        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3074            return null;
3075        }
3076
3077        // Disable package parsing on eng builds to allow for faster incremental development.
3078        if (Build.IS_ENG) {
3079            return null;
3080        }
3081
3082        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3083            Slog.i(TAG, "Disabling package parser cache due to system property.");
3084            return null;
3085        }
3086
3087        // The base directory for the package parser cache lives under /data/system/.
3088        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3089                "package_cache");
3090        if (cacheBaseDir == null) {
3091            return null;
3092        }
3093
3094        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3095        // This also serves to "GC" unused entries when the package cache version changes (which
3096        // can only happen during upgrades).
3097        if (isUpgrade) {
3098            FileUtils.deleteContents(cacheBaseDir);
3099        }
3100
3101
3102        // Return the versioned package cache directory. This is something like
3103        // "/data/system/package_cache/1"
3104        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3105
3106        // The following is a workaround to aid development on non-numbered userdebug
3107        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3108        // the system partition is newer.
3109        //
3110        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3111        // that starts with "eng." to signify that this is an engineering build and not
3112        // destined for release.
3113        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3114            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3115
3116            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3117            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3118            // in general and should not be used for production changes. In this specific case,
3119            // we know that they will work.
3120            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3121            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3122                FileUtils.deleteContents(cacheBaseDir);
3123                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3124            }
3125        }
3126
3127        return cacheDir;
3128    }
3129
3130    @Override
3131    public boolean isFirstBoot() {
3132        // allow instant applications
3133        return mFirstBoot;
3134    }
3135
3136    @Override
3137    public boolean isOnlyCoreApps() {
3138        // allow instant applications
3139        return mOnlyCore;
3140    }
3141
3142    @Override
3143    public boolean isUpgrade() {
3144        // allow instant applications
3145        return mIsUpgrade;
3146    }
3147
3148    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3149        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3150
3151        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3152                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3153                UserHandle.USER_SYSTEM);
3154        if (matches.size() == 1) {
3155            return matches.get(0).getComponentInfo().packageName;
3156        } else if (matches.size() == 0) {
3157            Log.e(TAG, "There should probably be a verifier, but, none were found");
3158            return null;
3159        }
3160        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3161    }
3162
3163    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3164        synchronized (mPackages) {
3165            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3166            if (libraryEntry == null) {
3167                throw new IllegalStateException("Missing required shared library:" + name);
3168            }
3169            return libraryEntry.apk;
3170        }
3171    }
3172
3173    private @NonNull String getRequiredInstallerLPr() {
3174        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3175        intent.addCategory(Intent.CATEGORY_DEFAULT);
3176        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3177
3178        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3179                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3180                UserHandle.USER_SYSTEM);
3181        if (matches.size() == 1) {
3182            ResolveInfo resolveInfo = matches.get(0);
3183            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3184                throw new RuntimeException("The installer must be a privileged app");
3185            }
3186            return matches.get(0).getComponentInfo().packageName;
3187        } else {
3188            throw new RuntimeException("There must be exactly one installer; found " + matches);
3189        }
3190    }
3191
3192    private @NonNull String getRequiredUninstallerLPr() {
3193        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3194        intent.addCategory(Intent.CATEGORY_DEFAULT);
3195        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3196
3197        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3198                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3199                UserHandle.USER_SYSTEM);
3200        if (resolveInfo == null ||
3201                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3202            throw new RuntimeException("There must be exactly one uninstaller; found "
3203                    + resolveInfo);
3204        }
3205        return resolveInfo.getComponentInfo().packageName;
3206    }
3207
3208    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3209        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3210
3211        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3212                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3213                UserHandle.USER_SYSTEM);
3214        ResolveInfo best = null;
3215        final int N = matches.size();
3216        for (int i = 0; i < N; i++) {
3217            final ResolveInfo cur = matches.get(i);
3218            final String packageName = cur.getComponentInfo().packageName;
3219            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3220                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3221                continue;
3222            }
3223
3224            if (best == null || cur.priority > best.priority) {
3225                best = cur;
3226            }
3227        }
3228
3229        if (best != null) {
3230            return best.getComponentInfo().getComponentName();
3231        }
3232        Slog.w(TAG, "Intent filter verifier not found");
3233        return null;
3234    }
3235
3236    @Override
3237    public @Nullable ComponentName getInstantAppResolverComponent() {
3238        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3239            return null;
3240        }
3241        synchronized (mPackages) {
3242            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3243            if (instantAppResolver == null) {
3244                return null;
3245            }
3246            return instantAppResolver.first;
3247        }
3248    }
3249
3250    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3251        final String[] packageArray =
3252                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3253        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3254            if (DEBUG_EPHEMERAL) {
3255                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3256            }
3257            return null;
3258        }
3259
3260        final int callingUid = Binder.getCallingUid();
3261        final int resolveFlags =
3262                MATCH_DIRECT_BOOT_AWARE
3263                | MATCH_DIRECT_BOOT_UNAWARE
3264                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3265        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3266        final Intent resolverIntent = new Intent(actionName);
3267        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3268                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3269        // temporarily look for the old action
3270        if (resolvers.size() == 0) {
3271            if (DEBUG_EPHEMERAL) {
3272                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3273            }
3274            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3275            resolverIntent.setAction(actionName);
3276            resolvers = queryIntentServicesInternal(resolverIntent, null,
3277                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3278        }
3279        final int N = resolvers.size();
3280        if (N == 0) {
3281            if (DEBUG_EPHEMERAL) {
3282                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3283            }
3284            return null;
3285        }
3286
3287        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3288        for (int i = 0; i < N; i++) {
3289            final ResolveInfo info = resolvers.get(i);
3290
3291            if (info.serviceInfo == null) {
3292                continue;
3293            }
3294
3295            final String packageName = info.serviceInfo.packageName;
3296            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3297                if (DEBUG_EPHEMERAL) {
3298                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3299                            + " pkg: " + packageName + ", info:" + info);
3300                }
3301                continue;
3302            }
3303
3304            if (DEBUG_EPHEMERAL) {
3305                Slog.v(TAG, "Ephemeral resolver found;"
3306                        + " pkg: " + packageName + ", info:" + info);
3307            }
3308            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3309        }
3310        if (DEBUG_EPHEMERAL) {
3311            Slog.v(TAG, "Ephemeral resolver NOT found");
3312        }
3313        return null;
3314    }
3315
3316    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3317        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3318        intent.addCategory(Intent.CATEGORY_DEFAULT);
3319        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3320
3321        final int resolveFlags =
3322                MATCH_DIRECT_BOOT_AWARE
3323                | MATCH_DIRECT_BOOT_UNAWARE
3324                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3325        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3326                resolveFlags, UserHandle.USER_SYSTEM);
3327        // temporarily look for the old action
3328        if (matches.isEmpty()) {
3329            if (DEBUG_EPHEMERAL) {
3330                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3331            }
3332            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3333            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3334                    resolveFlags, UserHandle.USER_SYSTEM);
3335        }
3336        Iterator<ResolveInfo> iter = matches.iterator();
3337        while (iter.hasNext()) {
3338            final ResolveInfo rInfo = iter.next();
3339            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3340            if (ps != null) {
3341                final PermissionsState permissionsState = ps.getPermissionsState();
3342                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3343                    continue;
3344                }
3345            }
3346            iter.remove();
3347        }
3348        if (matches.size() == 0) {
3349            return null;
3350        } else if (matches.size() == 1) {
3351            return (ActivityInfo) matches.get(0).getComponentInfo();
3352        } else {
3353            throw new RuntimeException(
3354                    "There must be at most one ephemeral installer; found " + matches);
3355        }
3356    }
3357
3358    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3359            @NonNull ComponentName resolver) {
3360        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3361                .addCategory(Intent.CATEGORY_DEFAULT)
3362                .setPackage(resolver.getPackageName());
3363        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3364        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3365                UserHandle.USER_SYSTEM);
3366        // temporarily look for the old action
3367        if (matches.isEmpty()) {
3368            if (DEBUG_EPHEMERAL) {
3369                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3370            }
3371            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3372            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3373                    UserHandle.USER_SYSTEM);
3374        }
3375        if (matches.isEmpty()) {
3376            return null;
3377        }
3378        return matches.get(0).getComponentInfo().getComponentName();
3379    }
3380
3381    private void primeDomainVerificationsLPw(int userId) {
3382        if (DEBUG_DOMAIN_VERIFICATION) {
3383            Slog.d(TAG, "Priming domain verifications in user " + userId);
3384        }
3385
3386        SystemConfig systemConfig = SystemConfig.getInstance();
3387        ArraySet<String> packages = systemConfig.getLinkedApps();
3388
3389        for (String packageName : packages) {
3390            PackageParser.Package pkg = mPackages.get(packageName);
3391            if (pkg != null) {
3392                if (!pkg.isSystemApp()) {
3393                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3394                    continue;
3395                }
3396
3397                ArraySet<String> domains = null;
3398                for (PackageParser.Activity a : pkg.activities) {
3399                    for (ActivityIntentInfo filter : a.intents) {
3400                        if (hasValidDomains(filter)) {
3401                            if (domains == null) {
3402                                domains = new ArraySet<String>();
3403                            }
3404                            domains.addAll(filter.getHostsList());
3405                        }
3406                    }
3407                }
3408
3409                if (domains != null && domains.size() > 0) {
3410                    if (DEBUG_DOMAIN_VERIFICATION) {
3411                        Slog.v(TAG, "      + " + packageName);
3412                    }
3413                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3414                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3415                    // and then 'always' in the per-user state actually used for intent resolution.
3416                    final IntentFilterVerificationInfo ivi;
3417                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3418                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3419                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3420                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3421                } else {
3422                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3423                            + "' does not handle web links");
3424                }
3425            } else {
3426                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3427            }
3428        }
3429
3430        scheduleWritePackageRestrictionsLocked(userId);
3431        scheduleWriteSettingsLocked();
3432    }
3433
3434    private void applyFactoryDefaultBrowserLPw(int userId) {
3435        // The default browser app's package name is stored in a string resource,
3436        // with a product-specific overlay used for vendor customization.
3437        String browserPkg = mContext.getResources().getString(
3438                com.android.internal.R.string.default_browser);
3439        if (!TextUtils.isEmpty(browserPkg)) {
3440            // non-empty string => required to be a known package
3441            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3442            if (ps == null) {
3443                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3444                browserPkg = null;
3445            } else {
3446                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3447            }
3448        }
3449
3450        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3451        // default.  If there's more than one, just leave everything alone.
3452        if (browserPkg == null) {
3453            calculateDefaultBrowserLPw(userId);
3454        }
3455    }
3456
3457    private void calculateDefaultBrowserLPw(int userId) {
3458        List<String> allBrowsers = resolveAllBrowserApps(userId);
3459        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3460        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3461    }
3462
3463    private List<String> resolveAllBrowserApps(int userId) {
3464        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3465        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3466                PackageManager.MATCH_ALL, userId);
3467
3468        final int count = list.size();
3469        List<String> result = new ArrayList<String>(count);
3470        for (int i=0; i<count; i++) {
3471            ResolveInfo info = list.get(i);
3472            if (info.activityInfo == null
3473                    || !info.handleAllWebDataURI
3474                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3475                    || result.contains(info.activityInfo.packageName)) {
3476                continue;
3477            }
3478            result.add(info.activityInfo.packageName);
3479        }
3480
3481        return result;
3482    }
3483
3484    private boolean packageIsBrowser(String packageName, int userId) {
3485        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3486                PackageManager.MATCH_ALL, userId);
3487        final int N = list.size();
3488        for (int i = 0; i < N; i++) {
3489            ResolveInfo info = list.get(i);
3490            if (packageName.equals(info.activityInfo.packageName)) {
3491                return true;
3492            }
3493        }
3494        return false;
3495    }
3496
3497    private void checkDefaultBrowser() {
3498        final int myUserId = UserHandle.myUserId();
3499        final String packageName = getDefaultBrowserPackageName(myUserId);
3500        if (packageName != null) {
3501            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3502            if (info == null) {
3503                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3504                synchronized (mPackages) {
3505                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3506                }
3507            }
3508        }
3509    }
3510
3511    @Override
3512    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3513            throws RemoteException {
3514        try {
3515            return super.onTransact(code, data, reply, flags);
3516        } catch (RuntimeException e) {
3517            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3518                Slog.wtf(TAG, "Package Manager Crash", e);
3519            }
3520            throw e;
3521        }
3522    }
3523
3524    static int[] appendInts(int[] cur, int[] add) {
3525        if (add == null) return cur;
3526        if (cur == null) return add;
3527        final int N = add.length;
3528        for (int i=0; i<N; i++) {
3529            cur = appendInt(cur, add[i]);
3530        }
3531        return cur;
3532    }
3533
3534    /**
3535     * Returns whether or not a full application can see an instant application.
3536     * <p>
3537     * Currently, there are three cases in which this can occur:
3538     * <ol>
3539     * <li>The calling application is a "special" process. The special
3540     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3541     *     and {@code 0}</li>
3542     * <li>The calling application has the permission
3543     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3544     * <li>The calling application is the default launcher on the
3545     *     system partition.</li>
3546     * </ol>
3547     */
3548    private boolean canViewInstantApps(int callingUid, int userId) {
3549        if (callingUid == Process.SYSTEM_UID
3550                || callingUid == Process.SHELL_UID
3551                || callingUid == Process.ROOT_UID) {
3552            return true;
3553        }
3554        if (mContext.checkCallingOrSelfPermission(
3555                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3556            return true;
3557        }
3558        if (mContext.checkCallingOrSelfPermission(
3559                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3560            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3561            if (homeComponent != null
3562                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3563                return true;
3564            }
3565        }
3566        return false;
3567    }
3568
3569    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3570        if (!sUserManager.exists(userId)) return null;
3571        if (ps == null) {
3572            return null;
3573        }
3574        PackageParser.Package p = ps.pkg;
3575        if (p == null) {
3576            return null;
3577        }
3578        final int callingUid = Binder.getCallingUid();
3579        // Filter out ephemeral app metadata:
3580        //   * The system/shell/root can see metadata for any app
3581        //   * An installed app can see metadata for 1) other installed apps
3582        //     and 2) ephemeral apps that have explicitly interacted with it
3583        //   * Ephemeral apps can only see their own data and exposed installed apps
3584        //   * Holding a signature permission allows seeing instant apps
3585        if (filterAppAccessLPr(ps, callingUid, userId)) {
3586            return null;
3587        }
3588
3589        final PermissionsState permissionsState = ps.getPermissionsState();
3590
3591        // Compute GIDs only if requested
3592        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3593                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3594        // Compute granted permissions only if package has requested permissions
3595        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3596                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3597        final PackageUserState state = ps.readUserState(userId);
3598
3599        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3600                && ps.isSystem()) {
3601            flags |= MATCH_ANY_USER;
3602        }
3603
3604        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3605                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3606
3607        if (packageInfo == null) {
3608            return null;
3609        }
3610
3611        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3612                resolveExternalPackageNameLPr(p);
3613
3614        return packageInfo;
3615    }
3616
3617    @Override
3618    public void checkPackageStartable(String packageName, int userId) {
3619        final int callingUid = Binder.getCallingUid();
3620        if (getInstantAppPackageName(callingUid) != null) {
3621            throw new SecurityException("Instant applications don't have access to this method");
3622        }
3623        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3624        synchronized (mPackages) {
3625            final PackageSetting ps = mSettings.mPackages.get(packageName);
3626            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3627                throw new SecurityException("Package " + packageName + " was not found!");
3628            }
3629
3630            if (!ps.getInstalled(userId)) {
3631                throw new SecurityException(
3632                        "Package " + packageName + " was not installed for user " + userId + "!");
3633            }
3634
3635            if (mSafeMode && !ps.isSystem()) {
3636                throw new SecurityException("Package " + packageName + " not a system app!");
3637            }
3638
3639            if (mFrozenPackages.contains(packageName)) {
3640                throw new SecurityException("Package " + packageName + " is currently frozen!");
3641            }
3642
3643            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3644                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3645                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3646            }
3647        }
3648    }
3649
3650    @Override
3651    public boolean isPackageAvailable(String packageName, int userId) {
3652        if (!sUserManager.exists(userId)) return false;
3653        final int callingUid = Binder.getCallingUid();
3654        enforceCrossUserPermission(callingUid, userId,
3655                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3656        synchronized (mPackages) {
3657            PackageParser.Package p = mPackages.get(packageName);
3658            if (p != null) {
3659                final PackageSetting ps = (PackageSetting) p.mExtras;
3660                if (filterAppAccessLPr(ps, callingUid, userId)) {
3661                    return false;
3662                }
3663                if (ps != null) {
3664                    final PackageUserState state = ps.readUserState(userId);
3665                    if (state != null) {
3666                        return PackageParser.isAvailable(state);
3667                    }
3668                }
3669            }
3670        }
3671        return false;
3672    }
3673
3674    @Override
3675    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3676        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3677                flags, Binder.getCallingUid(), userId);
3678    }
3679
3680    @Override
3681    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3682            int flags, int userId) {
3683        return getPackageInfoInternal(versionedPackage.getPackageName(),
3684                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3685    }
3686
3687    /**
3688     * Important: The provided filterCallingUid is used exclusively to filter out packages
3689     * that can be seen based on user state. It's typically the original caller uid prior
3690     * to clearing. Because it can only be provided by trusted code, it's value can be
3691     * trusted and will be used as-is; unlike userId which will be validated by this method.
3692     */
3693    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3694            int flags, int filterCallingUid, int userId) {
3695        if (!sUserManager.exists(userId)) return null;
3696        flags = updateFlagsForPackage(flags, userId, packageName);
3697        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3698                false /* requireFullPermission */, false /* checkShell */, "get package info");
3699
3700        // reader
3701        synchronized (mPackages) {
3702            // Normalize package name to handle renamed packages and static libs
3703            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3704
3705            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3706            if (matchFactoryOnly) {
3707                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3708                if (ps != null) {
3709                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3710                        return null;
3711                    }
3712                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3713                        return null;
3714                    }
3715                    return generatePackageInfo(ps, flags, userId);
3716                }
3717            }
3718
3719            PackageParser.Package p = mPackages.get(packageName);
3720            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3721                return null;
3722            }
3723            if (DEBUG_PACKAGE_INFO)
3724                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3725            if (p != null) {
3726                final PackageSetting ps = (PackageSetting) p.mExtras;
3727                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3728                    return null;
3729                }
3730                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3731                    return null;
3732                }
3733                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3734            }
3735            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3736                final PackageSetting ps = mSettings.mPackages.get(packageName);
3737                if (ps == null) return null;
3738                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3739                    return null;
3740                }
3741                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3742                    return null;
3743                }
3744                return generatePackageInfo(ps, flags, userId);
3745            }
3746        }
3747        return null;
3748    }
3749
3750    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3751        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3752            return true;
3753        }
3754        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3755            return true;
3756        }
3757        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3758            return true;
3759        }
3760        return false;
3761    }
3762
3763    private boolean isComponentVisibleToInstantApp(
3764            @Nullable ComponentName component, @ComponentType int type) {
3765        if (type == TYPE_ACTIVITY) {
3766            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3767            return activity != null
3768                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3769                    : false;
3770        } else if (type == TYPE_RECEIVER) {
3771            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3772            return activity != null
3773                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3774                    : false;
3775        } else if (type == TYPE_SERVICE) {
3776            final PackageParser.Service service = mServices.mServices.get(component);
3777            return service != null
3778                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3779                    : false;
3780        } else if (type == TYPE_PROVIDER) {
3781            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3782            return provider != null
3783                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3784                    : false;
3785        } else if (type == TYPE_UNKNOWN) {
3786            return isComponentVisibleToInstantApp(component);
3787        }
3788        return false;
3789    }
3790
3791    /**
3792     * Returns whether or not access to the application should be filtered.
3793     * <p>
3794     * Access may be limited based upon whether the calling or target applications
3795     * are instant applications.
3796     *
3797     * @see #canAccessInstantApps(int)
3798     */
3799    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3800            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3801        // if we're in an isolated process, get the real calling UID
3802        if (Process.isIsolated(callingUid)) {
3803            callingUid = mIsolatedOwners.get(callingUid);
3804        }
3805        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3806        final boolean callerIsInstantApp = instantAppPkgName != null;
3807        if (ps == null) {
3808            if (callerIsInstantApp) {
3809                // pretend the application exists, but, needs to be filtered
3810                return true;
3811            }
3812            return false;
3813        }
3814        // if the target and caller are the same application, don't filter
3815        if (isCallerSameApp(ps.name, callingUid)) {
3816            return false;
3817        }
3818        if (callerIsInstantApp) {
3819            // request for a specific component; if it hasn't been explicitly exposed, filter
3820            if (component != null) {
3821                return !isComponentVisibleToInstantApp(component, componentType);
3822            }
3823            // request for application; if no components have been explicitly exposed, filter
3824            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3825        }
3826        if (ps.getInstantApp(userId)) {
3827            // caller can see all components of all instant applications, don't filter
3828            if (canViewInstantApps(callingUid, userId)) {
3829                return false;
3830            }
3831            // request for a specific instant application component, filter
3832            if (component != null) {
3833                return true;
3834            }
3835            // request for an instant application; if the caller hasn't been granted access, filter
3836            return !mInstantAppRegistry.isInstantAccessGranted(
3837                    userId, UserHandle.getAppId(callingUid), ps.appId);
3838        }
3839        return false;
3840    }
3841
3842    /**
3843     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3844     */
3845    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3846        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3847    }
3848
3849    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3850            int flags) {
3851        // Callers can access only the libs they depend on, otherwise they need to explicitly
3852        // ask for the shared libraries given the caller is allowed to access all static libs.
3853        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3854            // System/shell/root get to see all static libs
3855            final int appId = UserHandle.getAppId(uid);
3856            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3857                    || appId == Process.ROOT_UID) {
3858                return false;
3859            }
3860        }
3861
3862        // No package means no static lib as it is always on internal storage
3863        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3864            return false;
3865        }
3866
3867        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3868                ps.pkg.staticSharedLibVersion);
3869        if (libEntry == null) {
3870            return false;
3871        }
3872
3873        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3874        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3875        if (uidPackageNames == null) {
3876            return true;
3877        }
3878
3879        for (String uidPackageName : uidPackageNames) {
3880            if (ps.name.equals(uidPackageName)) {
3881                return false;
3882            }
3883            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3884            if (uidPs != null) {
3885                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3886                        libEntry.info.getName());
3887                if (index < 0) {
3888                    continue;
3889                }
3890                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3891                    return false;
3892                }
3893            }
3894        }
3895        return true;
3896    }
3897
3898    @Override
3899    public String[] currentToCanonicalPackageNames(String[] names) {
3900        final int callingUid = Binder.getCallingUid();
3901        if (getInstantAppPackageName(callingUid) != null) {
3902            return names;
3903        }
3904        final String[] out = new String[names.length];
3905        // reader
3906        synchronized (mPackages) {
3907            final int callingUserId = UserHandle.getUserId(callingUid);
3908            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3909            for (int i=names.length-1; i>=0; i--) {
3910                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3911                boolean translateName = false;
3912                if (ps != null && ps.realName != null) {
3913                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3914                    translateName = !targetIsInstantApp
3915                            || canViewInstantApps
3916                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3917                                    UserHandle.getAppId(callingUid), ps.appId);
3918                }
3919                out[i] = translateName ? ps.realName : names[i];
3920            }
3921        }
3922        return out;
3923    }
3924
3925    @Override
3926    public String[] canonicalToCurrentPackageNames(String[] names) {
3927        final int callingUid = Binder.getCallingUid();
3928        if (getInstantAppPackageName(callingUid) != null) {
3929            return names;
3930        }
3931        final String[] out = new String[names.length];
3932        // reader
3933        synchronized (mPackages) {
3934            final int callingUserId = UserHandle.getUserId(callingUid);
3935            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3936            for (int i=names.length-1; i>=0; i--) {
3937                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3938                boolean translateName = false;
3939                if (cur != null) {
3940                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3941                    final boolean targetIsInstantApp =
3942                            ps != null && ps.getInstantApp(callingUserId);
3943                    translateName = !targetIsInstantApp
3944                            || canViewInstantApps
3945                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3946                                    UserHandle.getAppId(callingUid), ps.appId);
3947                }
3948                out[i] = translateName ? cur : names[i];
3949            }
3950        }
3951        return out;
3952    }
3953
3954    @Override
3955    public int getPackageUid(String packageName, int flags, int userId) {
3956        if (!sUserManager.exists(userId)) return -1;
3957        final int callingUid = Binder.getCallingUid();
3958        flags = updateFlagsForPackage(flags, userId, packageName);
3959        enforceCrossUserPermission(callingUid, userId,
3960                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3961
3962        // reader
3963        synchronized (mPackages) {
3964            final PackageParser.Package p = mPackages.get(packageName);
3965            if (p != null && p.isMatch(flags)) {
3966                PackageSetting ps = (PackageSetting) p.mExtras;
3967                if (filterAppAccessLPr(ps, callingUid, userId)) {
3968                    return -1;
3969                }
3970                return UserHandle.getUid(userId, p.applicationInfo.uid);
3971            }
3972            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3973                final PackageSetting ps = mSettings.mPackages.get(packageName);
3974                if (ps != null && ps.isMatch(flags)
3975                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3976                    return UserHandle.getUid(userId, ps.appId);
3977                }
3978            }
3979        }
3980
3981        return -1;
3982    }
3983
3984    @Override
3985    public int[] getPackageGids(String packageName, int flags, int userId) {
3986        if (!sUserManager.exists(userId)) return null;
3987        final int callingUid = Binder.getCallingUid();
3988        flags = updateFlagsForPackage(flags, userId, packageName);
3989        enforceCrossUserPermission(callingUid, userId,
3990                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3991
3992        // reader
3993        synchronized (mPackages) {
3994            final PackageParser.Package p = mPackages.get(packageName);
3995            if (p != null && p.isMatch(flags)) {
3996                PackageSetting ps = (PackageSetting) p.mExtras;
3997                if (filterAppAccessLPr(ps, callingUid, userId)) {
3998                    return null;
3999                }
4000                // TODO: Shouldn't this be checking for package installed state for userId and
4001                // return null?
4002                return ps.getPermissionsState().computeGids(userId);
4003            }
4004            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4005                final PackageSetting ps = mSettings.mPackages.get(packageName);
4006                if (ps != null && ps.isMatch(flags)
4007                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4008                    return ps.getPermissionsState().computeGids(userId);
4009                }
4010            }
4011        }
4012
4013        return null;
4014    }
4015
4016    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4017        if (bp.perm != null) {
4018            return PackageParser.generatePermissionInfo(bp.perm, flags);
4019        }
4020        PermissionInfo pi = new PermissionInfo();
4021        pi.name = bp.name;
4022        pi.packageName = bp.sourcePackage;
4023        pi.nonLocalizedLabel = bp.name;
4024        pi.protectionLevel = bp.protectionLevel;
4025        return pi;
4026    }
4027
4028    @Override
4029    public PermissionInfo getPermissionInfo(String name, int flags) {
4030        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4031            return null;
4032        }
4033        // reader
4034        synchronized (mPackages) {
4035            final BasePermission p = mSettings.mPermissions.get(name);
4036            if (p != null) {
4037                return generatePermissionInfo(p, flags);
4038            }
4039            return null;
4040        }
4041    }
4042
4043    @Override
4044    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4045            int flags) {
4046        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4047            return null;
4048        }
4049        // reader
4050        synchronized (mPackages) {
4051            if (group != null && !mPermissionGroups.containsKey(group)) {
4052                // This is thrown as NameNotFoundException
4053                return null;
4054            }
4055
4056            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4057            for (BasePermission p : mSettings.mPermissions.values()) {
4058                if (group == null) {
4059                    if (p.perm == null || p.perm.info.group == null) {
4060                        out.add(generatePermissionInfo(p, flags));
4061                    }
4062                } else {
4063                    if (p.perm != null && group.equals(p.perm.info.group)) {
4064                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4065                    }
4066                }
4067            }
4068            return new ParceledListSlice<>(out);
4069        }
4070    }
4071
4072    @Override
4073    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4074        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4075            return null;
4076        }
4077        // reader
4078        synchronized (mPackages) {
4079            return PackageParser.generatePermissionGroupInfo(
4080                    mPermissionGroups.get(name), flags);
4081        }
4082    }
4083
4084    @Override
4085    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4086        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4087            return ParceledListSlice.emptyList();
4088        }
4089        // reader
4090        synchronized (mPackages) {
4091            final int N = mPermissionGroups.size();
4092            ArrayList<PermissionGroupInfo> out
4093                    = new ArrayList<PermissionGroupInfo>(N);
4094            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4095                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4096            }
4097            return new ParceledListSlice<>(out);
4098        }
4099    }
4100
4101    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4102            int filterCallingUid, int userId) {
4103        if (!sUserManager.exists(userId)) return null;
4104        PackageSetting ps = mSettings.mPackages.get(packageName);
4105        if (ps != null) {
4106            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4107                return null;
4108            }
4109            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4110                return null;
4111            }
4112            if (ps.pkg == null) {
4113                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4114                if (pInfo != null) {
4115                    return pInfo.applicationInfo;
4116                }
4117                return null;
4118            }
4119            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4120                    ps.readUserState(userId), userId);
4121            if (ai != null) {
4122                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4123            }
4124            return ai;
4125        }
4126        return null;
4127    }
4128
4129    @Override
4130    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4131        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4132    }
4133
4134    /**
4135     * Important: The provided filterCallingUid is used exclusively to filter out applications
4136     * that can be seen based on user state. It's typically the original caller uid prior
4137     * to clearing. Because it can only be provided by trusted code, it's value can be
4138     * trusted and will be used as-is; unlike userId which will be validated by this method.
4139     */
4140    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4141            int filterCallingUid, int userId) {
4142        if (!sUserManager.exists(userId)) return null;
4143        flags = updateFlagsForApplication(flags, userId, packageName);
4144        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4145                false /* requireFullPermission */, false /* checkShell */, "get application info");
4146
4147        // writer
4148        synchronized (mPackages) {
4149            // Normalize package name to handle renamed packages and static libs
4150            packageName = resolveInternalPackageNameLPr(packageName,
4151                    PackageManager.VERSION_CODE_HIGHEST);
4152
4153            PackageParser.Package p = mPackages.get(packageName);
4154            if (DEBUG_PACKAGE_INFO) Log.v(
4155                    TAG, "getApplicationInfo " + packageName
4156                    + ": " + p);
4157            if (p != null) {
4158                PackageSetting ps = mSettings.mPackages.get(packageName);
4159                if (ps == null) return null;
4160                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4161                    return null;
4162                }
4163                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4164                    return null;
4165                }
4166                // Note: isEnabledLP() does not apply here - always return info
4167                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4168                        p, flags, ps.readUserState(userId), userId);
4169                if (ai != null) {
4170                    ai.packageName = resolveExternalPackageNameLPr(p);
4171                }
4172                return ai;
4173            }
4174            if ("android".equals(packageName)||"system".equals(packageName)) {
4175                return mAndroidApplication;
4176            }
4177            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4178                // Already generates the external package name
4179                return generateApplicationInfoFromSettingsLPw(packageName,
4180                        flags, filterCallingUid, userId);
4181            }
4182        }
4183        return null;
4184    }
4185
4186    private String normalizePackageNameLPr(String packageName) {
4187        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4188        return normalizedPackageName != null ? normalizedPackageName : packageName;
4189    }
4190
4191    @Override
4192    public void deletePreloadsFileCache() {
4193        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4194            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4195        }
4196        File dir = Environment.getDataPreloadsFileCacheDirectory();
4197        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4198        FileUtils.deleteContents(dir);
4199    }
4200
4201    @Override
4202    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4203            final int storageFlags, final IPackageDataObserver observer) {
4204        mContext.enforceCallingOrSelfPermission(
4205                android.Manifest.permission.CLEAR_APP_CACHE, null);
4206        mHandler.post(() -> {
4207            boolean success = false;
4208            try {
4209                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4210                success = true;
4211            } catch (IOException e) {
4212                Slog.w(TAG, e);
4213            }
4214            if (observer != null) {
4215                try {
4216                    observer.onRemoveCompleted(null, success);
4217                } catch (RemoteException e) {
4218                    Slog.w(TAG, e);
4219                }
4220            }
4221        });
4222    }
4223
4224    @Override
4225    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4226            final int storageFlags, final IntentSender pi) {
4227        mContext.enforceCallingOrSelfPermission(
4228                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4229        mHandler.post(() -> {
4230            boolean success = false;
4231            try {
4232                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4233                success = true;
4234            } catch (IOException e) {
4235                Slog.w(TAG, e);
4236            }
4237            if (pi != null) {
4238                try {
4239                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4240                } catch (SendIntentException e) {
4241                    Slog.w(TAG, e);
4242                }
4243            }
4244        });
4245    }
4246
4247    /**
4248     * Blocking call to clear various types of cached data across the system
4249     * until the requested bytes are available.
4250     */
4251    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4252        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4253        final File file = storage.findPathForUuid(volumeUuid);
4254        if (file.getUsableSpace() >= bytes) return;
4255
4256        if (ENABLE_FREE_CACHE_V2) {
4257            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4258                    volumeUuid);
4259            final boolean aggressive = (storageFlags
4260                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4261            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4262
4263            // 1. Pre-flight to determine if we have any chance to succeed
4264            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4265            if (internalVolume && (aggressive || SystemProperties
4266                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4267                deletePreloadsFileCache();
4268                if (file.getUsableSpace() >= bytes) return;
4269            }
4270
4271            // 3. Consider parsed APK data (aggressive only)
4272            if (internalVolume && aggressive) {
4273                FileUtils.deleteContents(mCacheDir);
4274                if (file.getUsableSpace() >= bytes) return;
4275            }
4276
4277            // 4. Consider cached app data (above quotas)
4278            try {
4279                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4280                        Installer.FLAG_FREE_CACHE_V2);
4281            } catch (InstallerException ignored) {
4282            }
4283            if (file.getUsableSpace() >= bytes) return;
4284
4285            // 5. Consider shared libraries with refcount=0 and age>min cache period
4286            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4287                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4288                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4289                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4290                return;
4291            }
4292
4293            // 6. Consider dexopt output (aggressive only)
4294            // TODO: Implement
4295
4296            // 7. Consider installed instant apps unused longer than min cache period
4297            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4298                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4299                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4300                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4301                return;
4302            }
4303
4304            // 8. Consider cached app data (below quotas)
4305            try {
4306                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4307                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4308            } catch (InstallerException ignored) {
4309            }
4310            if (file.getUsableSpace() >= bytes) return;
4311
4312            // 9. Consider DropBox entries
4313            // TODO: Implement
4314
4315            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4316            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4317                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4318                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4319                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4320                return;
4321            }
4322        } else {
4323            try {
4324                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4325            } catch (InstallerException ignored) {
4326            }
4327            if (file.getUsableSpace() >= bytes) return;
4328        }
4329
4330        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4331    }
4332
4333    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4334            throws IOException {
4335        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4336        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4337
4338        List<VersionedPackage> packagesToDelete = null;
4339        final long now = System.currentTimeMillis();
4340
4341        synchronized (mPackages) {
4342            final int[] allUsers = sUserManager.getUserIds();
4343            final int libCount = mSharedLibraries.size();
4344            for (int i = 0; i < libCount; i++) {
4345                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4346                if (versionedLib == null) {
4347                    continue;
4348                }
4349                final int versionCount = versionedLib.size();
4350                for (int j = 0; j < versionCount; j++) {
4351                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4352                    // Skip packages that are not static shared libs.
4353                    if (!libInfo.isStatic()) {
4354                        break;
4355                    }
4356                    // Important: We skip static shared libs used for some user since
4357                    // in such a case we need to keep the APK on the device. The check for
4358                    // a lib being used for any user is performed by the uninstall call.
4359                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4360                    // Resolve the package name - we use synthetic package names internally
4361                    final String internalPackageName = resolveInternalPackageNameLPr(
4362                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4363                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4364                    // Skip unused static shared libs cached less than the min period
4365                    // to prevent pruning a lib needed by a subsequently installed package.
4366                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4367                        continue;
4368                    }
4369                    if (packagesToDelete == null) {
4370                        packagesToDelete = new ArrayList<>();
4371                    }
4372                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4373                            declaringPackage.getVersionCode()));
4374                }
4375            }
4376        }
4377
4378        if (packagesToDelete != null) {
4379            final int packageCount = packagesToDelete.size();
4380            for (int i = 0; i < packageCount; i++) {
4381                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4382                // Delete the package synchronously (will fail of the lib used for any user).
4383                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4384                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4385                                == PackageManager.DELETE_SUCCEEDED) {
4386                    if (volume.getUsableSpace() >= neededSpace) {
4387                        return true;
4388                    }
4389                }
4390            }
4391        }
4392
4393        return false;
4394    }
4395
4396    /**
4397     * Update given flags based on encryption status of current user.
4398     */
4399    private int updateFlags(int flags, int userId) {
4400        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4401                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4402            // Caller expressed an explicit opinion about what encryption
4403            // aware/unaware components they want to see, so fall through and
4404            // give them what they want
4405        } else {
4406            // Caller expressed no opinion, so match based on user state
4407            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4408                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4409            } else {
4410                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4411            }
4412        }
4413        return flags;
4414    }
4415
4416    private UserManagerInternal getUserManagerInternal() {
4417        if (mUserManagerInternal == null) {
4418            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4419        }
4420        return mUserManagerInternal;
4421    }
4422
4423    private DeviceIdleController.LocalService getDeviceIdleController() {
4424        if (mDeviceIdleController == null) {
4425            mDeviceIdleController =
4426                    LocalServices.getService(DeviceIdleController.LocalService.class);
4427        }
4428        return mDeviceIdleController;
4429    }
4430
4431    /**
4432     * Update given flags when being used to request {@link PackageInfo}.
4433     */
4434    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4435        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4436        boolean triaged = true;
4437        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4438                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4439            // Caller is asking for component details, so they'd better be
4440            // asking for specific encryption matching behavior, or be triaged
4441            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4442                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4443                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4444                triaged = false;
4445            }
4446        }
4447        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4448                | PackageManager.MATCH_SYSTEM_ONLY
4449                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4450            triaged = false;
4451        }
4452        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4453            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4454                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4455                    + Debug.getCallers(5));
4456        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4457                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4458            // If the caller wants all packages and has a restricted profile associated with it,
4459            // then match all users. This is to make sure that launchers that need to access work
4460            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4461            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4462            flags |= PackageManager.MATCH_ANY_USER;
4463        }
4464        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4465            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4466                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4467        }
4468        return updateFlags(flags, userId);
4469    }
4470
4471    /**
4472     * Update given flags when being used to request {@link ApplicationInfo}.
4473     */
4474    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4475        return updateFlagsForPackage(flags, userId, cookie);
4476    }
4477
4478    /**
4479     * Update given flags when being used to request {@link ComponentInfo}.
4480     */
4481    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4482        if (cookie instanceof Intent) {
4483            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4484                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4485            }
4486        }
4487
4488        boolean triaged = true;
4489        // Caller is asking for component details, so they'd better be
4490        // asking for specific encryption matching behavior, or be triaged
4491        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4492                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4493                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4494            triaged = false;
4495        }
4496        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4497            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4498                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4499        }
4500
4501        return updateFlags(flags, userId);
4502    }
4503
4504    /**
4505     * Update given intent when being used to request {@link ResolveInfo}.
4506     */
4507    private Intent updateIntentForResolve(Intent intent) {
4508        if (intent.getSelector() != null) {
4509            intent = intent.getSelector();
4510        }
4511        if (DEBUG_PREFERRED) {
4512            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4513        }
4514        return intent;
4515    }
4516
4517    /**
4518     * Update given flags when being used to request {@link ResolveInfo}.
4519     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4520     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4521     * flag set. However, this flag is only honoured in three circumstances:
4522     * <ul>
4523     * <li>when called from a system process</li>
4524     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4525     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4526     * action and a {@code android.intent.category.BROWSABLE} category</li>
4527     * </ul>
4528     */
4529    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4530        return updateFlagsForResolve(flags, userId, intent, callingUid,
4531                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4532    }
4533    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4534            boolean wantInstantApps) {
4535        return updateFlagsForResolve(flags, userId, intent, callingUid,
4536                wantInstantApps, false /*onlyExposedExplicitly*/);
4537    }
4538    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4539            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4540        // Safe mode means we shouldn't match any third-party components
4541        if (mSafeMode) {
4542            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4543        }
4544        if (getInstantAppPackageName(callingUid) != null) {
4545            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4546            if (onlyExposedExplicitly) {
4547                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4548            }
4549            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4550            flags |= PackageManager.MATCH_INSTANT;
4551        } else {
4552            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4553            final boolean allowMatchInstant =
4554                    (wantInstantApps
4555                            && Intent.ACTION_VIEW.equals(intent.getAction())
4556                            && hasWebURI(intent))
4557                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4558            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4559                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4560            if (!allowMatchInstant) {
4561                flags &= ~PackageManager.MATCH_INSTANT;
4562            }
4563        }
4564        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4565    }
4566
4567    @Override
4568    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4569        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4570    }
4571
4572    /**
4573     * Important: The provided filterCallingUid is used exclusively to filter out activities
4574     * that can be seen based on user state. It's typically the original caller uid prior
4575     * to clearing. Because it can only be provided by trusted code, it's value can be
4576     * trusted and will be used as-is; unlike userId which will be validated by this method.
4577     */
4578    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4579            int filterCallingUid, int userId) {
4580        if (!sUserManager.exists(userId)) return null;
4581        flags = updateFlagsForComponent(flags, userId, component);
4582        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4583                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4584        synchronized (mPackages) {
4585            PackageParser.Activity a = mActivities.mActivities.get(component);
4586
4587            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4588            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4589                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4590                if (ps == null) return null;
4591                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4592                    return null;
4593                }
4594                return PackageParser.generateActivityInfo(
4595                        a, flags, ps.readUserState(userId), userId);
4596            }
4597            if (mResolveComponentName.equals(component)) {
4598                return PackageParser.generateActivityInfo(
4599                        mResolveActivity, flags, new PackageUserState(), userId);
4600            }
4601        }
4602        return null;
4603    }
4604
4605    @Override
4606    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4607            String resolvedType) {
4608        synchronized (mPackages) {
4609            if (component.equals(mResolveComponentName)) {
4610                // The resolver supports EVERYTHING!
4611                return true;
4612            }
4613            final int callingUid = Binder.getCallingUid();
4614            final int callingUserId = UserHandle.getUserId(callingUid);
4615            PackageParser.Activity a = mActivities.mActivities.get(component);
4616            if (a == null) {
4617                return false;
4618            }
4619            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4620            if (ps == null) {
4621                return false;
4622            }
4623            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4624                return false;
4625            }
4626            for (int i=0; i<a.intents.size(); i++) {
4627                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4628                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4629                    return true;
4630                }
4631            }
4632            return false;
4633        }
4634    }
4635
4636    @Override
4637    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4638        if (!sUserManager.exists(userId)) return null;
4639        final int callingUid = Binder.getCallingUid();
4640        flags = updateFlagsForComponent(flags, userId, component);
4641        enforceCrossUserPermission(callingUid, userId,
4642                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4643        synchronized (mPackages) {
4644            PackageParser.Activity a = mReceivers.mActivities.get(component);
4645            if (DEBUG_PACKAGE_INFO) Log.v(
4646                TAG, "getReceiverInfo " + component + ": " + a);
4647            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4648                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4649                if (ps == null) return null;
4650                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4651                    return null;
4652                }
4653                return PackageParser.generateActivityInfo(
4654                        a, flags, ps.readUserState(userId), userId);
4655            }
4656        }
4657        return null;
4658    }
4659
4660    @Override
4661    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4662            int flags, int userId) {
4663        if (!sUserManager.exists(userId)) return null;
4664        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4665        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4666            return null;
4667        }
4668
4669        flags = updateFlagsForPackage(flags, userId, null);
4670
4671        final boolean canSeeStaticLibraries =
4672                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4673                        == PERMISSION_GRANTED
4674                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4675                        == PERMISSION_GRANTED
4676                || canRequestPackageInstallsInternal(packageName,
4677                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4678                        false  /* throwIfPermNotDeclared*/)
4679                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4680                        == PERMISSION_GRANTED;
4681
4682        synchronized (mPackages) {
4683            List<SharedLibraryInfo> result = null;
4684
4685            final int libCount = mSharedLibraries.size();
4686            for (int i = 0; i < libCount; i++) {
4687                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4688                if (versionedLib == null) {
4689                    continue;
4690                }
4691
4692                final int versionCount = versionedLib.size();
4693                for (int j = 0; j < versionCount; j++) {
4694                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4695                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4696                        break;
4697                    }
4698                    final long identity = Binder.clearCallingIdentity();
4699                    try {
4700                        PackageInfo packageInfo = getPackageInfoVersioned(
4701                                libInfo.getDeclaringPackage(), flags
4702                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4703                        if (packageInfo == null) {
4704                            continue;
4705                        }
4706                    } finally {
4707                        Binder.restoreCallingIdentity(identity);
4708                    }
4709
4710                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4711                            libInfo.getVersion(), libInfo.getType(),
4712                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4713                            flags, userId));
4714
4715                    if (result == null) {
4716                        result = new ArrayList<>();
4717                    }
4718                    result.add(resLibInfo);
4719                }
4720            }
4721
4722            return result != null ? new ParceledListSlice<>(result) : null;
4723        }
4724    }
4725
4726    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4727            SharedLibraryInfo libInfo, int flags, int userId) {
4728        List<VersionedPackage> versionedPackages = null;
4729        final int packageCount = mSettings.mPackages.size();
4730        for (int i = 0; i < packageCount; i++) {
4731            PackageSetting ps = mSettings.mPackages.valueAt(i);
4732
4733            if (ps == null) {
4734                continue;
4735            }
4736
4737            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4738                continue;
4739            }
4740
4741            final String libName = libInfo.getName();
4742            if (libInfo.isStatic()) {
4743                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4744                if (libIdx < 0) {
4745                    continue;
4746                }
4747                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4748                    continue;
4749                }
4750                if (versionedPackages == null) {
4751                    versionedPackages = new ArrayList<>();
4752                }
4753                // If the dependent is a static shared lib, use the public package name
4754                String dependentPackageName = ps.name;
4755                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4756                    dependentPackageName = ps.pkg.manifestPackageName;
4757                }
4758                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4759            } else if (ps.pkg != null) {
4760                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4761                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4762                    if (versionedPackages == null) {
4763                        versionedPackages = new ArrayList<>();
4764                    }
4765                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4766                }
4767            }
4768        }
4769
4770        return versionedPackages;
4771    }
4772
4773    @Override
4774    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4775        if (!sUserManager.exists(userId)) return null;
4776        final int callingUid = Binder.getCallingUid();
4777        flags = updateFlagsForComponent(flags, userId, component);
4778        enforceCrossUserPermission(callingUid, userId,
4779                false /* requireFullPermission */, false /* checkShell */, "get service info");
4780        synchronized (mPackages) {
4781            PackageParser.Service s = mServices.mServices.get(component);
4782            if (DEBUG_PACKAGE_INFO) Log.v(
4783                TAG, "getServiceInfo " + component + ": " + s);
4784            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4785                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4786                if (ps == null) return null;
4787                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4788                    return null;
4789                }
4790                return PackageParser.generateServiceInfo(
4791                        s, flags, ps.readUserState(userId), userId);
4792            }
4793        }
4794        return null;
4795    }
4796
4797    @Override
4798    public ProviderInfo getProviderInfo(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 provider info");
4804        synchronized (mPackages) {
4805            PackageParser.Provider p = mProviders.mProviders.get(component);
4806            if (DEBUG_PACKAGE_INFO) Log.v(
4807                TAG, "getProviderInfo " + component + ": " + p);
4808            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4809                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4810                if (ps == null) return null;
4811                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4812                    return null;
4813                }
4814                return PackageParser.generateProviderInfo(
4815                        p, flags, ps.readUserState(userId), userId);
4816            }
4817        }
4818        return null;
4819    }
4820
4821    @Override
4822    public String[] getSystemSharedLibraryNames() {
4823        // allow instant applications
4824        synchronized (mPackages) {
4825            Set<String> libs = null;
4826            final int libCount = mSharedLibraries.size();
4827            for (int i = 0; i < libCount; i++) {
4828                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4829                if (versionedLib == null) {
4830                    continue;
4831                }
4832                final int versionCount = versionedLib.size();
4833                for (int j = 0; j < versionCount; j++) {
4834                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4835                    if (!libEntry.info.isStatic()) {
4836                        if (libs == null) {
4837                            libs = new ArraySet<>();
4838                        }
4839                        libs.add(libEntry.info.getName());
4840                        break;
4841                    }
4842                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4843                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4844                            UserHandle.getUserId(Binder.getCallingUid()),
4845                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4846                        if (libs == null) {
4847                            libs = new ArraySet<>();
4848                        }
4849                        libs.add(libEntry.info.getName());
4850                        break;
4851                    }
4852                }
4853            }
4854
4855            if (libs != null) {
4856                String[] libsArray = new String[libs.size()];
4857                libs.toArray(libsArray);
4858                return libsArray;
4859            }
4860
4861            return null;
4862        }
4863    }
4864
4865    @Override
4866    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4867        // allow instant applications
4868        synchronized (mPackages) {
4869            return mServicesSystemSharedLibraryPackageName;
4870        }
4871    }
4872
4873    @Override
4874    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4875        // allow instant applications
4876        synchronized (mPackages) {
4877            return mSharedSystemSharedLibraryPackageName;
4878        }
4879    }
4880
4881    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4882        for (int i = userList.length - 1; i >= 0; --i) {
4883            final int userId = userList[i];
4884            // don't add instant app to the list of updates
4885            if (pkgSetting.getInstantApp(userId)) {
4886                continue;
4887            }
4888            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4889            if (changedPackages == null) {
4890                changedPackages = new SparseArray<>();
4891                mChangedPackages.put(userId, changedPackages);
4892            }
4893            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4894            if (sequenceNumbers == null) {
4895                sequenceNumbers = new HashMap<>();
4896                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4897            }
4898            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4899            if (sequenceNumber != null) {
4900                changedPackages.remove(sequenceNumber);
4901            }
4902            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4903            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4904        }
4905        mChangedPackagesSequenceNumber++;
4906    }
4907
4908    @Override
4909    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4910        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4911            return null;
4912        }
4913        synchronized (mPackages) {
4914            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4915                return null;
4916            }
4917            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4918            if (changedPackages == null) {
4919                return null;
4920            }
4921            final List<String> packageNames =
4922                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4923            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4924                final String packageName = changedPackages.get(i);
4925                if (packageName != null) {
4926                    packageNames.add(packageName);
4927                }
4928            }
4929            return packageNames.isEmpty()
4930                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4931        }
4932    }
4933
4934    @Override
4935    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4936        // allow instant applications
4937        ArrayList<FeatureInfo> res;
4938        synchronized (mAvailableFeatures) {
4939            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4940            res.addAll(mAvailableFeatures.values());
4941        }
4942        final FeatureInfo fi = new FeatureInfo();
4943        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4944                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4945        res.add(fi);
4946
4947        return new ParceledListSlice<>(res);
4948    }
4949
4950    @Override
4951    public boolean hasSystemFeature(String name, int version) {
4952        // allow instant applications
4953        synchronized (mAvailableFeatures) {
4954            final FeatureInfo feat = mAvailableFeatures.get(name);
4955            if (feat == null) {
4956                return false;
4957            } else {
4958                return feat.version >= version;
4959            }
4960        }
4961    }
4962
4963    @Override
4964    public int checkPermission(String permName, String pkgName, int userId) {
4965        if (!sUserManager.exists(userId)) {
4966            return PackageManager.PERMISSION_DENIED;
4967        }
4968        final int callingUid = Binder.getCallingUid();
4969
4970        synchronized (mPackages) {
4971            final PackageParser.Package p = mPackages.get(pkgName);
4972            if (p != null && p.mExtras != null) {
4973                final PackageSetting ps = (PackageSetting) p.mExtras;
4974                if (filterAppAccessLPr(ps, callingUid, userId)) {
4975                    return PackageManager.PERMISSION_DENIED;
4976                }
4977                final boolean instantApp = ps.getInstantApp(userId);
4978                final PermissionsState permissionsState = ps.getPermissionsState();
4979                if (permissionsState.hasPermission(permName, userId)) {
4980                    if (instantApp) {
4981                        BasePermission bp = mSettings.mPermissions.get(permName);
4982                        if (bp != null && bp.isInstant()) {
4983                            return PackageManager.PERMISSION_GRANTED;
4984                        }
4985                    } else {
4986                        return PackageManager.PERMISSION_GRANTED;
4987                    }
4988                }
4989                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4990                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4991                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4992                    return PackageManager.PERMISSION_GRANTED;
4993                }
4994            }
4995        }
4996
4997        return PackageManager.PERMISSION_DENIED;
4998    }
4999
5000    @Override
5001    public int checkUidPermission(String permName, int uid) {
5002        final int callingUid = Binder.getCallingUid();
5003        final int callingUserId = UserHandle.getUserId(callingUid);
5004        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5005        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5006        final int userId = UserHandle.getUserId(uid);
5007        if (!sUserManager.exists(userId)) {
5008            return PackageManager.PERMISSION_DENIED;
5009        }
5010
5011        synchronized (mPackages) {
5012            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5013            if (obj != null) {
5014                if (obj instanceof SharedUserSetting) {
5015                    if (isCallerInstantApp) {
5016                        return PackageManager.PERMISSION_DENIED;
5017                    }
5018                } else if (obj instanceof PackageSetting) {
5019                    final PackageSetting ps = (PackageSetting) obj;
5020                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5021                        return PackageManager.PERMISSION_DENIED;
5022                    }
5023                }
5024                final SettingBase settingBase = (SettingBase) obj;
5025                final PermissionsState permissionsState = settingBase.getPermissionsState();
5026                if (permissionsState.hasPermission(permName, userId)) {
5027                    if (isUidInstantApp) {
5028                        BasePermission bp = mSettings.mPermissions.get(permName);
5029                        if (bp != null && bp.isInstant()) {
5030                            return PackageManager.PERMISSION_GRANTED;
5031                        }
5032                    } else {
5033                        return PackageManager.PERMISSION_GRANTED;
5034                    }
5035                }
5036                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5037                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5038                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5039                    return PackageManager.PERMISSION_GRANTED;
5040                }
5041            } else {
5042                ArraySet<String> perms = mSystemPermissions.get(uid);
5043                if (perms != null) {
5044                    if (perms.contains(permName)) {
5045                        return PackageManager.PERMISSION_GRANTED;
5046                    }
5047                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5048                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5049                        return PackageManager.PERMISSION_GRANTED;
5050                    }
5051                }
5052            }
5053        }
5054
5055        return PackageManager.PERMISSION_DENIED;
5056    }
5057
5058    @Override
5059    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5060        if (UserHandle.getCallingUserId() != userId) {
5061            mContext.enforceCallingPermission(
5062                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5063                    "isPermissionRevokedByPolicy for user " + userId);
5064        }
5065
5066        if (checkPermission(permission, packageName, userId)
5067                == PackageManager.PERMISSION_GRANTED) {
5068            return false;
5069        }
5070
5071        final int callingUid = Binder.getCallingUid();
5072        if (getInstantAppPackageName(callingUid) != null) {
5073            if (!isCallerSameApp(packageName, callingUid)) {
5074                return false;
5075            }
5076        } else {
5077            if (isInstantApp(packageName, userId)) {
5078                return false;
5079            }
5080        }
5081
5082        final long identity = Binder.clearCallingIdentity();
5083        try {
5084            final int flags = getPermissionFlags(permission, packageName, userId);
5085            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5086        } finally {
5087            Binder.restoreCallingIdentity(identity);
5088        }
5089    }
5090
5091    @Override
5092    public String getPermissionControllerPackageName() {
5093        synchronized (mPackages) {
5094            return mRequiredInstallerPackage;
5095        }
5096    }
5097
5098    /**
5099     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5100     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5101     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5102     * @param message the message to log on security exception
5103     */
5104    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5105            boolean checkShell, String message) {
5106        if (userId < 0) {
5107            throw new IllegalArgumentException("Invalid userId " + userId);
5108        }
5109        if (checkShell) {
5110            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5111        }
5112        if (userId == UserHandle.getUserId(callingUid)) return;
5113        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5114            if (requireFullPermission) {
5115                mContext.enforceCallingOrSelfPermission(
5116                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5117            } else {
5118                try {
5119                    mContext.enforceCallingOrSelfPermission(
5120                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5121                } catch (SecurityException se) {
5122                    mContext.enforceCallingOrSelfPermission(
5123                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5124                }
5125            }
5126        }
5127    }
5128
5129    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5130        if (callingUid == Process.SHELL_UID) {
5131            if (userHandle >= 0
5132                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5133                throw new SecurityException("Shell does not have permission to access user "
5134                        + userHandle);
5135            } else if (userHandle < 0) {
5136                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5137                        + Debug.getCallers(3));
5138            }
5139        }
5140    }
5141
5142    private BasePermission findPermissionTreeLP(String permName) {
5143        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5144            if (permName.startsWith(bp.name) &&
5145                    permName.length() > bp.name.length() &&
5146                    permName.charAt(bp.name.length()) == '.') {
5147                return bp;
5148            }
5149        }
5150        return null;
5151    }
5152
5153    private BasePermission checkPermissionTreeLP(String permName) {
5154        if (permName != null) {
5155            BasePermission bp = findPermissionTreeLP(permName);
5156            if (bp != null) {
5157                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5158                    return bp;
5159                }
5160                throw new SecurityException("Calling uid "
5161                        + Binder.getCallingUid()
5162                        + " is not allowed to add to permission tree "
5163                        + bp.name + " owned by uid " + bp.uid);
5164            }
5165        }
5166        throw new SecurityException("No permission tree found for " + permName);
5167    }
5168
5169    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5170        if (s1 == null) {
5171            return s2 == null;
5172        }
5173        if (s2 == null) {
5174            return false;
5175        }
5176        if (s1.getClass() != s2.getClass()) {
5177            return false;
5178        }
5179        return s1.equals(s2);
5180    }
5181
5182    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5183        if (pi1.icon != pi2.icon) return false;
5184        if (pi1.logo != pi2.logo) return false;
5185        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5186        if (!compareStrings(pi1.name, pi2.name)) return false;
5187        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5188        // We'll take care of setting this one.
5189        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5190        // These are not currently stored in settings.
5191        //if (!compareStrings(pi1.group, pi2.group)) return false;
5192        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5193        //if (pi1.labelRes != pi2.labelRes) return false;
5194        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5195        return true;
5196    }
5197
5198    int permissionInfoFootprint(PermissionInfo info) {
5199        int size = info.name.length();
5200        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5201        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5202        return size;
5203    }
5204
5205    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5206        int size = 0;
5207        for (BasePermission perm : mSettings.mPermissions.values()) {
5208            if (perm.uid == tree.uid) {
5209                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5210            }
5211        }
5212        return size;
5213    }
5214
5215    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5216        // We calculate the max size of permissions defined by this uid and throw
5217        // if that plus the size of 'info' would exceed our stated maximum.
5218        if (tree.uid != Process.SYSTEM_UID) {
5219            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5220            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5221                throw new SecurityException("Permission tree size cap exceeded");
5222            }
5223        }
5224    }
5225
5226    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5227        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5228            throw new SecurityException("Instant apps can't add permissions");
5229        }
5230        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5231            throw new SecurityException("Label must be specified in permission");
5232        }
5233        BasePermission tree = checkPermissionTreeLP(info.name);
5234        BasePermission bp = mSettings.mPermissions.get(info.name);
5235        boolean added = bp == null;
5236        boolean changed = true;
5237        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5238        if (added) {
5239            enforcePermissionCapLocked(info, tree);
5240            bp = new BasePermission(info.name, tree.sourcePackage,
5241                    BasePermission.TYPE_DYNAMIC);
5242        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5243            throw new SecurityException(
5244                    "Not allowed to modify non-dynamic permission "
5245                    + info.name);
5246        } else {
5247            if (bp.protectionLevel == fixedLevel
5248                    && bp.perm.owner.equals(tree.perm.owner)
5249                    && bp.uid == tree.uid
5250                    && comparePermissionInfos(bp.perm.info, info)) {
5251                changed = false;
5252            }
5253        }
5254        bp.protectionLevel = fixedLevel;
5255        info = new PermissionInfo(info);
5256        info.protectionLevel = fixedLevel;
5257        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5258        bp.perm.info.packageName = tree.perm.info.packageName;
5259        bp.uid = tree.uid;
5260        if (added) {
5261            mSettings.mPermissions.put(info.name, bp);
5262        }
5263        if (changed) {
5264            if (!async) {
5265                mSettings.writeLPr();
5266            } else {
5267                scheduleWriteSettingsLocked();
5268            }
5269        }
5270        return added;
5271    }
5272
5273    @Override
5274    public boolean addPermission(PermissionInfo info) {
5275        synchronized (mPackages) {
5276            return addPermissionLocked(info, false);
5277        }
5278    }
5279
5280    @Override
5281    public boolean addPermissionAsync(PermissionInfo info) {
5282        synchronized (mPackages) {
5283            return addPermissionLocked(info, true);
5284        }
5285    }
5286
5287    @Override
5288    public void removePermission(String name) {
5289        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5290            throw new SecurityException("Instant applications don't have access to this method");
5291        }
5292        synchronized (mPackages) {
5293            checkPermissionTreeLP(name);
5294            BasePermission bp = mSettings.mPermissions.get(name);
5295            if (bp != null) {
5296                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5297                    throw new SecurityException(
5298                            "Not allowed to modify non-dynamic permission "
5299                            + name);
5300                }
5301                mSettings.mPermissions.remove(name);
5302                mSettings.writeLPr();
5303            }
5304        }
5305    }
5306
5307    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5308            PackageParser.Package pkg, BasePermission bp) {
5309        int index = pkg.requestedPermissions.indexOf(bp.name);
5310        if (index == -1) {
5311            throw new SecurityException("Package " + pkg.packageName
5312                    + " has not requested permission " + bp.name);
5313        }
5314        if (!bp.isRuntime() && !bp.isDevelopment()) {
5315            throw new SecurityException("Permission " + bp.name
5316                    + " is not a changeable permission type");
5317        }
5318    }
5319
5320    @Override
5321    public void grantRuntimePermission(String packageName, String name, final int userId) {
5322        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5323    }
5324
5325    private void grantRuntimePermission(String packageName, String name, final int userId,
5326            boolean overridePolicy) {
5327        if (!sUserManager.exists(userId)) {
5328            Log.e(TAG, "No such user:" + userId);
5329            return;
5330        }
5331        final int callingUid = Binder.getCallingUid();
5332
5333        mContext.enforceCallingOrSelfPermission(
5334                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5335                "grantRuntimePermission");
5336
5337        enforceCrossUserPermission(callingUid, userId,
5338                true /* requireFullPermission */, true /* checkShell */,
5339                "grantRuntimePermission");
5340
5341        final int uid;
5342        final PackageSetting ps;
5343
5344        synchronized (mPackages) {
5345            final PackageParser.Package pkg = mPackages.get(packageName);
5346            if (pkg == null) {
5347                throw new IllegalArgumentException("Unknown package: " + packageName);
5348            }
5349            final BasePermission bp = mSettings.mPermissions.get(name);
5350            if (bp == null) {
5351                throw new IllegalArgumentException("Unknown permission: " + name);
5352            }
5353            ps = (PackageSetting) pkg.mExtras;
5354            if (ps == null
5355                    || filterAppAccessLPr(ps, callingUid, userId)) {
5356                throw new IllegalArgumentException("Unknown package: " + packageName);
5357            }
5358
5359            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5360
5361            // If a permission review is required for legacy apps we represent
5362            // their permissions as always granted runtime ones since we need
5363            // to keep the review required permission flag per user while an
5364            // install permission's state is shared across all users.
5365            if (mPermissionReviewRequired
5366                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5367                    && bp.isRuntime()) {
5368                return;
5369            }
5370
5371            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5372
5373            final PermissionsState permissionsState = ps.getPermissionsState();
5374
5375            final int flags = permissionsState.getPermissionFlags(name, userId);
5376            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5377                throw new SecurityException("Cannot grant system fixed permission "
5378                        + name + " for package " + packageName);
5379            }
5380            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5381                throw new SecurityException("Cannot grant policy fixed permission "
5382                        + name + " for package " + packageName);
5383            }
5384
5385            if (bp.isDevelopment()) {
5386                // Development permissions must be handled specially, since they are not
5387                // normal runtime permissions.  For now they apply to all users.
5388                if (permissionsState.grantInstallPermission(bp) !=
5389                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5390                    scheduleWriteSettingsLocked();
5391                }
5392                return;
5393            }
5394
5395            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5396                throw new SecurityException("Cannot grant non-ephemeral permission"
5397                        + name + " for package " + packageName);
5398            }
5399
5400            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5401                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5402                return;
5403            }
5404
5405            final int result = permissionsState.grantRuntimePermission(bp, userId);
5406            switch (result) {
5407                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5408                    return;
5409                }
5410
5411                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5412                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5413                    mHandler.post(new Runnable() {
5414                        @Override
5415                        public void run() {
5416                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5417                        }
5418                    });
5419                }
5420                break;
5421            }
5422
5423            if (bp.isRuntime()) {
5424                logPermissionGranted(mContext, name, packageName);
5425            }
5426
5427            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5428
5429            // Not critical if that is lost - app has to request again.
5430            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5431        }
5432
5433        // Only need to do this if user is initialized. Otherwise it's a new user
5434        // and there are no processes running as the user yet and there's no need
5435        // to make an expensive call to remount processes for the changed permissions.
5436        if (READ_EXTERNAL_STORAGE.equals(name)
5437                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5438            final long token = Binder.clearCallingIdentity();
5439            try {
5440                if (sUserManager.isInitialized(userId)) {
5441                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5442                            StorageManagerInternal.class);
5443                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5444                }
5445            } finally {
5446                Binder.restoreCallingIdentity(token);
5447            }
5448        }
5449    }
5450
5451    @Override
5452    public void revokeRuntimePermission(String packageName, String name, int userId) {
5453        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5454    }
5455
5456    private void revokeRuntimePermission(String packageName, String name, int userId,
5457            boolean overridePolicy) {
5458        if (!sUserManager.exists(userId)) {
5459            Log.e(TAG, "No such user:" + userId);
5460            return;
5461        }
5462
5463        mContext.enforceCallingOrSelfPermission(
5464                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5465                "revokeRuntimePermission");
5466
5467        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5468                true /* requireFullPermission */, true /* checkShell */,
5469                "revokeRuntimePermission");
5470
5471        final int appId;
5472
5473        synchronized (mPackages) {
5474            final PackageParser.Package pkg = mPackages.get(packageName);
5475            if (pkg == null) {
5476                throw new IllegalArgumentException("Unknown package: " + packageName);
5477            }
5478            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5479            if (ps == null
5480                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5481                throw new IllegalArgumentException("Unknown package: " + packageName);
5482            }
5483            final BasePermission bp = mSettings.mPermissions.get(name);
5484            if (bp == null) {
5485                throw new IllegalArgumentException("Unknown permission: " + name);
5486            }
5487
5488            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5489
5490            // If a permission review is required for legacy apps we represent
5491            // their permissions as always granted runtime ones since we need
5492            // to keep the review required permission flag per user while an
5493            // install permission's state is shared across all users.
5494            if (mPermissionReviewRequired
5495                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5496                    && bp.isRuntime()) {
5497                return;
5498            }
5499
5500            final PermissionsState permissionsState = ps.getPermissionsState();
5501
5502            final int flags = permissionsState.getPermissionFlags(name, userId);
5503            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5504                throw new SecurityException("Cannot revoke system fixed permission "
5505                        + name + " for package " + packageName);
5506            }
5507            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5508                throw new SecurityException("Cannot revoke policy fixed permission "
5509                        + name + " for package " + packageName);
5510            }
5511
5512            if (bp.isDevelopment()) {
5513                // Development permissions must be handled specially, since they are not
5514                // normal runtime permissions.  For now they apply to all users.
5515                if (permissionsState.revokeInstallPermission(bp) !=
5516                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5517                    scheduleWriteSettingsLocked();
5518                }
5519                return;
5520            }
5521
5522            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5523                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5524                return;
5525            }
5526
5527            if (bp.isRuntime()) {
5528                logPermissionRevoked(mContext, name, packageName);
5529            }
5530
5531            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5532
5533            // Critical, after this call app should never have the permission.
5534            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5535
5536            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5537        }
5538
5539        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5540    }
5541
5542    /**
5543     * Get the first event id for the permission.
5544     *
5545     * <p>There are four events for each permission: <ul>
5546     *     <li>Request permission: first id + 0</li>
5547     *     <li>Grant permission: first id + 1</li>
5548     *     <li>Request for permission denied: first id + 2</li>
5549     *     <li>Revoke permission: first id + 3</li>
5550     * </ul></p>
5551     *
5552     * @param name name of the permission
5553     *
5554     * @return The first event id for the permission
5555     */
5556    private static int getBaseEventId(@NonNull String name) {
5557        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5558
5559        if (eventIdIndex == -1) {
5560            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5561                    || Build.IS_USER) {
5562                Log.i(TAG, "Unknown permission " + name);
5563
5564                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5565            } else {
5566                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5567                //
5568                // Also update
5569                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5570                // - metrics_constants.proto
5571                throw new IllegalStateException("Unknown permission " + name);
5572            }
5573        }
5574
5575        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5576    }
5577
5578    /**
5579     * Log that a permission was revoked.
5580     *
5581     * @param context Context of the caller
5582     * @param name name of the permission
5583     * @param packageName package permission if for
5584     */
5585    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5586            @NonNull String packageName) {
5587        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5588    }
5589
5590    /**
5591     * Log that a permission request was granted.
5592     *
5593     * @param context Context of the caller
5594     * @param name name of the permission
5595     * @param packageName package permission if for
5596     */
5597    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5598            @NonNull String packageName) {
5599        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5600    }
5601
5602    @Override
5603    public void resetRuntimePermissions() {
5604        mContext.enforceCallingOrSelfPermission(
5605                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5606                "revokeRuntimePermission");
5607
5608        int callingUid = Binder.getCallingUid();
5609        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5610            mContext.enforceCallingOrSelfPermission(
5611                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5612                    "resetRuntimePermissions");
5613        }
5614
5615        synchronized (mPackages) {
5616            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5617            for (int userId : UserManagerService.getInstance().getUserIds()) {
5618                final int packageCount = mPackages.size();
5619                for (int i = 0; i < packageCount; i++) {
5620                    PackageParser.Package pkg = mPackages.valueAt(i);
5621                    if (!(pkg.mExtras instanceof PackageSetting)) {
5622                        continue;
5623                    }
5624                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5625                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5626                }
5627            }
5628        }
5629    }
5630
5631    @Override
5632    public int getPermissionFlags(String name, String packageName, int userId) {
5633        if (!sUserManager.exists(userId)) {
5634            return 0;
5635        }
5636
5637        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5638
5639        final int callingUid = Binder.getCallingUid();
5640        enforceCrossUserPermission(callingUid, userId,
5641                true /* requireFullPermission */, false /* checkShell */,
5642                "getPermissionFlags");
5643
5644        synchronized (mPackages) {
5645            final PackageParser.Package pkg = mPackages.get(packageName);
5646            if (pkg == null) {
5647                return 0;
5648            }
5649            final BasePermission bp = mSettings.mPermissions.get(name);
5650            if (bp == null) {
5651                return 0;
5652            }
5653            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5654            if (ps == null
5655                    || filterAppAccessLPr(ps, callingUid, userId)) {
5656                return 0;
5657            }
5658            PermissionsState permissionsState = ps.getPermissionsState();
5659            return permissionsState.getPermissionFlags(name, userId);
5660        }
5661    }
5662
5663    @Override
5664    public void updatePermissionFlags(String name, String packageName, int flagMask,
5665            int flagValues, int userId) {
5666        if (!sUserManager.exists(userId)) {
5667            return;
5668        }
5669
5670        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5671
5672        final int callingUid = Binder.getCallingUid();
5673        enforceCrossUserPermission(callingUid, userId,
5674                true /* requireFullPermission */, true /* checkShell */,
5675                "updatePermissionFlags");
5676
5677        // Only the system can change these flags and nothing else.
5678        if (getCallingUid() != Process.SYSTEM_UID) {
5679            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5680            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5681            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5682            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5683            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5684        }
5685
5686        synchronized (mPackages) {
5687            final PackageParser.Package pkg = mPackages.get(packageName);
5688            if (pkg == null) {
5689                throw new IllegalArgumentException("Unknown package: " + packageName);
5690            }
5691            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5692            if (ps == null
5693                    || filterAppAccessLPr(ps, callingUid, userId)) {
5694                throw new IllegalArgumentException("Unknown package: " + packageName);
5695            }
5696
5697            final BasePermission bp = mSettings.mPermissions.get(name);
5698            if (bp == null) {
5699                throw new IllegalArgumentException("Unknown permission: " + name);
5700            }
5701
5702            PermissionsState permissionsState = ps.getPermissionsState();
5703
5704            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5705
5706            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5707                // Install and runtime permissions are stored in different places,
5708                // so figure out what permission changed and persist the change.
5709                if (permissionsState.getInstallPermissionState(name) != null) {
5710                    scheduleWriteSettingsLocked();
5711                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5712                        || hadState) {
5713                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5714                }
5715            }
5716        }
5717    }
5718
5719    /**
5720     * Update the permission flags for all packages and runtime permissions of a user in order
5721     * to allow device or profile owner to remove POLICY_FIXED.
5722     */
5723    @Override
5724    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5725        if (!sUserManager.exists(userId)) {
5726            return;
5727        }
5728
5729        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5730
5731        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5732                true /* requireFullPermission */, true /* checkShell */,
5733                "updatePermissionFlagsForAllApps");
5734
5735        // Only the system can change system fixed flags.
5736        if (getCallingUid() != Process.SYSTEM_UID) {
5737            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5738            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5739        }
5740
5741        synchronized (mPackages) {
5742            boolean changed = false;
5743            final int packageCount = mPackages.size();
5744            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5745                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5746                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5747                if (ps == null) {
5748                    continue;
5749                }
5750                PermissionsState permissionsState = ps.getPermissionsState();
5751                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5752                        userId, flagMask, flagValues);
5753            }
5754            if (changed) {
5755                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5756            }
5757        }
5758    }
5759
5760    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5761        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5762                != PackageManager.PERMISSION_GRANTED
5763            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5764                != PackageManager.PERMISSION_GRANTED) {
5765            throw new SecurityException(message + " requires "
5766                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5767                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5768        }
5769    }
5770
5771    @Override
5772    public boolean shouldShowRequestPermissionRationale(String permissionName,
5773            String packageName, int userId) {
5774        if (UserHandle.getCallingUserId() != userId) {
5775            mContext.enforceCallingPermission(
5776                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5777                    "canShowRequestPermissionRationale for user " + userId);
5778        }
5779
5780        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5781        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5782            return false;
5783        }
5784
5785        if (checkPermission(permissionName, packageName, userId)
5786                == PackageManager.PERMISSION_GRANTED) {
5787            return false;
5788        }
5789
5790        final int flags;
5791
5792        final long identity = Binder.clearCallingIdentity();
5793        try {
5794            flags = getPermissionFlags(permissionName,
5795                    packageName, userId);
5796        } finally {
5797            Binder.restoreCallingIdentity(identity);
5798        }
5799
5800        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5801                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5802                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5803
5804        if ((flags & fixedFlags) != 0) {
5805            return false;
5806        }
5807
5808        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5809    }
5810
5811    @Override
5812    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5813        mContext.enforceCallingOrSelfPermission(
5814                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5815                "addOnPermissionsChangeListener");
5816
5817        synchronized (mPackages) {
5818            mOnPermissionChangeListeners.addListenerLocked(listener);
5819        }
5820    }
5821
5822    @Override
5823    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5824        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5825            throw new SecurityException("Instant applications don't have access to this method");
5826        }
5827        synchronized (mPackages) {
5828            mOnPermissionChangeListeners.removeListenerLocked(listener);
5829        }
5830    }
5831
5832    @Override
5833    public boolean isProtectedBroadcast(String actionName) {
5834        // allow instant applications
5835        synchronized (mProtectedBroadcasts) {
5836            if (mProtectedBroadcasts.contains(actionName)) {
5837                return true;
5838            } else if (actionName != null) {
5839                // TODO: remove these terrible hacks
5840                if (actionName.startsWith("android.net.netmon.lingerExpired")
5841                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5842                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5843                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5844                    return true;
5845                }
5846            }
5847        }
5848        return false;
5849    }
5850
5851    @Override
5852    public int checkSignatures(String pkg1, String pkg2) {
5853        synchronized (mPackages) {
5854            final PackageParser.Package p1 = mPackages.get(pkg1);
5855            final PackageParser.Package p2 = mPackages.get(pkg2);
5856            if (p1 == null || p1.mExtras == null
5857                    || p2 == null || p2.mExtras == null) {
5858                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5859            }
5860            final int callingUid = Binder.getCallingUid();
5861            final int callingUserId = UserHandle.getUserId(callingUid);
5862            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5863            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5864            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5865                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5866                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5867            }
5868            return compareSignatures(p1.mSignatures, p2.mSignatures);
5869        }
5870    }
5871
5872    @Override
5873    public int checkUidSignatures(int uid1, int uid2) {
5874        final int callingUid = Binder.getCallingUid();
5875        final int callingUserId = UserHandle.getUserId(callingUid);
5876        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5877        // Map to base uids.
5878        uid1 = UserHandle.getAppId(uid1);
5879        uid2 = UserHandle.getAppId(uid2);
5880        // reader
5881        synchronized (mPackages) {
5882            Signature[] s1;
5883            Signature[] s2;
5884            Object obj = mSettings.getUserIdLPr(uid1);
5885            if (obj != null) {
5886                if (obj instanceof SharedUserSetting) {
5887                    if (isCallerInstantApp) {
5888                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5889                    }
5890                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5891                } else if (obj instanceof PackageSetting) {
5892                    final PackageSetting ps = (PackageSetting) obj;
5893                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5894                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5895                    }
5896                    s1 = ps.signatures.mSignatures;
5897                } else {
5898                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5899                }
5900            } else {
5901                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5902            }
5903            obj = mSettings.getUserIdLPr(uid2);
5904            if (obj != null) {
5905                if (obj instanceof SharedUserSetting) {
5906                    if (isCallerInstantApp) {
5907                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5908                    }
5909                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5910                } else if (obj instanceof PackageSetting) {
5911                    final PackageSetting ps = (PackageSetting) obj;
5912                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5913                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5914                    }
5915                    s2 = ps.signatures.mSignatures;
5916                } else {
5917                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5918                }
5919            } else {
5920                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5921            }
5922            return compareSignatures(s1, s2);
5923        }
5924    }
5925
5926    /**
5927     * This method should typically only be used when granting or revoking
5928     * permissions, since the app may immediately restart after this call.
5929     * <p>
5930     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5931     * guard your work against the app being relaunched.
5932     */
5933    private void killUid(int appId, int userId, String reason) {
5934        final long identity = Binder.clearCallingIdentity();
5935        try {
5936            IActivityManager am = ActivityManager.getService();
5937            if (am != null) {
5938                try {
5939                    am.killUid(appId, userId, reason);
5940                } catch (RemoteException e) {
5941                    /* ignore - same process */
5942                }
5943            }
5944        } finally {
5945            Binder.restoreCallingIdentity(identity);
5946        }
5947    }
5948
5949    /**
5950     * Compares two sets of signatures. Returns:
5951     * <br />
5952     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5953     * <br />
5954     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5955     * <br />
5956     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5957     * <br />
5958     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5959     * <br />
5960     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5961     */
5962    static int compareSignatures(Signature[] s1, Signature[] s2) {
5963        if (s1 == null) {
5964            return s2 == null
5965                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5966                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5967        }
5968
5969        if (s2 == null) {
5970            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5971        }
5972
5973        if (s1.length != s2.length) {
5974            return PackageManager.SIGNATURE_NO_MATCH;
5975        }
5976
5977        // Since both signature sets are of size 1, we can compare without HashSets.
5978        if (s1.length == 1) {
5979            return s1[0].equals(s2[0]) ?
5980                    PackageManager.SIGNATURE_MATCH :
5981                    PackageManager.SIGNATURE_NO_MATCH;
5982        }
5983
5984        ArraySet<Signature> set1 = new ArraySet<Signature>();
5985        for (Signature sig : s1) {
5986            set1.add(sig);
5987        }
5988        ArraySet<Signature> set2 = new ArraySet<Signature>();
5989        for (Signature sig : s2) {
5990            set2.add(sig);
5991        }
5992        // Make sure s2 contains all signatures in s1.
5993        if (set1.equals(set2)) {
5994            return PackageManager.SIGNATURE_MATCH;
5995        }
5996        return PackageManager.SIGNATURE_NO_MATCH;
5997    }
5998
5999    /**
6000     * If the database version for this type of package (internal storage or
6001     * external storage) is less than the version where package signatures
6002     * were updated, return true.
6003     */
6004    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6005        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6006        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6007    }
6008
6009    /**
6010     * Used for backward compatibility to make sure any packages with
6011     * certificate chains get upgraded to the new style. {@code existingSigs}
6012     * will be in the old format (since they were stored on disk from before the
6013     * system upgrade) and {@code scannedSigs} will be in the newer format.
6014     */
6015    private int compareSignaturesCompat(PackageSignatures existingSigs,
6016            PackageParser.Package scannedPkg) {
6017        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6018            return PackageManager.SIGNATURE_NO_MATCH;
6019        }
6020
6021        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6022        for (Signature sig : existingSigs.mSignatures) {
6023            existingSet.add(sig);
6024        }
6025        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6026        for (Signature sig : scannedPkg.mSignatures) {
6027            try {
6028                Signature[] chainSignatures = sig.getChainSignatures();
6029                for (Signature chainSig : chainSignatures) {
6030                    scannedCompatSet.add(chainSig);
6031                }
6032            } catch (CertificateEncodingException e) {
6033                scannedCompatSet.add(sig);
6034            }
6035        }
6036        /*
6037         * Make sure the expanded scanned set contains all signatures in the
6038         * existing one.
6039         */
6040        if (scannedCompatSet.equals(existingSet)) {
6041            // Migrate the old signatures to the new scheme.
6042            existingSigs.assignSignatures(scannedPkg.mSignatures);
6043            // The new KeySets will be re-added later in the scanning process.
6044            synchronized (mPackages) {
6045                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6046            }
6047            return PackageManager.SIGNATURE_MATCH;
6048        }
6049        return PackageManager.SIGNATURE_NO_MATCH;
6050    }
6051
6052    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6053        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6054        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6055    }
6056
6057    private int compareSignaturesRecover(PackageSignatures existingSigs,
6058            PackageParser.Package scannedPkg) {
6059        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6060            return PackageManager.SIGNATURE_NO_MATCH;
6061        }
6062
6063        String msg = null;
6064        try {
6065            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6066                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6067                        + scannedPkg.packageName);
6068                return PackageManager.SIGNATURE_MATCH;
6069            }
6070        } catch (CertificateException e) {
6071            msg = e.getMessage();
6072        }
6073
6074        logCriticalInfo(Log.INFO,
6075                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6076        return PackageManager.SIGNATURE_NO_MATCH;
6077    }
6078
6079    @Override
6080    public List<String> getAllPackages() {
6081        final int callingUid = Binder.getCallingUid();
6082        final int callingUserId = UserHandle.getUserId(callingUid);
6083        synchronized (mPackages) {
6084            if (canViewInstantApps(callingUid, callingUserId)) {
6085                return new ArrayList<String>(mPackages.keySet());
6086            }
6087            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6088            final List<String> result = new ArrayList<>();
6089            if (instantAppPkgName != null) {
6090                // caller is an instant application; filter unexposed applications
6091                for (PackageParser.Package pkg : mPackages.values()) {
6092                    if (!pkg.visibleToInstantApps) {
6093                        continue;
6094                    }
6095                    result.add(pkg.packageName);
6096                }
6097            } else {
6098                // caller is a normal application; filter instant applications
6099                for (PackageParser.Package pkg : mPackages.values()) {
6100                    final PackageSetting ps =
6101                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6102                    if (ps != null
6103                            && ps.getInstantApp(callingUserId)
6104                            && !mInstantAppRegistry.isInstantAccessGranted(
6105                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6106                        continue;
6107                    }
6108                    result.add(pkg.packageName);
6109                }
6110            }
6111            return result;
6112        }
6113    }
6114
6115    @Override
6116    public String[] getPackagesForUid(int uid) {
6117        final int callingUid = Binder.getCallingUid();
6118        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6119        final int userId = UserHandle.getUserId(uid);
6120        uid = UserHandle.getAppId(uid);
6121        // reader
6122        synchronized (mPackages) {
6123            Object obj = mSettings.getUserIdLPr(uid);
6124            if (obj instanceof SharedUserSetting) {
6125                if (isCallerInstantApp) {
6126                    return null;
6127                }
6128                final SharedUserSetting sus = (SharedUserSetting) obj;
6129                final int N = sus.packages.size();
6130                String[] res = new String[N];
6131                final Iterator<PackageSetting> it = sus.packages.iterator();
6132                int i = 0;
6133                while (it.hasNext()) {
6134                    PackageSetting ps = it.next();
6135                    if (ps.getInstalled(userId)) {
6136                        res[i++] = ps.name;
6137                    } else {
6138                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6139                    }
6140                }
6141                return res;
6142            } else if (obj instanceof PackageSetting) {
6143                final PackageSetting ps = (PackageSetting) obj;
6144                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6145                    return new String[]{ps.name};
6146                }
6147            }
6148        }
6149        return null;
6150    }
6151
6152    @Override
6153    public String getNameForUid(int uid) {
6154        final int callingUid = Binder.getCallingUid();
6155        if (getInstantAppPackageName(callingUid) != null) {
6156            return null;
6157        }
6158        synchronized (mPackages) {
6159            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6160            if (obj instanceof SharedUserSetting) {
6161                final SharedUserSetting sus = (SharedUserSetting) obj;
6162                return sus.name + ":" + sus.userId;
6163            } else if (obj instanceof PackageSetting) {
6164                final PackageSetting ps = (PackageSetting) obj;
6165                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6166                    return null;
6167                }
6168                return ps.name;
6169            }
6170        }
6171        return null;
6172    }
6173
6174    @Override
6175    public int getUidForSharedUser(String sharedUserName) {
6176        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6177            return -1;
6178        }
6179        if (sharedUserName == null) {
6180            return -1;
6181        }
6182        // reader
6183        synchronized (mPackages) {
6184            SharedUserSetting suid;
6185            try {
6186                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6187                if (suid != null) {
6188                    return suid.userId;
6189                }
6190            } catch (PackageManagerException ignore) {
6191                // can't happen, but, still need to catch it
6192            }
6193            return -1;
6194        }
6195    }
6196
6197    @Override
6198    public int getFlagsForUid(int uid) {
6199        final int callingUid = Binder.getCallingUid();
6200        if (getInstantAppPackageName(callingUid) != null) {
6201            return 0;
6202        }
6203        synchronized (mPackages) {
6204            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6205            if (obj instanceof SharedUserSetting) {
6206                final SharedUserSetting sus = (SharedUserSetting) obj;
6207                return sus.pkgFlags;
6208            } else if (obj instanceof PackageSetting) {
6209                final PackageSetting ps = (PackageSetting) obj;
6210                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6211                    return 0;
6212                }
6213                return ps.pkgFlags;
6214            }
6215        }
6216        return 0;
6217    }
6218
6219    @Override
6220    public int getPrivateFlagsForUid(int uid) {
6221        final int callingUid = Binder.getCallingUid();
6222        if (getInstantAppPackageName(callingUid) != null) {
6223            return 0;
6224        }
6225        synchronized (mPackages) {
6226            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6227            if (obj instanceof SharedUserSetting) {
6228                final SharedUserSetting sus = (SharedUserSetting) obj;
6229                return sus.pkgPrivateFlags;
6230            } else if (obj instanceof PackageSetting) {
6231                final PackageSetting ps = (PackageSetting) obj;
6232                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6233                    return 0;
6234                }
6235                return ps.pkgPrivateFlags;
6236            }
6237        }
6238        return 0;
6239    }
6240
6241    @Override
6242    public boolean isUidPrivileged(int uid) {
6243        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6244            return false;
6245        }
6246        uid = UserHandle.getAppId(uid);
6247        // reader
6248        synchronized (mPackages) {
6249            Object obj = mSettings.getUserIdLPr(uid);
6250            if (obj instanceof SharedUserSetting) {
6251                final SharedUserSetting sus = (SharedUserSetting) obj;
6252                final Iterator<PackageSetting> it = sus.packages.iterator();
6253                while (it.hasNext()) {
6254                    if (it.next().isPrivileged()) {
6255                        return true;
6256                    }
6257                }
6258            } else if (obj instanceof PackageSetting) {
6259                final PackageSetting ps = (PackageSetting) obj;
6260                return ps.isPrivileged();
6261            }
6262        }
6263        return false;
6264    }
6265
6266    @Override
6267    public String[] getAppOpPermissionPackages(String permissionName) {
6268        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6269            return null;
6270        }
6271        synchronized (mPackages) {
6272            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6273            if (pkgs == null) {
6274                return null;
6275            }
6276            return pkgs.toArray(new String[pkgs.size()]);
6277        }
6278    }
6279
6280    @Override
6281    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6282            int flags, int userId) {
6283        return resolveIntentInternal(
6284                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6285    }
6286
6287    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6288            int flags, int userId, boolean resolveForStart) {
6289        try {
6290            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6291
6292            if (!sUserManager.exists(userId)) return null;
6293            final int callingUid = Binder.getCallingUid();
6294            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6295            enforceCrossUserPermission(callingUid, userId,
6296                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6297
6298            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6299            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6300                    flags, callingUid, userId, resolveForStart);
6301            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6302
6303            final ResolveInfo bestChoice =
6304                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6305            return bestChoice;
6306        } finally {
6307            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6308        }
6309    }
6310
6311    @Override
6312    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6313        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6314            throw new SecurityException(
6315                    "findPersistentPreferredActivity can only be run by the system");
6316        }
6317        if (!sUserManager.exists(userId)) {
6318            return null;
6319        }
6320        final int callingUid = Binder.getCallingUid();
6321        intent = updateIntentForResolve(intent);
6322        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6323        final int flags = updateFlagsForResolve(
6324                0, userId, intent, callingUid, false /*includeInstantApps*/);
6325        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6326                userId);
6327        synchronized (mPackages) {
6328            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6329                    userId);
6330        }
6331    }
6332
6333    @Override
6334    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6335            IntentFilter filter, int match, ComponentName activity) {
6336        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6337            return;
6338        }
6339        final int userId = UserHandle.getCallingUserId();
6340        if (DEBUG_PREFERRED) {
6341            Log.v(TAG, "setLastChosenActivity intent=" + intent
6342                + " resolvedType=" + resolvedType
6343                + " flags=" + flags
6344                + " filter=" + filter
6345                + " match=" + match
6346                + " activity=" + activity);
6347            filter.dump(new PrintStreamPrinter(System.out), "    ");
6348        }
6349        intent.setComponent(null);
6350        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6351                userId);
6352        // Find any earlier preferred or last chosen entries and nuke them
6353        findPreferredActivity(intent, resolvedType,
6354                flags, query, 0, false, true, false, userId);
6355        // Add the new activity as the last chosen for this filter
6356        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6357                "Setting last chosen");
6358    }
6359
6360    @Override
6361    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6362        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6363            return null;
6364        }
6365        final int userId = UserHandle.getCallingUserId();
6366        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6367        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6368                userId);
6369        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6370                false, false, false, userId);
6371    }
6372
6373    /**
6374     * Returns whether or not instant apps have been disabled remotely.
6375     */
6376    private boolean isEphemeralDisabled() {
6377        return mEphemeralAppsDisabled;
6378    }
6379
6380    private boolean isInstantAppAllowed(
6381            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6382            boolean skipPackageCheck) {
6383        if (mInstantAppResolverConnection == null) {
6384            return false;
6385        }
6386        if (mInstantAppInstallerActivity == null) {
6387            return false;
6388        }
6389        if (intent.getComponent() != null) {
6390            return false;
6391        }
6392        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6393            return false;
6394        }
6395        if (!skipPackageCheck && intent.getPackage() != null) {
6396            return false;
6397        }
6398        final boolean isWebUri = hasWebURI(intent);
6399        if (!isWebUri || intent.getData().getHost() == null) {
6400            return false;
6401        }
6402        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6403        // Or if there's already an ephemeral app installed that handles the action
6404        synchronized (mPackages) {
6405            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6406            for (int n = 0; n < count; n++) {
6407                final ResolveInfo info = resolvedActivities.get(n);
6408                final String packageName = info.activityInfo.packageName;
6409                final PackageSetting ps = mSettings.mPackages.get(packageName);
6410                if (ps != null) {
6411                    // only check domain verification status if the app is not a browser
6412                    if (!info.handleAllWebDataURI) {
6413                        // Try to get the status from User settings first
6414                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6415                        final int status = (int) (packedStatus >> 32);
6416                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6417                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6418                            if (DEBUG_EPHEMERAL) {
6419                                Slog.v(TAG, "DENY instant app;"
6420                                    + " pkg: " + packageName + ", status: " + status);
6421                            }
6422                            return false;
6423                        }
6424                    }
6425                    if (ps.getInstantApp(userId)) {
6426                        if (DEBUG_EPHEMERAL) {
6427                            Slog.v(TAG, "DENY instant app installed;"
6428                                    + " pkg: " + packageName);
6429                        }
6430                        return false;
6431                    }
6432                }
6433            }
6434        }
6435        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6436        return true;
6437    }
6438
6439    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6440            Intent origIntent, String resolvedType, String callingPackage,
6441            Bundle verificationBundle, int userId) {
6442        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6443                new InstantAppRequest(responseObj, origIntent, resolvedType,
6444                        callingPackage, userId, verificationBundle));
6445        mHandler.sendMessage(msg);
6446    }
6447
6448    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6449            int flags, List<ResolveInfo> query, int userId) {
6450        if (query != null) {
6451            final int N = query.size();
6452            if (N == 1) {
6453                return query.get(0);
6454            } else if (N > 1) {
6455                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6456                // If there is more than one activity with the same priority,
6457                // then let the user decide between them.
6458                ResolveInfo r0 = query.get(0);
6459                ResolveInfo r1 = query.get(1);
6460                if (DEBUG_INTENT_MATCHING || debug) {
6461                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6462                            + r1.activityInfo.name + "=" + r1.priority);
6463                }
6464                // If the first activity has a higher priority, or a different
6465                // default, then it is always desirable to pick it.
6466                if (r0.priority != r1.priority
6467                        || r0.preferredOrder != r1.preferredOrder
6468                        || r0.isDefault != r1.isDefault) {
6469                    return query.get(0);
6470                }
6471                // If we have saved a preference for a preferred activity for
6472                // this Intent, use that.
6473                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6474                        flags, query, r0.priority, true, false, debug, userId);
6475                if (ri != null) {
6476                    return ri;
6477                }
6478                // If we have an ephemeral app, use it
6479                for (int i = 0; i < N; i++) {
6480                    ri = query.get(i);
6481                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6482                        final String packageName = ri.activityInfo.packageName;
6483                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6484                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6485                        final int status = (int)(packedStatus >> 32);
6486                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6487                            return ri;
6488                        }
6489                    }
6490                }
6491                ri = new ResolveInfo(mResolveInfo);
6492                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6493                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6494                // If all of the options come from the same package, show the application's
6495                // label and icon instead of the generic resolver's.
6496                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6497                // and then throw away the ResolveInfo itself, meaning that the caller loses
6498                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6499                // a fallback for this case; we only set the target package's resources on
6500                // the ResolveInfo, not the ActivityInfo.
6501                final String intentPackage = intent.getPackage();
6502                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6503                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6504                    ri.resolvePackageName = intentPackage;
6505                    if (userNeedsBadging(userId)) {
6506                        ri.noResourceId = true;
6507                    } else {
6508                        ri.icon = appi.icon;
6509                    }
6510                    ri.iconResourceId = appi.icon;
6511                    ri.labelRes = appi.labelRes;
6512                }
6513                ri.activityInfo.applicationInfo = new ApplicationInfo(
6514                        ri.activityInfo.applicationInfo);
6515                if (userId != 0) {
6516                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6517                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6518                }
6519                // Make sure that the resolver is displayable in car mode
6520                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6521                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6522                return ri;
6523            }
6524        }
6525        return null;
6526    }
6527
6528    /**
6529     * Return true if the given list is not empty and all of its contents have
6530     * an activityInfo with the given package name.
6531     */
6532    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6533        if (ArrayUtils.isEmpty(list)) {
6534            return false;
6535        }
6536        for (int i = 0, N = list.size(); i < N; i++) {
6537            final ResolveInfo ri = list.get(i);
6538            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6539            if (ai == null || !packageName.equals(ai.packageName)) {
6540                return false;
6541            }
6542        }
6543        return true;
6544    }
6545
6546    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6547            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6548        final int N = query.size();
6549        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6550                .get(userId);
6551        // Get the list of persistent preferred activities that handle the intent
6552        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6553        List<PersistentPreferredActivity> pprefs = ppir != null
6554                ? ppir.queryIntent(intent, resolvedType,
6555                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6556                        userId)
6557                : null;
6558        if (pprefs != null && pprefs.size() > 0) {
6559            final int M = pprefs.size();
6560            for (int i=0; i<M; i++) {
6561                final PersistentPreferredActivity ppa = pprefs.get(i);
6562                if (DEBUG_PREFERRED || debug) {
6563                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6564                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6565                            + "\n  component=" + ppa.mComponent);
6566                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6567                }
6568                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6569                        flags | MATCH_DISABLED_COMPONENTS, userId);
6570                if (DEBUG_PREFERRED || debug) {
6571                    Slog.v(TAG, "Found persistent preferred activity:");
6572                    if (ai != null) {
6573                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6574                    } else {
6575                        Slog.v(TAG, "  null");
6576                    }
6577                }
6578                if (ai == null) {
6579                    // This previously registered persistent preferred activity
6580                    // component is no longer known. Ignore it and do NOT remove it.
6581                    continue;
6582                }
6583                for (int j=0; j<N; j++) {
6584                    final ResolveInfo ri = query.get(j);
6585                    if (!ri.activityInfo.applicationInfo.packageName
6586                            .equals(ai.applicationInfo.packageName)) {
6587                        continue;
6588                    }
6589                    if (!ri.activityInfo.name.equals(ai.name)) {
6590                        continue;
6591                    }
6592                    //  Found a persistent preference that can handle the intent.
6593                    if (DEBUG_PREFERRED || debug) {
6594                        Slog.v(TAG, "Returning persistent preferred activity: " +
6595                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6596                    }
6597                    return ri;
6598                }
6599            }
6600        }
6601        return null;
6602    }
6603
6604    // TODO: handle preferred activities missing while user has amnesia
6605    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6606            List<ResolveInfo> query, int priority, boolean always,
6607            boolean removeMatches, boolean debug, int userId) {
6608        if (!sUserManager.exists(userId)) return null;
6609        final int callingUid = Binder.getCallingUid();
6610        flags = updateFlagsForResolve(
6611                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6612        intent = updateIntentForResolve(intent);
6613        // writer
6614        synchronized (mPackages) {
6615            // Try to find a matching persistent preferred activity.
6616            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6617                    debug, userId);
6618
6619            // If a persistent preferred activity matched, use it.
6620            if (pri != null) {
6621                return pri;
6622            }
6623
6624            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6625            // Get the list of preferred activities that handle the intent
6626            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6627            List<PreferredActivity> prefs = pir != null
6628                    ? pir.queryIntent(intent, resolvedType,
6629                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6630                            userId)
6631                    : null;
6632            if (prefs != null && prefs.size() > 0) {
6633                boolean changed = false;
6634                try {
6635                    // First figure out how good the original match set is.
6636                    // We will only allow preferred activities that came
6637                    // from the same match quality.
6638                    int match = 0;
6639
6640                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6641
6642                    final int N = query.size();
6643                    for (int j=0; j<N; j++) {
6644                        final ResolveInfo ri = query.get(j);
6645                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6646                                + ": 0x" + Integer.toHexString(match));
6647                        if (ri.match > match) {
6648                            match = ri.match;
6649                        }
6650                    }
6651
6652                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6653                            + Integer.toHexString(match));
6654
6655                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6656                    final int M = prefs.size();
6657                    for (int i=0; i<M; i++) {
6658                        final PreferredActivity pa = prefs.get(i);
6659                        if (DEBUG_PREFERRED || debug) {
6660                            Slog.v(TAG, "Checking PreferredActivity ds="
6661                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6662                                    + "\n  component=" + pa.mPref.mComponent);
6663                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6664                        }
6665                        if (pa.mPref.mMatch != match) {
6666                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6667                                    + Integer.toHexString(pa.mPref.mMatch));
6668                            continue;
6669                        }
6670                        // If it's not an "always" type preferred activity and that's what we're
6671                        // looking for, skip it.
6672                        if (always && !pa.mPref.mAlways) {
6673                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6674                            continue;
6675                        }
6676                        final ActivityInfo ai = getActivityInfo(
6677                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6678                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6679                                userId);
6680                        if (DEBUG_PREFERRED || debug) {
6681                            Slog.v(TAG, "Found preferred activity:");
6682                            if (ai != null) {
6683                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6684                            } else {
6685                                Slog.v(TAG, "  null");
6686                            }
6687                        }
6688                        if (ai == null) {
6689                            // This previously registered preferred activity
6690                            // component is no longer known.  Most likely an update
6691                            // to the app was installed and in the new version this
6692                            // component no longer exists.  Clean it up by removing
6693                            // it from the preferred activities list, and skip it.
6694                            Slog.w(TAG, "Removing dangling preferred activity: "
6695                                    + pa.mPref.mComponent);
6696                            pir.removeFilter(pa);
6697                            changed = true;
6698                            continue;
6699                        }
6700                        for (int j=0; j<N; j++) {
6701                            final ResolveInfo ri = query.get(j);
6702                            if (!ri.activityInfo.applicationInfo.packageName
6703                                    .equals(ai.applicationInfo.packageName)) {
6704                                continue;
6705                            }
6706                            if (!ri.activityInfo.name.equals(ai.name)) {
6707                                continue;
6708                            }
6709
6710                            if (removeMatches) {
6711                                pir.removeFilter(pa);
6712                                changed = true;
6713                                if (DEBUG_PREFERRED) {
6714                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6715                                }
6716                                break;
6717                            }
6718
6719                            // Okay we found a previously set preferred or last chosen app.
6720                            // If the result set is different from when this
6721                            // was created, we need to clear it and re-ask the
6722                            // user their preference, if we're looking for an "always" type entry.
6723                            if (always && !pa.mPref.sameSet(query)) {
6724                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6725                                        + intent + " type " + resolvedType);
6726                                if (DEBUG_PREFERRED) {
6727                                    Slog.v(TAG, "Removing preferred activity since set changed "
6728                                            + pa.mPref.mComponent);
6729                                }
6730                                pir.removeFilter(pa);
6731                                // Re-add the filter as a "last chosen" entry (!always)
6732                                PreferredActivity lastChosen = new PreferredActivity(
6733                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6734                                pir.addFilter(lastChosen);
6735                                changed = true;
6736                                return null;
6737                            }
6738
6739                            // Yay! Either the set matched or we're looking for the last chosen
6740                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6741                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6742                            return ri;
6743                        }
6744                    }
6745                } finally {
6746                    if (changed) {
6747                        if (DEBUG_PREFERRED) {
6748                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6749                        }
6750                        scheduleWritePackageRestrictionsLocked(userId);
6751                    }
6752                }
6753            }
6754        }
6755        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6756        return null;
6757    }
6758
6759    /*
6760     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6761     */
6762    @Override
6763    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6764            int targetUserId) {
6765        mContext.enforceCallingOrSelfPermission(
6766                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6767        List<CrossProfileIntentFilter> matches =
6768                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6769        if (matches != null) {
6770            int size = matches.size();
6771            for (int i = 0; i < size; i++) {
6772                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6773            }
6774        }
6775        if (hasWebURI(intent)) {
6776            // cross-profile app linking works only towards the parent.
6777            final int callingUid = Binder.getCallingUid();
6778            final UserInfo parent = getProfileParent(sourceUserId);
6779            synchronized(mPackages) {
6780                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6781                        false /*includeInstantApps*/);
6782                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6783                        intent, resolvedType, flags, sourceUserId, parent.id);
6784                return xpDomainInfo != null;
6785            }
6786        }
6787        return false;
6788    }
6789
6790    private UserInfo getProfileParent(int userId) {
6791        final long identity = Binder.clearCallingIdentity();
6792        try {
6793            return sUserManager.getProfileParent(userId);
6794        } finally {
6795            Binder.restoreCallingIdentity(identity);
6796        }
6797    }
6798
6799    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6800            String resolvedType, int userId) {
6801        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6802        if (resolver != null) {
6803            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6804        }
6805        return null;
6806    }
6807
6808    @Override
6809    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6810            String resolvedType, int flags, int userId) {
6811        try {
6812            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6813
6814            return new ParceledListSlice<>(
6815                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6816        } finally {
6817            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6818        }
6819    }
6820
6821    /**
6822     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6823     * instant, returns {@code null}.
6824     */
6825    private String getInstantAppPackageName(int callingUid) {
6826        synchronized (mPackages) {
6827            // If the caller is an isolated app use the owner's uid for the lookup.
6828            if (Process.isIsolated(callingUid)) {
6829                callingUid = mIsolatedOwners.get(callingUid);
6830            }
6831            final int appId = UserHandle.getAppId(callingUid);
6832            final Object obj = mSettings.getUserIdLPr(appId);
6833            if (obj instanceof PackageSetting) {
6834                final PackageSetting ps = (PackageSetting) obj;
6835                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6836                return isInstantApp ? ps.pkg.packageName : null;
6837            }
6838        }
6839        return null;
6840    }
6841
6842    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6843            String resolvedType, int flags, int userId) {
6844        return queryIntentActivitiesInternal(
6845                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6846    }
6847
6848    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6849            String resolvedType, int flags, int filterCallingUid, int userId,
6850            boolean resolveForStart) {
6851        if (!sUserManager.exists(userId)) return Collections.emptyList();
6852        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6853        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6854                false /* requireFullPermission */, false /* checkShell */,
6855                "query intent activities");
6856        final String pkgName = intent.getPackage();
6857        ComponentName comp = intent.getComponent();
6858        if (comp == null) {
6859            if (intent.getSelector() != null) {
6860                intent = intent.getSelector();
6861                comp = intent.getComponent();
6862            }
6863        }
6864
6865        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6866                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6867        if (comp != null) {
6868            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6869            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6870            if (ai != null) {
6871                // When specifying an explicit component, we prevent the activity from being
6872                // used when either 1) the calling package is normal and the activity is within
6873                // an ephemeral application or 2) the calling package is ephemeral and the
6874                // activity is not visible to ephemeral applications.
6875                final boolean matchInstantApp =
6876                        (flags & PackageManager.MATCH_INSTANT) != 0;
6877                final boolean matchVisibleToInstantAppOnly =
6878                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6879                final boolean matchExplicitlyVisibleOnly =
6880                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6881                final boolean isCallerInstantApp =
6882                        instantAppPkgName != null;
6883                final boolean isTargetSameInstantApp =
6884                        comp.getPackageName().equals(instantAppPkgName);
6885                final boolean isTargetInstantApp =
6886                        (ai.applicationInfo.privateFlags
6887                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6888                final boolean isTargetVisibleToInstantApp =
6889                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6890                final boolean isTargetExplicitlyVisibleToInstantApp =
6891                        isTargetVisibleToInstantApp
6892                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6893                final boolean isTargetHiddenFromInstantApp =
6894                        !isTargetVisibleToInstantApp
6895                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6896                final boolean blockResolution =
6897                        !isTargetSameInstantApp
6898                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6899                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6900                                        && isTargetHiddenFromInstantApp));
6901                if (!blockResolution) {
6902                    final ResolveInfo ri = new ResolveInfo();
6903                    ri.activityInfo = ai;
6904                    list.add(ri);
6905                }
6906            }
6907            return applyPostResolutionFilter(list, instantAppPkgName);
6908        }
6909
6910        // reader
6911        boolean sortResult = false;
6912        boolean addEphemeral = false;
6913        List<ResolveInfo> result;
6914        final boolean ephemeralDisabled = isEphemeralDisabled();
6915        synchronized (mPackages) {
6916            if (pkgName == null) {
6917                List<CrossProfileIntentFilter> matchingFilters =
6918                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6919                // Check for results that need to skip the current profile.
6920                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6921                        resolvedType, flags, userId);
6922                if (xpResolveInfo != null) {
6923                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6924                    xpResult.add(xpResolveInfo);
6925                    return applyPostResolutionFilter(
6926                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6927                }
6928
6929                // Check for results in the current profile.
6930                result = filterIfNotSystemUser(mActivities.queryIntent(
6931                        intent, resolvedType, flags, userId), userId);
6932                addEphemeral = !ephemeralDisabled
6933                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6934                // Check for cross profile results.
6935                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6936                xpResolveInfo = queryCrossProfileIntents(
6937                        matchingFilters, intent, resolvedType, flags, userId,
6938                        hasNonNegativePriorityResult);
6939                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6940                    boolean isVisibleToUser = filterIfNotSystemUser(
6941                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6942                    if (isVisibleToUser) {
6943                        result.add(xpResolveInfo);
6944                        sortResult = true;
6945                    }
6946                }
6947                if (hasWebURI(intent)) {
6948                    CrossProfileDomainInfo xpDomainInfo = null;
6949                    final UserInfo parent = getProfileParent(userId);
6950                    if (parent != null) {
6951                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6952                                flags, userId, parent.id);
6953                    }
6954                    if (xpDomainInfo != null) {
6955                        if (xpResolveInfo != null) {
6956                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6957                            // in the result.
6958                            result.remove(xpResolveInfo);
6959                        }
6960                        if (result.size() == 0 && !addEphemeral) {
6961                            // No result in current profile, but found candidate in parent user.
6962                            // And we are not going to add emphemeral app, so we can return the
6963                            // result straight away.
6964                            result.add(xpDomainInfo.resolveInfo);
6965                            return applyPostResolutionFilter(result, instantAppPkgName);
6966                        }
6967                    } else if (result.size() <= 1 && !addEphemeral) {
6968                        // No result in parent user and <= 1 result in current profile, and we
6969                        // are not going to add emphemeral app, so we can return the result without
6970                        // further processing.
6971                        return applyPostResolutionFilter(result, instantAppPkgName);
6972                    }
6973                    // We have more than one candidate (combining results from current and parent
6974                    // profile), so we need filtering and sorting.
6975                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6976                            intent, flags, result, xpDomainInfo, userId);
6977                    sortResult = true;
6978                }
6979            } else {
6980                final PackageParser.Package pkg = mPackages.get(pkgName);
6981                result = null;
6982                if (pkg != null) {
6983                    result = filterIfNotSystemUser(
6984                            mActivities.queryIntentForPackage(
6985                                    intent, resolvedType, flags, pkg.activities, userId),
6986                            userId);
6987                }
6988                if (result == null || result.size() == 0) {
6989                    // the caller wants to resolve for a particular package; however, there
6990                    // were no installed results, so, try to find an ephemeral result
6991                    addEphemeral = !ephemeralDisabled
6992                            && isInstantAppAllowed(
6993                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6994                    if (result == null) {
6995                        result = new ArrayList<>();
6996                    }
6997                }
6998            }
6999        }
7000        if (addEphemeral) {
7001            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7002        }
7003        if (sortResult) {
7004            Collections.sort(result, mResolvePrioritySorter);
7005        }
7006        return applyPostResolutionFilter(result, instantAppPkgName);
7007    }
7008
7009    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7010            String resolvedType, int flags, int userId) {
7011        // first, check to see if we've got an instant app already installed
7012        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7013        ResolveInfo localInstantApp = null;
7014        boolean blockResolution = false;
7015        if (!alreadyResolvedLocally) {
7016            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7017                    flags
7018                        | PackageManager.GET_RESOLVED_FILTER
7019                        | PackageManager.MATCH_INSTANT
7020                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7021                    userId);
7022            for (int i = instantApps.size() - 1; i >= 0; --i) {
7023                final ResolveInfo info = instantApps.get(i);
7024                final String packageName = info.activityInfo.packageName;
7025                final PackageSetting ps = mSettings.mPackages.get(packageName);
7026                if (ps.getInstantApp(userId)) {
7027                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7028                    final int status = (int)(packedStatus >> 32);
7029                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7030                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7031                        // there's a local instant application installed, but, the user has
7032                        // chosen to never use it; skip resolution and don't acknowledge
7033                        // an instant application is even available
7034                        if (DEBUG_EPHEMERAL) {
7035                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7036                        }
7037                        blockResolution = true;
7038                        break;
7039                    } else {
7040                        // we have a locally installed instant application; skip resolution
7041                        // but acknowledge there's an instant application available
7042                        if (DEBUG_EPHEMERAL) {
7043                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7044                        }
7045                        localInstantApp = info;
7046                        break;
7047                    }
7048                }
7049            }
7050        }
7051        // no app installed, let's see if one's available
7052        AuxiliaryResolveInfo auxiliaryResponse = null;
7053        if (!blockResolution) {
7054            if (localInstantApp == null) {
7055                // we don't have an instant app locally, resolve externally
7056                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7057                final InstantAppRequest requestObject = new InstantAppRequest(
7058                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7059                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7060                auxiliaryResponse =
7061                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7062                                mContext, mInstantAppResolverConnection, requestObject);
7063                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7064            } else {
7065                // we have an instant application locally, but, we can't admit that since
7066                // callers shouldn't be able to determine prior browsing. create a dummy
7067                // auxiliary response so the downstream code behaves as if there's an
7068                // instant application available externally. when it comes time to start
7069                // the instant application, we'll do the right thing.
7070                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7071                auxiliaryResponse = new AuxiliaryResolveInfo(
7072                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7073            }
7074        }
7075        if (auxiliaryResponse != null) {
7076            if (DEBUG_EPHEMERAL) {
7077                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7078            }
7079            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7080            final PackageSetting ps =
7081                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7082            if (ps != null) {
7083                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7084                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7085                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7086                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7087                // make sure this resolver is the default
7088                ephemeralInstaller.isDefault = true;
7089                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7090                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7091                // add a non-generic filter
7092                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7093                ephemeralInstaller.filter.addDataPath(
7094                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7095                ephemeralInstaller.isInstantAppAvailable = true;
7096                result.add(ephemeralInstaller);
7097            }
7098        }
7099        return result;
7100    }
7101
7102    private static class CrossProfileDomainInfo {
7103        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7104        ResolveInfo resolveInfo;
7105        /* Best domain verification status of the activities found in the other profile */
7106        int bestDomainVerificationStatus;
7107    }
7108
7109    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7110            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7111        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7112                sourceUserId)) {
7113            return null;
7114        }
7115        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7116                resolvedType, flags, parentUserId);
7117
7118        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7119            return null;
7120        }
7121        CrossProfileDomainInfo result = null;
7122        int size = resultTargetUser.size();
7123        for (int i = 0; i < size; i++) {
7124            ResolveInfo riTargetUser = resultTargetUser.get(i);
7125            // Intent filter verification is only for filters that specify a host. So don't return
7126            // those that handle all web uris.
7127            if (riTargetUser.handleAllWebDataURI) {
7128                continue;
7129            }
7130            String packageName = riTargetUser.activityInfo.packageName;
7131            PackageSetting ps = mSettings.mPackages.get(packageName);
7132            if (ps == null) {
7133                continue;
7134            }
7135            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7136            int status = (int)(verificationState >> 32);
7137            if (result == null) {
7138                result = new CrossProfileDomainInfo();
7139                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7140                        sourceUserId, parentUserId);
7141                result.bestDomainVerificationStatus = status;
7142            } else {
7143                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7144                        result.bestDomainVerificationStatus);
7145            }
7146        }
7147        // Don't consider matches with status NEVER across profiles.
7148        if (result != null && result.bestDomainVerificationStatus
7149                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7150            return null;
7151        }
7152        return result;
7153    }
7154
7155    /**
7156     * Verification statuses are ordered from the worse to the best, except for
7157     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7158     */
7159    private int bestDomainVerificationStatus(int status1, int status2) {
7160        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7161            return status2;
7162        }
7163        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7164            return status1;
7165        }
7166        return (int) MathUtils.max(status1, status2);
7167    }
7168
7169    private boolean isUserEnabled(int userId) {
7170        long callingId = Binder.clearCallingIdentity();
7171        try {
7172            UserInfo userInfo = sUserManager.getUserInfo(userId);
7173            return userInfo != null && userInfo.isEnabled();
7174        } finally {
7175            Binder.restoreCallingIdentity(callingId);
7176        }
7177    }
7178
7179    /**
7180     * Filter out activities with systemUserOnly flag set, when current user is not System.
7181     *
7182     * @return filtered list
7183     */
7184    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7185        if (userId == UserHandle.USER_SYSTEM) {
7186            return resolveInfos;
7187        }
7188        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7189            ResolveInfo info = resolveInfos.get(i);
7190            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7191                resolveInfos.remove(i);
7192            }
7193        }
7194        return resolveInfos;
7195    }
7196
7197    /**
7198     * Filters out ephemeral activities.
7199     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7200     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7201     *
7202     * @param resolveInfos The pre-filtered list of resolved activities
7203     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7204     *          is performed.
7205     * @return A filtered list of resolved activities.
7206     */
7207    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7208            String ephemeralPkgName) {
7209        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7210            final ResolveInfo info = resolveInfos.get(i);
7211            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7212            // TODO: When adding on-demand split support for non-instant apps, remove this check
7213            // and always apply post filtering
7214            // allow activities that are defined in the provided package
7215            if (isEphemeralApp) {
7216                if (info.activityInfo.splitName != null
7217                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7218                                info.activityInfo.splitName)) {
7219                    // requested activity is defined in a split that hasn't been installed yet.
7220                    // add the installer to the resolve list
7221                    if (DEBUG_EPHEMERAL) {
7222                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7223                    }
7224                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7225                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7226                            info.activityInfo.packageName, info.activityInfo.splitName,
7227                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7228                    // make sure this resolver is the default
7229                    installerInfo.isDefault = true;
7230                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7231                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7232                    // add a non-generic filter
7233                    installerInfo.filter = new IntentFilter();
7234                    // load resources from the correct package
7235                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7236                    resolveInfos.set(i, installerInfo);
7237                    continue;
7238                }
7239            }
7240            // caller is a full app, don't need to apply any other filtering
7241            if (ephemeralPkgName == null) {
7242                continue;
7243            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7244                // caller is same app; don't need to apply any other filtering
7245                continue;
7246            }
7247            // allow activities that have been explicitly exposed to ephemeral apps
7248            if (!isEphemeralApp
7249                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7250                continue;
7251            }
7252            resolveInfos.remove(i);
7253        }
7254        return resolveInfos;
7255    }
7256
7257    /**
7258     * @param resolveInfos list of resolve infos in descending priority order
7259     * @return if the list contains a resolve info with non-negative priority
7260     */
7261    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7262        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7263    }
7264
7265    private static boolean hasWebURI(Intent intent) {
7266        if (intent.getData() == null) {
7267            return false;
7268        }
7269        final String scheme = intent.getScheme();
7270        if (TextUtils.isEmpty(scheme)) {
7271            return false;
7272        }
7273        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7274    }
7275
7276    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7277            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7278            int userId) {
7279        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7280
7281        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7282            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7283                    candidates.size());
7284        }
7285
7286        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7287        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7288        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7289        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7290        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7291        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7292
7293        synchronized (mPackages) {
7294            final int count = candidates.size();
7295            // First, try to use linked apps. Partition the candidates into four lists:
7296            // one for the final results, one for the "do not use ever", one for "undefined status"
7297            // and finally one for "browser app type".
7298            for (int n=0; n<count; n++) {
7299                ResolveInfo info = candidates.get(n);
7300                String packageName = info.activityInfo.packageName;
7301                PackageSetting ps = mSettings.mPackages.get(packageName);
7302                if (ps != null) {
7303                    // Add to the special match all list (Browser use case)
7304                    if (info.handleAllWebDataURI) {
7305                        matchAllList.add(info);
7306                        continue;
7307                    }
7308                    // Try to get the status from User settings first
7309                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7310                    int status = (int)(packedStatus >> 32);
7311                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7312                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7313                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7314                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7315                                    + " : linkgen=" + linkGeneration);
7316                        }
7317                        // Use link-enabled generation as preferredOrder, i.e.
7318                        // prefer newly-enabled over earlier-enabled.
7319                        info.preferredOrder = linkGeneration;
7320                        alwaysList.add(info);
7321                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7322                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7323                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7324                        }
7325                        neverList.add(info);
7326                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7327                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7328                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7329                        }
7330                        alwaysAskList.add(info);
7331                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7332                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7333                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7334                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7335                        }
7336                        undefinedList.add(info);
7337                    }
7338                }
7339            }
7340
7341            // We'll want to include browser possibilities in a few cases
7342            boolean includeBrowser = false;
7343
7344            // First try to add the "always" resolution(s) for the current user, if any
7345            if (alwaysList.size() > 0) {
7346                result.addAll(alwaysList);
7347            } else {
7348                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7349                result.addAll(undefinedList);
7350                // Maybe add one for the other profile.
7351                if (xpDomainInfo != null && (
7352                        xpDomainInfo.bestDomainVerificationStatus
7353                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7354                    result.add(xpDomainInfo.resolveInfo);
7355                }
7356                includeBrowser = true;
7357            }
7358
7359            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7360            // If there were 'always' entries their preferred order has been set, so we also
7361            // back that off to make the alternatives equivalent
7362            if (alwaysAskList.size() > 0) {
7363                for (ResolveInfo i : result) {
7364                    i.preferredOrder = 0;
7365                }
7366                result.addAll(alwaysAskList);
7367                includeBrowser = true;
7368            }
7369
7370            if (includeBrowser) {
7371                // Also add browsers (all of them or only the default one)
7372                if (DEBUG_DOMAIN_VERIFICATION) {
7373                    Slog.v(TAG, "   ...including browsers in candidate set");
7374                }
7375                if ((matchFlags & MATCH_ALL) != 0) {
7376                    result.addAll(matchAllList);
7377                } else {
7378                    // Browser/generic handling case.  If there's a default browser, go straight
7379                    // to that (but only if there is no other higher-priority match).
7380                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7381                    int maxMatchPrio = 0;
7382                    ResolveInfo defaultBrowserMatch = null;
7383                    final int numCandidates = matchAllList.size();
7384                    for (int n = 0; n < numCandidates; n++) {
7385                        ResolveInfo info = matchAllList.get(n);
7386                        // track the highest overall match priority...
7387                        if (info.priority > maxMatchPrio) {
7388                            maxMatchPrio = info.priority;
7389                        }
7390                        // ...and the highest-priority default browser match
7391                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7392                            if (defaultBrowserMatch == null
7393                                    || (defaultBrowserMatch.priority < info.priority)) {
7394                                if (debug) {
7395                                    Slog.v(TAG, "Considering default browser match " + info);
7396                                }
7397                                defaultBrowserMatch = info;
7398                            }
7399                        }
7400                    }
7401                    if (defaultBrowserMatch != null
7402                            && defaultBrowserMatch.priority >= maxMatchPrio
7403                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7404                    {
7405                        if (debug) {
7406                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7407                        }
7408                        result.add(defaultBrowserMatch);
7409                    } else {
7410                        result.addAll(matchAllList);
7411                    }
7412                }
7413
7414                // If there is nothing selected, add all candidates and remove the ones that the user
7415                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7416                if (result.size() == 0) {
7417                    result.addAll(candidates);
7418                    result.removeAll(neverList);
7419                }
7420            }
7421        }
7422        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7423            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7424                    result.size());
7425            for (ResolveInfo info : result) {
7426                Slog.v(TAG, "  + " + info.activityInfo);
7427            }
7428        }
7429        return result;
7430    }
7431
7432    // Returns a packed value as a long:
7433    //
7434    // high 'int'-sized word: link status: undefined/ask/never/always.
7435    // low 'int'-sized word: relative priority among 'always' results.
7436    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7437        long result = ps.getDomainVerificationStatusForUser(userId);
7438        // if none available, get the master status
7439        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7440            if (ps.getIntentFilterVerificationInfo() != null) {
7441                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7442            }
7443        }
7444        return result;
7445    }
7446
7447    private ResolveInfo querySkipCurrentProfileIntents(
7448            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7449            int flags, int sourceUserId) {
7450        if (matchingFilters != null) {
7451            int size = matchingFilters.size();
7452            for (int i = 0; i < size; i ++) {
7453                CrossProfileIntentFilter filter = matchingFilters.get(i);
7454                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7455                    // Checking if there are activities in the target user that can handle the
7456                    // intent.
7457                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7458                            resolvedType, flags, sourceUserId);
7459                    if (resolveInfo != null) {
7460                        return resolveInfo;
7461                    }
7462                }
7463            }
7464        }
7465        return null;
7466    }
7467
7468    // Return matching ResolveInfo in target user if any.
7469    private ResolveInfo queryCrossProfileIntents(
7470            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7471            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7472        if (matchingFilters != null) {
7473            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7474            // match the same intent. For performance reasons, it is better not to
7475            // run queryIntent twice for the same userId
7476            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7477            int size = matchingFilters.size();
7478            for (int i = 0; i < size; i++) {
7479                CrossProfileIntentFilter filter = matchingFilters.get(i);
7480                int targetUserId = filter.getTargetUserId();
7481                boolean skipCurrentProfile =
7482                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7483                boolean skipCurrentProfileIfNoMatchFound =
7484                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7485                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7486                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7487                    // Checking if there are activities in the target user that can handle the
7488                    // intent.
7489                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7490                            resolvedType, flags, sourceUserId);
7491                    if (resolveInfo != null) return resolveInfo;
7492                    alreadyTriedUserIds.put(targetUserId, true);
7493                }
7494            }
7495        }
7496        return null;
7497    }
7498
7499    /**
7500     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7501     * will forward the intent to the filter's target user.
7502     * Otherwise, returns null.
7503     */
7504    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7505            String resolvedType, int flags, int sourceUserId) {
7506        int targetUserId = filter.getTargetUserId();
7507        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7508                resolvedType, flags, targetUserId);
7509        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7510            // If all the matches in the target profile are suspended, return null.
7511            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7512                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7513                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7514                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7515                            targetUserId);
7516                }
7517            }
7518        }
7519        return null;
7520    }
7521
7522    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7523            int sourceUserId, int targetUserId) {
7524        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7525        long ident = Binder.clearCallingIdentity();
7526        boolean targetIsProfile;
7527        try {
7528            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7529        } finally {
7530            Binder.restoreCallingIdentity(ident);
7531        }
7532        String className;
7533        if (targetIsProfile) {
7534            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7535        } else {
7536            className = FORWARD_INTENT_TO_PARENT;
7537        }
7538        ComponentName forwardingActivityComponentName = new ComponentName(
7539                mAndroidApplication.packageName, className);
7540        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7541                sourceUserId);
7542        if (!targetIsProfile) {
7543            forwardingActivityInfo.showUserIcon = targetUserId;
7544            forwardingResolveInfo.noResourceId = true;
7545        }
7546        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7547        forwardingResolveInfo.priority = 0;
7548        forwardingResolveInfo.preferredOrder = 0;
7549        forwardingResolveInfo.match = 0;
7550        forwardingResolveInfo.isDefault = true;
7551        forwardingResolveInfo.filter = filter;
7552        forwardingResolveInfo.targetUserId = targetUserId;
7553        return forwardingResolveInfo;
7554    }
7555
7556    @Override
7557    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7558            Intent[] specifics, String[] specificTypes, Intent intent,
7559            String resolvedType, int flags, int userId) {
7560        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7561                specificTypes, intent, resolvedType, flags, userId));
7562    }
7563
7564    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7565            Intent[] specifics, String[] specificTypes, Intent intent,
7566            String resolvedType, int flags, int userId) {
7567        if (!sUserManager.exists(userId)) return Collections.emptyList();
7568        final int callingUid = Binder.getCallingUid();
7569        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7570                false /*includeInstantApps*/);
7571        enforceCrossUserPermission(callingUid, userId,
7572                false /*requireFullPermission*/, false /*checkShell*/,
7573                "query intent activity options");
7574        final String resultsAction = intent.getAction();
7575
7576        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7577                | PackageManager.GET_RESOLVED_FILTER, userId);
7578
7579        if (DEBUG_INTENT_MATCHING) {
7580            Log.v(TAG, "Query " + intent + ": " + results);
7581        }
7582
7583        int specificsPos = 0;
7584        int N;
7585
7586        // todo: note that the algorithm used here is O(N^2).  This
7587        // isn't a problem in our current environment, but if we start running
7588        // into situations where we have more than 5 or 10 matches then this
7589        // should probably be changed to something smarter...
7590
7591        // First we go through and resolve each of the specific items
7592        // that were supplied, taking care of removing any corresponding
7593        // duplicate items in the generic resolve list.
7594        if (specifics != null) {
7595            for (int i=0; i<specifics.length; i++) {
7596                final Intent sintent = specifics[i];
7597                if (sintent == null) {
7598                    continue;
7599                }
7600
7601                if (DEBUG_INTENT_MATCHING) {
7602                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7603                }
7604
7605                String action = sintent.getAction();
7606                if (resultsAction != null && resultsAction.equals(action)) {
7607                    // If this action was explicitly requested, then don't
7608                    // remove things that have it.
7609                    action = null;
7610                }
7611
7612                ResolveInfo ri = null;
7613                ActivityInfo ai = null;
7614
7615                ComponentName comp = sintent.getComponent();
7616                if (comp == null) {
7617                    ri = resolveIntent(
7618                        sintent,
7619                        specificTypes != null ? specificTypes[i] : null,
7620                            flags, userId);
7621                    if (ri == null) {
7622                        continue;
7623                    }
7624                    if (ri == mResolveInfo) {
7625                        // ACK!  Must do something better with this.
7626                    }
7627                    ai = ri.activityInfo;
7628                    comp = new ComponentName(ai.applicationInfo.packageName,
7629                            ai.name);
7630                } else {
7631                    ai = getActivityInfo(comp, flags, userId);
7632                    if (ai == null) {
7633                        continue;
7634                    }
7635                }
7636
7637                // Look for any generic query activities that are duplicates
7638                // of this specific one, and remove them from the results.
7639                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7640                N = results.size();
7641                int j;
7642                for (j=specificsPos; j<N; j++) {
7643                    ResolveInfo sri = results.get(j);
7644                    if ((sri.activityInfo.name.equals(comp.getClassName())
7645                            && sri.activityInfo.applicationInfo.packageName.equals(
7646                                    comp.getPackageName()))
7647                        || (action != null && sri.filter.matchAction(action))) {
7648                        results.remove(j);
7649                        if (DEBUG_INTENT_MATCHING) Log.v(
7650                            TAG, "Removing duplicate item from " + j
7651                            + " due to specific " + specificsPos);
7652                        if (ri == null) {
7653                            ri = sri;
7654                        }
7655                        j--;
7656                        N--;
7657                    }
7658                }
7659
7660                // Add this specific item to its proper place.
7661                if (ri == null) {
7662                    ri = new ResolveInfo();
7663                    ri.activityInfo = ai;
7664                }
7665                results.add(specificsPos, ri);
7666                ri.specificIndex = i;
7667                specificsPos++;
7668            }
7669        }
7670
7671        // Now we go through the remaining generic results and remove any
7672        // duplicate actions that are found here.
7673        N = results.size();
7674        for (int i=specificsPos; i<N-1; i++) {
7675            final ResolveInfo rii = results.get(i);
7676            if (rii.filter == null) {
7677                continue;
7678            }
7679
7680            // Iterate over all of the actions of this result's intent
7681            // filter...  typically this should be just one.
7682            final Iterator<String> it = rii.filter.actionsIterator();
7683            if (it == null) {
7684                continue;
7685            }
7686            while (it.hasNext()) {
7687                final String action = it.next();
7688                if (resultsAction != null && resultsAction.equals(action)) {
7689                    // If this action was explicitly requested, then don't
7690                    // remove things that have it.
7691                    continue;
7692                }
7693                for (int j=i+1; j<N; j++) {
7694                    final ResolveInfo rij = results.get(j);
7695                    if (rij.filter != null && rij.filter.hasAction(action)) {
7696                        results.remove(j);
7697                        if (DEBUG_INTENT_MATCHING) Log.v(
7698                            TAG, "Removing duplicate item from " + j
7699                            + " due to action " + action + " at " + i);
7700                        j--;
7701                        N--;
7702                    }
7703                }
7704            }
7705
7706            // If the caller didn't request filter information, drop it now
7707            // so we don't have to marshall/unmarshall it.
7708            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7709                rii.filter = null;
7710            }
7711        }
7712
7713        // Filter out the caller activity if so requested.
7714        if (caller != null) {
7715            N = results.size();
7716            for (int i=0; i<N; i++) {
7717                ActivityInfo ainfo = results.get(i).activityInfo;
7718                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7719                        && caller.getClassName().equals(ainfo.name)) {
7720                    results.remove(i);
7721                    break;
7722                }
7723            }
7724        }
7725
7726        // If the caller didn't request filter information,
7727        // drop them now so we don't have to
7728        // marshall/unmarshall it.
7729        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7730            N = results.size();
7731            for (int i=0; i<N; i++) {
7732                results.get(i).filter = null;
7733            }
7734        }
7735
7736        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7737        return results;
7738    }
7739
7740    @Override
7741    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7742            String resolvedType, int flags, int userId) {
7743        return new ParceledListSlice<>(
7744                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7745    }
7746
7747    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7748            String resolvedType, int flags, int userId) {
7749        if (!sUserManager.exists(userId)) return Collections.emptyList();
7750        final int callingUid = Binder.getCallingUid();
7751        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7752        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7753                false /*includeInstantApps*/);
7754        ComponentName comp = intent.getComponent();
7755        if (comp == null) {
7756            if (intent.getSelector() != null) {
7757                intent = intent.getSelector();
7758                comp = intent.getComponent();
7759            }
7760        }
7761        if (comp != null) {
7762            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7763            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7764            if (ai != null) {
7765                // When specifying an explicit component, we prevent the activity from being
7766                // used when either 1) the calling package is normal and the activity is within
7767                // an instant application or 2) the calling package is ephemeral and the
7768                // activity is not visible to instant applications.
7769                final boolean matchInstantApp =
7770                        (flags & PackageManager.MATCH_INSTANT) != 0;
7771                final boolean matchVisibleToInstantAppOnly =
7772                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7773                final boolean matchExplicitlyVisibleOnly =
7774                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7775                final boolean isCallerInstantApp =
7776                        instantAppPkgName != null;
7777                final boolean isTargetSameInstantApp =
7778                        comp.getPackageName().equals(instantAppPkgName);
7779                final boolean isTargetInstantApp =
7780                        (ai.applicationInfo.privateFlags
7781                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7782                final boolean isTargetVisibleToInstantApp =
7783                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7784                final boolean isTargetExplicitlyVisibleToInstantApp =
7785                        isTargetVisibleToInstantApp
7786                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7787                final boolean isTargetHiddenFromInstantApp =
7788                        !isTargetVisibleToInstantApp
7789                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7790                final boolean blockResolution =
7791                        !isTargetSameInstantApp
7792                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7793                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7794                                        && isTargetHiddenFromInstantApp));
7795                if (!blockResolution) {
7796                    ResolveInfo ri = new ResolveInfo();
7797                    ri.activityInfo = ai;
7798                    list.add(ri);
7799                }
7800            }
7801            return applyPostResolutionFilter(list, instantAppPkgName);
7802        }
7803
7804        // reader
7805        synchronized (mPackages) {
7806            String pkgName = intent.getPackage();
7807            if (pkgName == null) {
7808                final List<ResolveInfo> result =
7809                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7810                return applyPostResolutionFilter(result, instantAppPkgName);
7811            }
7812            final PackageParser.Package pkg = mPackages.get(pkgName);
7813            if (pkg != null) {
7814                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7815                        intent, resolvedType, flags, pkg.receivers, userId);
7816                return applyPostResolutionFilter(result, instantAppPkgName);
7817            }
7818            return Collections.emptyList();
7819        }
7820    }
7821
7822    @Override
7823    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7824        final int callingUid = Binder.getCallingUid();
7825        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7826    }
7827
7828    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7829            int userId, int callingUid) {
7830        if (!sUserManager.exists(userId)) return null;
7831        flags = updateFlagsForResolve(
7832                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7833        List<ResolveInfo> query = queryIntentServicesInternal(
7834                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7835        if (query != null) {
7836            if (query.size() >= 1) {
7837                // If there is more than one service with the same priority,
7838                // just arbitrarily pick the first one.
7839                return query.get(0);
7840            }
7841        }
7842        return null;
7843    }
7844
7845    @Override
7846    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7847            String resolvedType, int flags, int userId) {
7848        final int callingUid = Binder.getCallingUid();
7849        return new ParceledListSlice<>(queryIntentServicesInternal(
7850                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7851    }
7852
7853    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7854            String resolvedType, int flags, int userId, int callingUid,
7855            boolean includeInstantApps) {
7856        if (!sUserManager.exists(userId)) return Collections.emptyList();
7857        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7858        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7859        ComponentName comp = intent.getComponent();
7860        if (comp == null) {
7861            if (intent.getSelector() != null) {
7862                intent = intent.getSelector();
7863                comp = intent.getComponent();
7864            }
7865        }
7866        if (comp != null) {
7867            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7868            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7869            if (si != null) {
7870                // When specifying an explicit component, we prevent the service from being
7871                // used when either 1) the service is in an instant application and the
7872                // caller is not the same instant application or 2) the calling package is
7873                // ephemeral and the activity is not visible to ephemeral applications.
7874                final boolean matchInstantApp =
7875                        (flags & PackageManager.MATCH_INSTANT) != 0;
7876                final boolean matchVisibleToInstantAppOnly =
7877                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7878                final boolean isCallerInstantApp =
7879                        instantAppPkgName != null;
7880                final boolean isTargetSameInstantApp =
7881                        comp.getPackageName().equals(instantAppPkgName);
7882                final boolean isTargetInstantApp =
7883                        (si.applicationInfo.privateFlags
7884                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7885                final boolean isTargetHiddenFromInstantApp =
7886                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7887                final boolean blockResolution =
7888                        !isTargetSameInstantApp
7889                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7890                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7891                                        && isTargetHiddenFromInstantApp));
7892                if (!blockResolution) {
7893                    final ResolveInfo ri = new ResolveInfo();
7894                    ri.serviceInfo = si;
7895                    list.add(ri);
7896                }
7897            }
7898            return list;
7899        }
7900
7901        // reader
7902        synchronized (mPackages) {
7903            String pkgName = intent.getPackage();
7904            if (pkgName == null) {
7905                return applyPostServiceResolutionFilter(
7906                        mServices.queryIntent(intent, resolvedType, flags, userId),
7907                        instantAppPkgName);
7908            }
7909            final PackageParser.Package pkg = mPackages.get(pkgName);
7910            if (pkg != null) {
7911                return applyPostServiceResolutionFilter(
7912                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7913                                userId),
7914                        instantAppPkgName);
7915            }
7916            return Collections.emptyList();
7917        }
7918    }
7919
7920    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7921            String instantAppPkgName) {
7922        // TODO: When adding on-demand split support for non-instant apps, remove this check
7923        // and always apply post filtering
7924        if (instantAppPkgName == null) {
7925            return resolveInfos;
7926        }
7927        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7928            final ResolveInfo info = resolveInfos.get(i);
7929            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7930            // allow services that are defined in the provided package
7931            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7932                if (info.serviceInfo.splitName != null
7933                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7934                                info.serviceInfo.splitName)) {
7935                    // requested service is defined in a split that hasn't been installed yet.
7936                    // add the installer to the resolve list
7937                    if (DEBUG_EPHEMERAL) {
7938                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7939                    }
7940                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7941                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7942                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7943                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7944                    // make sure this resolver is the default
7945                    installerInfo.isDefault = true;
7946                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7947                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7948                    // add a non-generic filter
7949                    installerInfo.filter = new IntentFilter();
7950                    // load resources from the correct package
7951                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7952                    resolveInfos.set(i, installerInfo);
7953                }
7954                continue;
7955            }
7956            // allow services that have been explicitly exposed to ephemeral apps
7957            if (!isEphemeralApp
7958                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7959                continue;
7960            }
7961            resolveInfos.remove(i);
7962        }
7963        return resolveInfos;
7964    }
7965
7966    @Override
7967    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7968            String resolvedType, int flags, int userId) {
7969        return new ParceledListSlice<>(
7970                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7971    }
7972
7973    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7974            Intent intent, String resolvedType, int flags, int userId) {
7975        if (!sUserManager.exists(userId)) return Collections.emptyList();
7976        final int callingUid = Binder.getCallingUid();
7977        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7978        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7979                false /*includeInstantApps*/);
7980        ComponentName comp = intent.getComponent();
7981        if (comp == null) {
7982            if (intent.getSelector() != null) {
7983                intent = intent.getSelector();
7984                comp = intent.getComponent();
7985            }
7986        }
7987        if (comp != null) {
7988            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7989            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7990            if (pi != null) {
7991                // When specifying an explicit component, we prevent the provider from being
7992                // used when either 1) the provider is in an instant application and the
7993                // caller is not the same instant application or 2) the calling package is an
7994                // instant application and the provider is not visible to instant applications.
7995                final boolean matchInstantApp =
7996                        (flags & PackageManager.MATCH_INSTANT) != 0;
7997                final boolean matchVisibleToInstantAppOnly =
7998                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7999                final boolean isCallerInstantApp =
8000                        instantAppPkgName != null;
8001                final boolean isTargetSameInstantApp =
8002                        comp.getPackageName().equals(instantAppPkgName);
8003                final boolean isTargetInstantApp =
8004                        (pi.applicationInfo.privateFlags
8005                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8006                final boolean isTargetHiddenFromInstantApp =
8007                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8008                final boolean blockResolution =
8009                        !isTargetSameInstantApp
8010                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8011                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8012                                        && isTargetHiddenFromInstantApp));
8013                if (!blockResolution) {
8014                    final ResolveInfo ri = new ResolveInfo();
8015                    ri.providerInfo = pi;
8016                    list.add(ri);
8017                }
8018            }
8019            return list;
8020        }
8021
8022        // reader
8023        synchronized (mPackages) {
8024            String pkgName = intent.getPackage();
8025            if (pkgName == null) {
8026                return applyPostContentProviderResolutionFilter(
8027                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8028                        instantAppPkgName);
8029            }
8030            final PackageParser.Package pkg = mPackages.get(pkgName);
8031            if (pkg != null) {
8032                return applyPostContentProviderResolutionFilter(
8033                        mProviders.queryIntentForPackage(
8034                        intent, resolvedType, flags, pkg.providers, userId),
8035                        instantAppPkgName);
8036            }
8037            return Collections.emptyList();
8038        }
8039    }
8040
8041    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8042            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8043        // TODO: When adding on-demand split support for non-instant applications, remove
8044        // this check and always apply post filtering
8045        if (instantAppPkgName == null) {
8046            return resolveInfos;
8047        }
8048        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8049            final ResolveInfo info = resolveInfos.get(i);
8050            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8051            // allow providers that are defined in the provided package
8052            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8053                if (info.providerInfo.splitName != null
8054                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8055                                info.providerInfo.splitName)) {
8056                    // requested provider is defined in a split that hasn't been installed yet.
8057                    // add the installer to the resolve list
8058                    if (DEBUG_EPHEMERAL) {
8059                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8060                    }
8061                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8062                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8063                            info.providerInfo.packageName, info.providerInfo.splitName,
8064                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8065                    // make sure this resolver is the default
8066                    installerInfo.isDefault = true;
8067                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8068                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8069                    // add a non-generic filter
8070                    installerInfo.filter = new IntentFilter();
8071                    // load resources from the correct package
8072                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8073                    resolveInfos.set(i, installerInfo);
8074                }
8075                continue;
8076            }
8077            // allow providers that have been explicitly exposed to instant applications
8078            if (!isEphemeralApp
8079                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8080                continue;
8081            }
8082            resolveInfos.remove(i);
8083        }
8084        return resolveInfos;
8085    }
8086
8087    @Override
8088    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8089        final int callingUid = Binder.getCallingUid();
8090        if (getInstantAppPackageName(callingUid) != null) {
8091            return ParceledListSlice.emptyList();
8092        }
8093        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8094        flags = updateFlagsForPackage(flags, userId, null);
8095        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8096        enforceCrossUserPermission(callingUid, userId,
8097                true /* requireFullPermission */, false /* checkShell */,
8098                "get installed packages");
8099
8100        // writer
8101        synchronized (mPackages) {
8102            ArrayList<PackageInfo> list;
8103            if (listUninstalled) {
8104                list = new ArrayList<>(mSettings.mPackages.size());
8105                for (PackageSetting ps : mSettings.mPackages.values()) {
8106                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8107                        continue;
8108                    }
8109                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8110                        return null;
8111                    }
8112                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8113                    if (pi != null) {
8114                        list.add(pi);
8115                    }
8116                }
8117            } else {
8118                list = new ArrayList<>(mPackages.size());
8119                for (PackageParser.Package p : mPackages.values()) {
8120                    final PackageSetting ps = (PackageSetting) p.mExtras;
8121                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8122                        continue;
8123                    }
8124                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8125                        return null;
8126                    }
8127                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8128                            p.mExtras, flags, userId);
8129                    if (pi != null) {
8130                        list.add(pi);
8131                    }
8132                }
8133            }
8134
8135            return new ParceledListSlice<>(list);
8136        }
8137    }
8138
8139    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8140            String[] permissions, boolean[] tmp, int flags, int userId) {
8141        int numMatch = 0;
8142        final PermissionsState permissionsState = ps.getPermissionsState();
8143        for (int i=0; i<permissions.length; i++) {
8144            final String permission = permissions[i];
8145            if (permissionsState.hasPermission(permission, userId)) {
8146                tmp[i] = true;
8147                numMatch++;
8148            } else {
8149                tmp[i] = false;
8150            }
8151        }
8152        if (numMatch == 0) {
8153            return;
8154        }
8155        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8156
8157        // The above might return null in cases of uninstalled apps or install-state
8158        // skew across users/profiles.
8159        if (pi != null) {
8160            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8161                if (numMatch == permissions.length) {
8162                    pi.requestedPermissions = permissions;
8163                } else {
8164                    pi.requestedPermissions = new String[numMatch];
8165                    numMatch = 0;
8166                    for (int i=0; i<permissions.length; i++) {
8167                        if (tmp[i]) {
8168                            pi.requestedPermissions[numMatch] = permissions[i];
8169                            numMatch++;
8170                        }
8171                    }
8172                }
8173            }
8174            list.add(pi);
8175        }
8176    }
8177
8178    @Override
8179    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8180            String[] permissions, int flags, int userId) {
8181        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8182        flags = updateFlagsForPackage(flags, userId, permissions);
8183        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8184                true /* requireFullPermission */, false /* checkShell */,
8185                "get packages holding permissions");
8186        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8187
8188        // writer
8189        synchronized (mPackages) {
8190            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8191            boolean[] tmpBools = new boolean[permissions.length];
8192            if (listUninstalled) {
8193                for (PackageSetting ps : mSettings.mPackages.values()) {
8194                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8195                            userId);
8196                }
8197            } else {
8198                for (PackageParser.Package pkg : mPackages.values()) {
8199                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8200                    if (ps != null) {
8201                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8202                                userId);
8203                    }
8204                }
8205            }
8206
8207            return new ParceledListSlice<PackageInfo>(list);
8208        }
8209    }
8210
8211    @Override
8212    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8213        final int callingUid = Binder.getCallingUid();
8214        if (getInstantAppPackageName(callingUid) != null) {
8215            return ParceledListSlice.emptyList();
8216        }
8217        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8218        flags = updateFlagsForApplication(flags, userId, null);
8219        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8220
8221        // writer
8222        synchronized (mPackages) {
8223            ArrayList<ApplicationInfo> list;
8224            if (listUninstalled) {
8225                list = new ArrayList<>(mSettings.mPackages.size());
8226                for (PackageSetting ps : mSettings.mPackages.values()) {
8227                    ApplicationInfo ai;
8228                    int effectiveFlags = flags;
8229                    if (ps.isSystem()) {
8230                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8231                    }
8232                    if (ps.pkg != null) {
8233                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8234                            continue;
8235                        }
8236                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8237                            return null;
8238                        }
8239                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8240                                ps.readUserState(userId), userId);
8241                        if (ai != null) {
8242                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8243                        }
8244                    } else {
8245                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8246                        // and already converts to externally visible package name
8247                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8248                                callingUid, effectiveFlags, userId);
8249                    }
8250                    if (ai != null) {
8251                        list.add(ai);
8252                    }
8253                }
8254            } else {
8255                list = new ArrayList<>(mPackages.size());
8256                for (PackageParser.Package p : mPackages.values()) {
8257                    if (p.mExtras != null) {
8258                        PackageSetting ps = (PackageSetting) p.mExtras;
8259                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8260                            continue;
8261                        }
8262                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8263                            return null;
8264                        }
8265                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8266                                ps.readUserState(userId), userId);
8267                        if (ai != null) {
8268                            ai.packageName = resolveExternalPackageNameLPr(p);
8269                            list.add(ai);
8270                        }
8271                    }
8272                }
8273            }
8274
8275            return new ParceledListSlice<>(list);
8276        }
8277    }
8278
8279    @Override
8280    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8281        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8282            return null;
8283        }
8284        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8285                "getEphemeralApplications");
8286        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8287                true /* requireFullPermission */, false /* checkShell */,
8288                "getEphemeralApplications");
8289        synchronized (mPackages) {
8290            List<InstantAppInfo> instantApps = mInstantAppRegistry
8291                    .getInstantAppsLPr(userId);
8292            if (instantApps != null) {
8293                return new ParceledListSlice<>(instantApps);
8294            }
8295        }
8296        return null;
8297    }
8298
8299    @Override
8300    public boolean isInstantApp(String packageName, int userId) {
8301        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8302                true /* requireFullPermission */, false /* checkShell */,
8303                "isInstantApp");
8304        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8305            return false;
8306        }
8307
8308        synchronized (mPackages) {
8309            int callingUid = Binder.getCallingUid();
8310            if (Process.isIsolated(callingUid)) {
8311                callingUid = mIsolatedOwners.get(callingUid);
8312            }
8313            final PackageSetting ps = mSettings.mPackages.get(packageName);
8314            PackageParser.Package pkg = mPackages.get(packageName);
8315            final boolean returnAllowed =
8316                    ps != null
8317                    && (isCallerSameApp(packageName, callingUid)
8318                            || canViewInstantApps(callingUid, userId)
8319                            || mInstantAppRegistry.isInstantAccessGranted(
8320                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8321            if (returnAllowed) {
8322                return ps.getInstantApp(userId);
8323            }
8324        }
8325        return false;
8326    }
8327
8328    @Override
8329    public byte[] getInstantAppCookie(String packageName, int userId) {
8330        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8331            return null;
8332        }
8333
8334        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8335                true /* requireFullPermission */, false /* checkShell */,
8336                "getInstantAppCookie");
8337        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8338            return null;
8339        }
8340        synchronized (mPackages) {
8341            return mInstantAppRegistry.getInstantAppCookieLPw(
8342                    packageName, userId);
8343        }
8344    }
8345
8346    @Override
8347    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8348        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8349            return true;
8350        }
8351
8352        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8353                true /* requireFullPermission */, true /* checkShell */,
8354                "setInstantAppCookie");
8355        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8356            return false;
8357        }
8358        synchronized (mPackages) {
8359            return mInstantAppRegistry.setInstantAppCookieLPw(
8360                    packageName, cookie, userId);
8361        }
8362    }
8363
8364    @Override
8365    public Bitmap getInstantAppIcon(String packageName, int userId) {
8366        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8367            return null;
8368        }
8369
8370        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8371                "getInstantAppIcon");
8372
8373        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8374                true /* requireFullPermission */, false /* checkShell */,
8375                "getInstantAppIcon");
8376
8377        synchronized (mPackages) {
8378            return mInstantAppRegistry.getInstantAppIconLPw(
8379                    packageName, userId);
8380        }
8381    }
8382
8383    private boolean isCallerSameApp(String packageName, int uid) {
8384        PackageParser.Package pkg = mPackages.get(packageName);
8385        return pkg != null
8386                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8387    }
8388
8389    @Override
8390    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8391        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8392            return ParceledListSlice.emptyList();
8393        }
8394        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8395    }
8396
8397    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8398        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8399
8400        // reader
8401        synchronized (mPackages) {
8402            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8403            final int userId = UserHandle.getCallingUserId();
8404            while (i.hasNext()) {
8405                final PackageParser.Package p = i.next();
8406                if (p.applicationInfo == null) continue;
8407
8408                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8409                        && !p.applicationInfo.isDirectBootAware();
8410                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8411                        && p.applicationInfo.isDirectBootAware();
8412
8413                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8414                        && (!mSafeMode || isSystemApp(p))
8415                        && (matchesUnaware || matchesAware)) {
8416                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8417                    if (ps != null) {
8418                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8419                                ps.readUserState(userId), userId);
8420                        if (ai != null) {
8421                            finalList.add(ai);
8422                        }
8423                    }
8424                }
8425            }
8426        }
8427
8428        return finalList;
8429    }
8430
8431    @Override
8432    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8433        if (!sUserManager.exists(userId)) return null;
8434        flags = updateFlagsForComponent(flags, userId, name);
8435        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8436        // reader
8437        synchronized (mPackages) {
8438            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8439            PackageSetting ps = provider != null
8440                    ? mSettings.mPackages.get(provider.owner.packageName)
8441                    : null;
8442            if (ps != null) {
8443                final boolean isInstantApp = ps.getInstantApp(userId);
8444                // normal application; filter out instant application provider
8445                if (instantAppPkgName == null && isInstantApp) {
8446                    return null;
8447                }
8448                // instant application; filter out other instant applications
8449                if (instantAppPkgName != null
8450                        && isInstantApp
8451                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8452                    return null;
8453                }
8454                // instant application; filter out non-exposed provider
8455                if (instantAppPkgName != null
8456                        && !isInstantApp
8457                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8458                    return null;
8459                }
8460                // provider not enabled
8461                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8462                    return null;
8463                }
8464                return PackageParser.generateProviderInfo(
8465                        provider, flags, ps.readUserState(userId), userId);
8466            }
8467            return null;
8468        }
8469    }
8470
8471    /**
8472     * @deprecated
8473     */
8474    @Deprecated
8475    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8476        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8477            return;
8478        }
8479        // reader
8480        synchronized (mPackages) {
8481            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8482                    .entrySet().iterator();
8483            final int userId = UserHandle.getCallingUserId();
8484            while (i.hasNext()) {
8485                Map.Entry<String, PackageParser.Provider> entry = i.next();
8486                PackageParser.Provider p = entry.getValue();
8487                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8488
8489                if (ps != null && p.syncable
8490                        && (!mSafeMode || (p.info.applicationInfo.flags
8491                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8492                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8493                            ps.readUserState(userId), userId);
8494                    if (info != null) {
8495                        outNames.add(entry.getKey());
8496                        outInfo.add(info);
8497                    }
8498                }
8499            }
8500        }
8501    }
8502
8503    @Override
8504    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8505            int uid, int flags, String metaDataKey) {
8506        final int callingUid = Binder.getCallingUid();
8507        final int userId = processName != null ? UserHandle.getUserId(uid)
8508                : UserHandle.getCallingUserId();
8509        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8510        flags = updateFlagsForComponent(flags, userId, processName);
8511        ArrayList<ProviderInfo> finalList = null;
8512        // reader
8513        synchronized (mPackages) {
8514            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8515            while (i.hasNext()) {
8516                final PackageParser.Provider p = i.next();
8517                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8518                if (ps != null && p.info.authority != null
8519                        && (processName == null
8520                                || (p.info.processName.equals(processName)
8521                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8522                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8523
8524                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8525                    // parameter.
8526                    if (metaDataKey != null
8527                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8528                        continue;
8529                    }
8530                    final ComponentName component =
8531                            new ComponentName(p.info.packageName, p.info.name);
8532                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8533                        continue;
8534                    }
8535                    if (finalList == null) {
8536                        finalList = new ArrayList<ProviderInfo>(3);
8537                    }
8538                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8539                            ps.readUserState(userId), userId);
8540                    if (info != null) {
8541                        finalList.add(info);
8542                    }
8543                }
8544            }
8545        }
8546
8547        if (finalList != null) {
8548            Collections.sort(finalList, mProviderInitOrderSorter);
8549            return new ParceledListSlice<ProviderInfo>(finalList);
8550        }
8551
8552        return ParceledListSlice.emptyList();
8553    }
8554
8555    @Override
8556    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8557        // reader
8558        synchronized (mPackages) {
8559            final int callingUid = Binder.getCallingUid();
8560            final int callingUserId = UserHandle.getUserId(callingUid);
8561            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8562            if (ps == null) return null;
8563            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8564                return null;
8565            }
8566            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8567            return PackageParser.generateInstrumentationInfo(i, flags);
8568        }
8569    }
8570
8571    @Override
8572    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8573            String targetPackage, int flags) {
8574        final int callingUid = Binder.getCallingUid();
8575        final int callingUserId = UserHandle.getUserId(callingUid);
8576        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8577        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8578            return ParceledListSlice.emptyList();
8579        }
8580        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8581    }
8582
8583    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8584            int flags) {
8585        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8586
8587        // reader
8588        synchronized (mPackages) {
8589            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8590            while (i.hasNext()) {
8591                final PackageParser.Instrumentation p = i.next();
8592                if (targetPackage == null
8593                        || targetPackage.equals(p.info.targetPackage)) {
8594                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8595                            flags);
8596                    if (ii != null) {
8597                        finalList.add(ii);
8598                    }
8599                }
8600            }
8601        }
8602
8603        return finalList;
8604    }
8605
8606    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8607        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8608        try {
8609            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8610        } finally {
8611            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8612        }
8613    }
8614
8615    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8616        final File[] files = dir.listFiles();
8617        if (ArrayUtils.isEmpty(files)) {
8618            Log.d(TAG, "No files in app dir " + dir);
8619            return;
8620        }
8621
8622        if (DEBUG_PACKAGE_SCANNING) {
8623            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8624                    + " flags=0x" + Integer.toHexString(parseFlags));
8625        }
8626        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8627                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8628                mParallelPackageParserCallback);
8629
8630        // Submit files for parsing in parallel
8631        int fileCount = 0;
8632        for (File file : files) {
8633            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8634                    && !PackageInstallerService.isStageName(file.getName());
8635            if (!isPackage) {
8636                // Ignore entries which are not packages
8637                continue;
8638            }
8639            parallelPackageParser.submit(file, parseFlags);
8640            fileCount++;
8641        }
8642
8643        // Process results one by one
8644        for (; fileCount > 0; fileCount--) {
8645            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8646            Throwable throwable = parseResult.throwable;
8647            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8648
8649            if (throwable == null) {
8650                // Static shared libraries have synthetic package names
8651                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8652                    renameStaticSharedLibraryPackage(parseResult.pkg);
8653                }
8654                try {
8655                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8656                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8657                                currentTime, null);
8658                    }
8659                } catch (PackageManagerException e) {
8660                    errorCode = e.error;
8661                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8662                }
8663            } else if (throwable instanceof PackageParser.PackageParserException) {
8664                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8665                        throwable;
8666                errorCode = e.error;
8667                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8668            } else {
8669                throw new IllegalStateException("Unexpected exception occurred while parsing "
8670                        + parseResult.scanFile, throwable);
8671            }
8672
8673            // Delete invalid userdata apps
8674            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8675                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8676                logCriticalInfo(Log.WARN,
8677                        "Deleting invalid package at " + parseResult.scanFile);
8678                removeCodePathLI(parseResult.scanFile);
8679            }
8680        }
8681        parallelPackageParser.close();
8682    }
8683
8684    private static File getSettingsProblemFile() {
8685        File dataDir = Environment.getDataDirectory();
8686        File systemDir = new File(dataDir, "system");
8687        File fname = new File(systemDir, "uiderrors.txt");
8688        return fname;
8689    }
8690
8691    static void reportSettingsProblem(int priority, String msg) {
8692        logCriticalInfo(priority, msg);
8693    }
8694
8695    public static void logCriticalInfo(int priority, String msg) {
8696        Slog.println(priority, TAG, msg);
8697        EventLogTags.writePmCriticalInfo(msg);
8698        try {
8699            File fname = getSettingsProblemFile();
8700            FileOutputStream out = new FileOutputStream(fname, true);
8701            PrintWriter pw = new FastPrintWriter(out);
8702            SimpleDateFormat formatter = new SimpleDateFormat();
8703            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8704            pw.println(dateString + ": " + msg);
8705            pw.close();
8706            FileUtils.setPermissions(
8707                    fname.toString(),
8708                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8709                    -1, -1);
8710        } catch (java.io.IOException e) {
8711        }
8712    }
8713
8714    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8715        if (srcFile.isDirectory()) {
8716            final File baseFile = new File(pkg.baseCodePath);
8717            long maxModifiedTime = baseFile.lastModified();
8718            if (pkg.splitCodePaths != null) {
8719                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8720                    final File splitFile = new File(pkg.splitCodePaths[i]);
8721                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8722                }
8723            }
8724            return maxModifiedTime;
8725        }
8726        return srcFile.lastModified();
8727    }
8728
8729    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8730            final int policyFlags) throws PackageManagerException {
8731        // When upgrading from pre-N MR1, verify the package time stamp using the package
8732        // directory and not the APK file.
8733        final long lastModifiedTime = mIsPreNMR1Upgrade
8734                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8735        if (ps != null
8736                && ps.codePath.equals(srcFile)
8737                && ps.timeStamp == lastModifiedTime
8738                && !isCompatSignatureUpdateNeeded(pkg)
8739                && !isRecoverSignatureUpdateNeeded(pkg)) {
8740            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8741            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8742            ArraySet<PublicKey> signingKs;
8743            synchronized (mPackages) {
8744                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8745            }
8746            if (ps.signatures.mSignatures != null
8747                    && ps.signatures.mSignatures.length != 0
8748                    && signingKs != null) {
8749                // Optimization: reuse the existing cached certificates
8750                // if the package appears to be unchanged.
8751                pkg.mSignatures = ps.signatures.mSignatures;
8752                pkg.mSigningKeys = signingKs;
8753                return;
8754            }
8755
8756            Slog.w(TAG, "PackageSetting for " + ps.name
8757                    + " is missing signatures.  Collecting certs again to recover them.");
8758        } else {
8759            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8760        }
8761
8762        try {
8763            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8764            PackageParser.collectCertificates(pkg, policyFlags);
8765        } catch (PackageParserException e) {
8766            throw PackageManagerException.from(e);
8767        } finally {
8768            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8769        }
8770    }
8771
8772    /**
8773     *  Traces a package scan.
8774     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8775     */
8776    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8777            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8778        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8779        try {
8780            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8781        } finally {
8782            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8783        }
8784    }
8785
8786    /**
8787     *  Scans a package and returns the newly parsed package.
8788     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8789     */
8790    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8791            long currentTime, UserHandle user) throws PackageManagerException {
8792        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8793        PackageParser pp = new PackageParser();
8794        pp.setSeparateProcesses(mSeparateProcesses);
8795        pp.setOnlyCoreApps(mOnlyCore);
8796        pp.setDisplayMetrics(mMetrics);
8797        pp.setCallback(mPackageParserCallback);
8798
8799        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8800            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8801        }
8802
8803        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8804        final PackageParser.Package pkg;
8805        try {
8806            pkg = pp.parsePackage(scanFile, parseFlags);
8807        } catch (PackageParserException e) {
8808            throw PackageManagerException.from(e);
8809        } finally {
8810            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8811        }
8812
8813        // Static shared libraries have synthetic package names
8814        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8815            renameStaticSharedLibraryPackage(pkg);
8816        }
8817
8818        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8819    }
8820
8821    /**
8822     *  Scans a package and returns the newly parsed package.
8823     *  @throws PackageManagerException on a parse error.
8824     */
8825    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8826            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8827            throws PackageManagerException {
8828        // If the package has children and this is the first dive in the function
8829        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8830        // packages (parent and children) would be successfully scanned before the
8831        // actual scan since scanning mutates internal state and we want to atomically
8832        // install the package and its children.
8833        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8834            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8835                scanFlags |= SCAN_CHECK_ONLY;
8836            }
8837        } else {
8838            scanFlags &= ~SCAN_CHECK_ONLY;
8839        }
8840
8841        // Scan the parent
8842        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8843                scanFlags, currentTime, user);
8844
8845        // Scan the children
8846        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8847        for (int i = 0; i < childCount; i++) {
8848            PackageParser.Package childPackage = pkg.childPackages.get(i);
8849            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8850                    currentTime, user);
8851        }
8852
8853
8854        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8855            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8856        }
8857
8858        return scannedPkg;
8859    }
8860
8861    /**
8862     *  Scans a package and returns the newly parsed package.
8863     *  @throws PackageManagerException on a parse error.
8864     */
8865    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8866            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8867            throws PackageManagerException {
8868        PackageSetting ps = null;
8869        PackageSetting updatedPkg;
8870        // reader
8871        synchronized (mPackages) {
8872            // Look to see if we already know about this package.
8873            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8874            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8875                // This package has been renamed to its original name.  Let's
8876                // use that.
8877                ps = mSettings.getPackageLPr(oldName);
8878            }
8879            // If there was no original package, see one for the real package name.
8880            if (ps == null) {
8881                ps = mSettings.getPackageLPr(pkg.packageName);
8882            }
8883            // Check to see if this package could be hiding/updating a system
8884            // package.  Must look for it either under the original or real
8885            // package name depending on our state.
8886            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8887            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8888
8889            // If this is a package we don't know about on the system partition, we
8890            // may need to remove disabled child packages on the system partition
8891            // or may need to not add child packages if the parent apk is updated
8892            // on the data partition and no longer defines this child package.
8893            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8894                // If this is a parent package for an updated system app and this system
8895                // app got an OTA update which no longer defines some of the child packages
8896                // we have to prune them from the disabled system packages.
8897                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8898                if (disabledPs != null) {
8899                    final int scannedChildCount = (pkg.childPackages != null)
8900                            ? pkg.childPackages.size() : 0;
8901                    final int disabledChildCount = disabledPs.childPackageNames != null
8902                            ? disabledPs.childPackageNames.size() : 0;
8903                    for (int i = 0; i < disabledChildCount; i++) {
8904                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8905                        boolean disabledPackageAvailable = false;
8906                        for (int j = 0; j < scannedChildCount; j++) {
8907                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8908                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8909                                disabledPackageAvailable = true;
8910                                break;
8911                            }
8912                         }
8913                         if (!disabledPackageAvailable) {
8914                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8915                         }
8916                    }
8917                }
8918            }
8919        }
8920
8921        final boolean isUpdatedPkg = updatedPkg != null;
8922        final boolean isUpdatedSystemPkg = isUpdatedPkg
8923                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
8924        boolean isUpdatedPkgBetter = false;
8925        // First check if this is a system package that may involve an update
8926        if (isUpdatedSystemPkg) {
8927            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8928            // it needs to drop FLAG_PRIVILEGED.
8929            if (locationIsPrivileged(scanFile)) {
8930                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8931            } else {
8932                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8933            }
8934
8935            if (ps != null && !ps.codePath.equals(scanFile)) {
8936                // The path has changed from what was last scanned...  check the
8937                // version of the new path against what we have stored to determine
8938                // what to do.
8939                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8940                if (pkg.mVersionCode <= ps.versionCode) {
8941                    // The system package has been updated and the code path does not match
8942                    // Ignore entry. Skip it.
8943                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8944                            + " ignored: updated version " + ps.versionCode
8945                            + " better than this " + pkg.mVersionCode);
8946                    if (!updatedPkg.codePath.equals(scanFile)) {
8947                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8948                                + ps.name + " changing from " + updatedPkg.codePathString
8949                                + " to " + scanFile);
8950                        updatedPkg.codePath = scanFile;
8951                        updatedPkg.codePathString = scanFile.toString();
8952                        updatedPkg.resourcePath = scanFile;
8953                        updatedPkg.resourcePathString = scanFile.toString();
8954                    }
8955                    updatedPkg.pkg = pkg;
8956                    updatedPkg.versionCode = pkg.mVersionCode;
8957
8958                    // Update the disabled system child packages to point to the package too.
8959                    final int childCount = updatedPkg.childPackageNames != null
8960                            ? updatedPkg.childPackageNames.size() : 0;
8961                    for (int i = 0; i < childCount; i++) {
8962                        String childPackageName = updatedPkg.childPackageNames.get(i);
8963                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8964                                childPackageName);
8965                        if (updatedChildPkg != null) {
8966                            updatedChildPkg.pkg = pkg;
8967                            updatedChildPkg.versionCode = pkg.mVersionCode;
8968                        }
8969                    }
8970                } else {
8971                    // The current app on the system partition is better than
8972                    // what we have updated to on the data partition; switch
8973                    // back to the system partition version.
8974                    // At this point, its safely assumed that package installation for
8975                    // apps in system partition will go through. If not there won't be a working
8976                    // version of the app
8977                    // writer
8978                    synchronized (mPackages) {
8979                        // Just remove the loaded entries from package lists.
8980                        mPackages.remove(ps.name);
8981                    }
8982
8983                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8984                            + " reverting from " + ps.codePathString
8985                            + ": new version " + pkg.mVersionCode
8986                            + " better than installed " + ps.versionCode);
8987
8988                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8989                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8990                    synchronized (mInstallLock) {
8991                        args.cleanUpResourcesLI();
8992                    }
8993                    synchronized (mPackages) {
8994                        mSettings.enableSystemPackageLPw(ps.name);
8995                    }
8996                    isUpdatedPkgBetter = true;
8997                }
8998            }
8999        }
9000
9001        String resourcePath = null;
9002        String baseResourcePath = null;
9003        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9004            if (ps != null && ps.resourcePathString != null) {
9005                resourcePath = ps.resourcePathString;
9006                baseResourcePath = ps.resourcePathString;
9007            } else {
9008                // Should not happen at all. Just log an error.
9009                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9010            }
9011        } else {
9012            resourcePath = pkg.codePath;
9013            baseResourcePath = pkg.baseCodePath;
9014        }
9015
9016        // Set application objects path explicitly.
9017        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9018        pkg.setApplicationInfoCodePath(pkg.codePath);
9019        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9020        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9021        pkg.setApplicationInfoResourcePath(resourcePath);
9022        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9023        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9024
9025        // throw an exception if we have an update to a system application, but, it's not more
9026        // recent than the package we've already scanned
9027        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9028            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9029                    + scanFile + " ignored: updated version " + ps.versionCode
9030                    + " better than this " + pkg.mVersionCode);
9031        }
9032
9033        if (isUpdatedPkg) {
9034            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9035            // initially
9036            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9037
9038            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9039            // flag set initially
9040            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9041                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9042            }
9043        }
9044
9045        // Verify certificates against what was last scanned
9046        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9047
9048        /*
9049         * A new system app appeared, but we already had a non-system one of the
9050         * same name installed earlier.
9051         */
9052        boolean shouldHideSystemApp = false;
9053        if (!isUpdatedPkg && ps != null
9054                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9055            /*
9056             * Check to make sure the signatures match first. If they don't,
9057             * wipe the installed application and its data.
9058             */
9059            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9060                    != PackageManager.SIGNATURE_MATCH) {
9061                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9062                        + " signatures don't match existing userdata copy; removing");
9063                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9064                        "scanPackageInternalLI")) {
9065                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9066                }
9067                ps = null;
9068            } else {
9069                /*
9070                 * If the newly-added system app is an older version than the
9071                 * already installed version, hide it. It will be scanned later
9072                 * and re-added like an update.
9073                 */
9074                if (pkg.mVersionCode <= ps.versionCode) {
9075                    shouldHideSystemApp = true;
9076                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9077                            + " but new version " + pkg.mVersionCode + " better than installed "
9078                            + ps.versionCode + "; hiding system");
9079                } else {
9080                    /*
9081                     * The newly found system app is a newer version that the
9082                     * one previously installed. Simply remove the
9083                     * already-installed application and replace it with our own
9084                     * while keeping the application data.
9085                     */
9086                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9087                            + " reverting from " + ps.codePathString + ": new version "
9088                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9089                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9090                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9091                    synchronized (mInstallLock) {
9092                        args.cleanUpResourcesLI();
9093                    }
9094                }
9095            }
9096        }
9097
9098        // The apk is forward locked (not public) if its code and resources
9099        // are kept in different files. (except for app in either system or
9100        // vendor path).
9101        // TODO grab this value from PackageSettings
9102        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9103            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9104                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9105            }
9106        }
9107
9108        final int userId = ((user == null) ? 0 : user.getIdentifier());
9109        if (ps != null && ps.getInstantApp(userId)) {
9110            scanFlags |= SCAN_AS_INSTANT_APP;
9111        }
9112
9113        // Note that we invoke the following method only if we are about to unpack an application
9114        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9115                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9116
9117        /*
9118         * If the system app should be overridden by a previously installed
9119         * data, hide the system app now and let the /data/app scan pick it up
9120         * again.
9121         */
9122        if (shouldHideSystemApp) {
9123            synchronized (mPackages) {
9124                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9125            }
9126        }
9127
9128        return scannedPkg;
9129    }
9130
9131    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9132        // Derive the new package synthetic package name
9133        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9134                + pkg.staticSharedLibVersion);
9135    }
9136
9137    private static String fixProcessName(String defProcessName,
9138            String processName) {
9139        if (processName == null) {
9140            return defProcessName;
9141        }
9142        return processName;
9143    }
9144
9145    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9146            throws PackageManagerException {
9147        if (pkgSetting.signatures.mSignatures != null) {
9148            // Already existing package. Make sure signatures match
9149            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9150                    == PackageManager.SIGNATURE_MATCH;
9151            if (!match) {
9152                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9153                        == PackageManager.SIGNATURE_MATCH;
9154            }
9155            if (!match) {
9156                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9157                        == PackageManager.SIGNATURE_MATCH;
9158            }
9159            if (!match) {
9160                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9161                        + pkg.packageName + " signatures do not match the "
9162                        + "previously installed version; ignoring!");
9163            }
9164        }
9165
9166        // Check for shared user signatures
9167        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9168            // Already existing package. Make sure signatures match
9169            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9170                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9171            if (!match) {
9172                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9173                        == PackageManager.SIGNATURE_MATCH;
9174            }
9175            if (!match) {
9176                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9177                        == PackageManager.SIGNATURE_MATCH;
9178            }
9179            if (!match) {
9180                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9181                        "Package " + pkg.packageName
9182                        + " has no signatures that match those in shared user "
9183                        + pkgSetting.sharedUser.name + "; ignoring!");
9184            }
9185        }
9186    }
9187
9188    /**
9189     * Enforces that only the system UID or root's UID can call a method exposed
9190     * via Binder.
9191     *
9192     * @param message used as message if SecurityException is thrown
9193     * @throws SecurityException if the caller is not system or root
9194     */
9195    private static final void enforceSystemOrRoot(String message) {
9196        final int uid = Binder.getCallingUid();
9197        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9198            throw new SecurityException(message);
9199        }
9200    }
9201
9202    @Override
9203    public void performFstrimIfNeeded() {
9204        enforceSystemOrRoot("Only the system can request fstrim");
9205
9206        // Before everything else, see whether we need to fstrim.
9207        try {
9208            IStorageManager sm = PackageHelper.getStorageManager();
9209            if (sm != null) {
9210                boolean doTrim = false;
9211                final long interval = android.provider.Settings.Global.getLong(
9212                        mContext.getContentResolver(),
9213                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9214                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9215                if (interval > 0) {
9216                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9217                    if (timeSinceLast > interval) {
9218                        doTrim = true;
9219                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9220                                + "; running immediately");
9221                    }
9222                }
9223                if (doTrim) {
9224                    final boolean dexOptDialogShown;
9225                    synchronized (mPackages) {
9226                        dexOptDialogShown = mDexOptDialogShown;
9227                    }
9228                    if (!isFirstBoot() && dexOptDialogShown) {
9229                        try {
9230                            ActivityManager.getService().showBootMessage(
9231                                    mContext.getResources().getString(
9232                                            R.string.android_upgrading_fstrim), true);
9233                        } catch (RemoteException e) {
9234                        }
9235                    }
9236                    sm.runMaintenance();
9237                }
9238            } else {
9239                Slog.e(TAG, "storageManager service unavailable!");
9240            }
9241        } catch (RemoteException e) {
9242            // Can't happen; StorageManagerService is local
9243        }
9244    }
9245
9246    @Override
9247    public void updatePackagesIfNeeded() {
9248        enforceSystemOrRoot("Only the system can request package update");
9249
9250        // We need to re-extract after an OTA.
9251        boolean causeUpgrade = isUpgrade();
9252
9253        // First boot or factory reset.
9254        // Note: we also handle devices that are upgrading to N right now as if it is their
9255        //       first boot, as they do not have profile data.
9256        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9257
9258        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9259        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9260
9261        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9262            return;
9263        }
9264
9265        List<PackageParser.Package> pkgs;
9266        synchronized (mPackages) {
9267            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9268        }
9269
9270        final long startTime = System.nanoTime();
9271        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9272                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9273                    false /* bootComplete */);
9274
9275        final int elapsedTimeSeconds =
9276                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9277
9278        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9279        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9280        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9281        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9282        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9283    }
9284
9285    /*
9286     * Return the prebuilt profile path given a package base code path.
9287     */
9288    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9289        return pkg.baseCodePath + ".prof";
9290    }
9291
9292    /**
9293     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9294     * containing statistics about the invocation. The array consists of three elements,
9295     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9296     * and {@code numberOfPackagesFailed}.
9297     */
9298    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9299            String compilerFilter, boolean bootComplete) {
9300
9301        int numberOfPackagesVisited = 0;
9302        int numberOfPackagesOptimized = 0;
9303        int numberOfPackagesSkipped = 0;
9304        int numberOfPackagesFailed = 0;
9305        final int numberOfPackagesToDexopt = pkgs.size();
9306
9307        for (PackageParser.Package pkg : pkgs) {
9308            numberOfPackagesVisited++;
9309
9310            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9311                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9312                // that are already compiled.
9313                File profileFile = new File(getPrebuildProfilePath(pkg));
9314                // Copy profile if it exists.
9315                if (profileFile.exists()) {
9316                    try {
9317                        // We could also do this lazily before calling dexopt in
9318                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9319                        // is that we don't have a good way to say "do this only once".
9320                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9321                                pkg.applicationInfo.uid, pkg.packageName)) {
9322                            Log.e(TAG, "Installer failed to copy system profile!");
9323                        }
9324                    } catch (Exception e) {
9325                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9326                                e);
9327                    }
9328                }
9329            }
9330
9331            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9332                if (DEBUG_DEXOPT) {
9333                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9334                }
9335                numberOfPackagesSkipped++;
9336                continue;
9337            }
9338
9339            if (DEBUG_DEXOPT) {
9340                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9341                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9342            }
9343
9344            if (showDialog) {
9345                try {
9346                    ActivityManager.getService().showBootMessage(
9347                            mContext.getResources().getString(R.string.android_upgrading_apk,
9348                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9349                } catch (RemoteException e) {
9350                }
9351                synchronized (mPackages) {
9352                    mDexOptDialogShown = true;
9353                }
9354            }
9355
9356            // If the OTA updates a system app which was previously preopted to a non-preopted state
9357            // the app might end up being verified at runtime. That's because by default the apps
9358            // are verify-profile but for preopted apps there's no profile.
9359            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9360            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9361            // filter (by default 'quicken').
9362            // Note that at this stage unused apps are already filtered.
9363            if (isSystemApp(pkg) &&
9364                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9365                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9366                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9367            }
9368
9369            // checkProfiles is false to avoid merging profiles during boot which
9370            // might interfere with background compilation (b/28612421).
9371            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9372            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9373            // trade-off worth doing to save boot time work.
9374            int primaryDexOptStaus = performDexOptTraced(pkg.packageName,
9375                    false /* checkProfiles */,
9376                    compilerFilter,
9377                    false /* force */,
9378                    bootComplete,
9379                    false /* downgrade */);
9380
9381            if (pkg.isSystemApp()) {
9382                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9383                // too much boot after an OTA.
9384                mDexManager.dexoptSecondaryDex(pkg.packageName,
9385                        compilerFilter,
9386                        false /* force */,
9387                        true /* compileOnlySharedDex */,
9388                        false /* downgrade */);
9389            }
9390
9391            // TODO(shubhamajmera): Record secondary dexopt stats.
9392            switch (primaryDexOptStaus) {
9393                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9394                    numberOfPackagesOptimized++;
9395                    break;
9396                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9397                    numberOfPackagesSkipped++;
9398                    break;
9399                case PackageDexOptimizer.DEX_OPT_FAILED:
9400                    numberOfPackagesFailed++;
9401                    break;
9402                default:
9403                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9404                    break;
9405            }
9406        }
9407
9408        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9409                numberOfPackagesFailed };
9410    }
9411
9412    @Override
9413    public void notifyPackageUse(String packageName, int reason) {
9414        synchronized (mPackages) {
9415            final int callingUid = Binder.getCallingUid();
9416            final int callingUserId = UserHandle.getUserId(callingUid);
9417            if (getInstantAppPackageName(callingUid) != null) {
9418                if (!isCallerSameApp(packageName, callingUid)) {
9419                    return;
9420                }
9421            } else {
9422                if (isInstantApp(packageName, callingUserId)) {
9423                    return;
9424                }
9425            }
9426            final PackageParser.Package p = mPackages.get(packageName);
9427            if (p == null) {
9428                return;
9429            }
9430            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9431        }
9432    }
9433
9434    @Override
9435    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9436        int userId = UserHandle.getCallingUserId();
9437        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9438        if (ai == null) {
9439            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9440                + loadingPackageName + ", user=" + userId);
9441            return;
9442        }
9443        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9444    }
9445
9446    @Override
9447    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9448            IDexModuleRegisterCallback callback) {
9449        int userId = UserHandle.getCallingUserId();
9450        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9451        DexManager.RegisterDexModuleResult result;
9452        if (ai == null) {
9453            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9454                     " calling user. package=" + packageName + ", user=" + userId);
9455            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9456        } else {
9457            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9458        }
9459
9460        if (callback != null) {
9461            mHandler.post(() -> {
9462                try {
9463                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9464                } catch (RemoteException e) {
9465                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9466                }
9467            });
9468        }
9469    }
9470
9471    @Override
9472    public boolean performDexOpt(String packageName,
9473            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete,
9474            boolean downgrade) {
9475        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9476            return false;
9477        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9478            return false;
9479        }
9480        int dexoptStatus = performDexOptWithStatus(
9481              packageName, checkProfiles, compileReason, force, bootComplete,
9482              downgrade);
9483        return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9484    }
9485
9486    /**
9487     * Perform dexopt on the given package and return one of following result:
9488     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9489     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9490     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9491     */
9492    /* package */ int performDexOptWithStatus(String packageName,
9493            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete,
9494            boolean downgrade) {
9495        return performDexOptTraced(packageName, checkProfiles,
9496                getCompilerFilterForReason(compileReason), force, bootComplete, downgrade);
9497    }
9498
9499    @Override
9500    public boolean performDexOptMode(String packageName,
9501            boolean checkProfiles, String targetCompilerFilter, boolean force,
9502            boolean bootComplete) {
9503        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9504            return false;
9505        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9506            return false;
9507        }
9508        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9509                targetCompilerFilter, force, bootComplete, false /* downgrade */);
9510        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9511    }
9512
9513    private int performDexOptTraced(String packageName,
9514                boolean checkProfiles, String targetCompilerFilter, boolean force,
9515                boolean bootComplete, boolean downgrade) {
9516        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9517        try {
9518            return performDexOptInternal(packageName, checkProfiles,
9519                    targetCompilerFilter, force, bootComplete, downgrade);
9520        } finally {
9521            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9522        }
9523    }
9524
9525    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9526    // if the package can now be considered up to date for the given filter.
9527    private int performDexOptInternal(String packageName,
9528                boolean checkProfiles, String targetCompilerFilter, boolean force,
9529                boolean bootComplete, boolean downgrade) {
9530        PackageParser.Package p;
9531        synchronized (mPackages) {
9532            p = mPackages.get(packageName);
9533            if (p == null) {
9534                // Package could not be found. Report failure.
9535                return PackageDexOptimizer.DEX_OPT_FAILED;
9536            }
9537            mPackageUsage.maybeWriteAsync(mPackages);
9538            mCompilerStats.maybeWriteAsync();
9539        }
9540        long callingId = Binder.clearCallingIdentity();
9541        try {
9542            synchronized (mInstallLock) {
9543                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9544                        targetCompilerFilter, force, bootComplete, downgrade);
9545            }
9546        } finally {
9547            Binder.restoreCallingIdentity(callingId);
9548        }
9549    }
9550
9551    public ArraySet<String> getOptimizablePackages() {
9552        ArraySet<String> pkgs = new ArraySet<String>();
9553        synchronized (mPackages) {
9554            for (PackageParser.Package p : mPackages.values()) {
9555                if (PackageDexOptimizer.canOptimizePackage(p)) {
9556                    pkgs.add(p.packageName);
9557                }
9558            }
9559        }
9560        return pkgs;
9561    }
9562
9563    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9564            boolean checkProfiles, String targetCompilerFilter,
9565            boolean force, boolean bootComplete, boolean downgrade) {
9566        // Select the dex optimizer based on the force parameter.
9567        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9568        //       allocate an object here.
9569        PackageDexOptimizer pdo = force
9570                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9571                : mPackageDexOptimizer;
9572
9573        // Dexopt all dependencies first. Note: we ignore the return value and march on
9574        // on errors.
9575        // Note that we are going to call performDexOpt on those libraries as many times as
9576        // they are referenced in packages. When we do a batch of performDexOpt (for example
9577        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9578        // and the first package that uses the library will dexopt it. The
9579        // others will see that the compiled code for the library is up to date.
9580        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9581        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9582        if (!deps.isEmpty()) {
9583            for (PackageParser.Package depPackage : deps) {
9584                // TODO: Analyze and investigate if we (should) profile libraries.
9585                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9586                        false /* checkProfiles */,
9587                        targetCompilerFilter,
9588                        getOrCreateCompilerPackageStats(depPackage),
9589                        true /* isUsedByOtherApps */,
9590                        bootComplete,
9591                        downgrade);
9592            }
9593        }
9594        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9595                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9596                mDexManager.isUsedByOtherApps(p.packageName), bootComplete, downgrade);
9597    }
9598
9599    // Performs dexopt on the used secondary dex files belonging to the given package.
9600    // Returns true if all dex files were process successfully (which could mean either dexopt or
9601    // skip). Returns false if any of the files caused errors.
9602    @Override
9603    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9604            boolean force) {
9605        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9606            return false;
9607        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9608            return false;
9609        }
9610        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force,
9611                false /* compileOnlySharedDex */, false /* downgrade */);
9612    }
9613
9614    public boolean performDexOptSecondary(String packageName, int compileReason,
9615            boolean force, boolean downgrade) {
9616        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force, downgrade);
9617    }
9618
9619    /**
9620     * Reconcile the information we have about the secondary dex files belonging to
9621     * {@code packagName} and the actual dex files. For all dex files that were
9622     * deleted, update the internal records and delete the generated oat files.
9623     */
9624    @Override
9625    public void reconcileSecondaryDexFiles(String packageName) {
9626        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9627            return;
9628        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9629            return;
9630        }
9631        mDexManager.reconcileSecondaryDexFiles(packageName);
9632    }
9633
9634    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9635    // a reference there.
9636    /*package*/ DexManager getDexManager() {
9637        return mDexManager;
9638    }
9639
9640    /**
9641     * Execute the background dexopt job immediately.
9642     */
9643    @Override
9644    public boolean runBackgroundDexoptJob() {
9645        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9646            return false;
9647        }
9648        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9649    }
9650
9651    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9652        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9653                || p.usesStaticLibraries != null) {
9654            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9655            Set<String> collectedNames = new HashSet<>();
9656            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9657
9658            retValue.remove(p);
9659
9660            return retValue;
9661        } else {
9662            return Collections.emptyList();
9663        }
9664    }
9665
9666    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9667            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9668        if (!collectedNames.contains(p.packageName)) {
9669            collectedNames.add(p.packageName);
9670            collected.add(p);
9671
9672            if (p.usesLibraries != null) {
9673                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9674                        null, collected, collectedNames);
9675            }
9676            if (p.usesOptionalLibraries != null) {
9677                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9678                        null, collected, collectedNames);
9679            }
9680            if (p.usesStaticLibraries != null) {
9681                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9682                        p.usesStaticLibrariesVersions, collected, collectedNames);
9683            }
9684        }
9685    }
9686
9687    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9688            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9689        final int libNameCount = libs.size();
9690        for (int i = 0; i < libNameCount; i++) {
9691            String libName = libs.get(i);
9692            int version = (versions != null && versions.length == libNameCount)
9693                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9694            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9695            if (libPkg != null) {
9696                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9697            }
9698        }
9699    }
9700
9701    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9702        synchronized (mPackages) {
9703            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9704            if (libEntry != null) {
9705                return mPackages.get(libEntry.apk);
9706            }
9707            return null;
9708        }
9709    }
9710
9711    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9712        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9713        if (versionedLib == null) {
9714            return null;
9715        }
9716        return versionedLib.get(version);
9717    }
9718
9719    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9720        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9721                pkg.staticSharedLibName);
9722        if (versionedLib == null) {
9723            return null;
9724        }
9725        int previousLibVersion = -1;
9726        final int versionCount = versionedLib.size();
9727        for (int i = 0; i < versionCount; i++) {
9728            final int libVersion = versionedLib.keyAt(i);
9729            if (libVersion < pkg.staticSharedLibVersion) {
9730                previousLibVersion = Math.max(previousLibVersion, libVersion);
9731            }
9732        }
9733        if (previousLibVersion >= 0) {
9734            return versionedLib.get(previousLibVersion);
9735        }
9736        return null;
9737    }
9738
9739    public void shutdown() {
9740        mPackageUsage.writeNow(mPackages);
9741        mCompilerStats.writeNow();
9742    }
9743
9744    @Override
9745    public void dumpProfiles(String packageName) {
9746        PackageParser.Package pkg;
9747        synchronized (mPackages) {
9748            pkg = mPackages.get(packageName);
9749            if (pkg == null) {
9750                throw new IllegalArgumentException("Unknown package: " + packageName);
9751            }
9752        }
9753        /* Only the shell, root, or the app user should be able to dump profiles. */
9754        int callingUid = Binder.getCallingUid();
9755        if (callingUid != Process.SHELL_UID &&
9756            callingUid != Process.ROOT_UID &&
9757            callingUid != pkg.applicationInfo.uid) {
9758            throw new SecurityException("dumpProfiles");
9759        }
9760
9761        synchronized (mInstallLock) {
9762            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9763            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9764            try {
9765                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9766                String codePaths = TextUtils.join(";", allCodePaths);
9767                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9768            } catch (InstallerException e) {
9769                Slog.w(TAG, "Failed to dump profiles", e);
9770            }
9771            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9772        }
9773    }
9774
9775    @Override
9776    public void forceDexOpt(String packageName) {
9777        enforceSystemOrRoot("forceDexOpt");
9778
9779        PackageParser.Package pkg;
9780        synchronized (mPackages) {
9781            pkg = mPackages.get(packageName);
9782            if (pkg == null) {
9783                throw new IllegalArgumentException("Unknown package: " + packageName);
9784            }
9785        }
9786
9787        synchronized (mInstallLock) {
9788            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9789
9790            // Whoever is calling forceDexOpt wants a compiled package.
9791            // Don't use profiles since that may cause compilation to be skipped.
9792            final int res = performDexOptInternalWithDependenciesLI(pkg,
9793                    false /* checkProfiles */, getDefaultCompilerFilter(),
9794                    true /* force */,
9795                    true /* bootComplete */,
9796                    false /* downgrade */);
9797
9798            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9799            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9800                throw new IllegalStateException("Failed to dexopt: " + res);
9801            }
9802        }
9803    }
9804
9805    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9806        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9807            Slog.w(TAG, "Unable to update from " + oldPkg.name
9808                    + " to " + newPkg.packageName
9809                    + ": old package not in system partition");
9810            return false;
9811        } else if (mPackages.get(oldPkg.name) != null) {
9812            Slog.w(TAG, "Unable to update from " + oldPkg.name
9813                    + " to " + newPkg.packageName
9814                    + ": old package still exists");
9815            return false;
9816        }
9817        return true;
9818    }
9819
9820    void removeCodePathLI(File codePath) {
9821        if (codePath.isDirectory()) {
9822            try {
9823                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9824            } catch (InstallerException e) {
9825                Slog.w(TAG, "Failed to remove code path", e);
9826            }
9827        } else {
9828            codePath.delete();
9829        }
9830    }
9831
9832    private int[] resolveUserIds(int userId) {
9833        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9834    }
9835
9836    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9837        if (pkg == null) {
9838            Slog.wtf(TAG, "Package was null!", new Throwable());
9839            return;
9840        }
9841        clearAppDataLeafLIF(pkg, userId, flags);
9842        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9843        for (int i = 0; i < childCount; i++) {
9844            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9845        }
9846    }
9847
9848    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9849        final PackageSetting ps;
9850        synchronized (mPackages) {
9851            ps = mSettings.mPackages.get(pkg.packageName);
9852        }
9853        for (int realUserId : resolveUserIds(userId)) {
9854            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9855            try {
9856                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9857                        ceDataInode);
9858            } catch (InstallerException e) {
9859                Slog.w(TAG, String.valueOf(e));
9860            }
9861        }
9862    }
9863
9864    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9865        if (pkg == null) {
9866            Slog.wtf(TAG, "Package was null!", new Throwable());
9867            return;
9868        }
9869        destroyAppDataLeafLIF(pkg, userId, flags);
9870        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9871        for (int i = 0; i < childCount; i++) {
9872            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9873        }
9874    }
9875
9876    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9877        final PackageSetting ps;
9878        synchronized (mPackages) {
9879            ps = mSettings.mPackages.get(pkg.packageName);
9880        }
9881        for (int realUserId : resolveUserIds(userId)) {
9882            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9883            try {
9884                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9885                        ceDataInode);
9886            } catch (InstallerException e) {
9887                Slog.w(TAG, String.valueOf(e));
9888            }
9889            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9890        }
9891    }
9892
9893    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9894        if (pkg == null) {
9895            Slog.wtf(TAG, "Package was null!", new Throwable());
9896            return;
9897        }
9898        destroyAppProfilesLeafLIF(pkg);
9899        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9900        for (int i = 0; i < childCount; i++) {
9901            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9902        }
9903    }
9904
9905    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9906        try {
9907            mInstaller.destroyAppProfiles(pkg.packageName);
9908        } catch (InstallerException e) {
9909            Slog.w(TAG, String.valueOf(e));
9910        }
9911    }
9912
9913    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9914        if (pkg == null) {
9915            Slog.wtf(TAG, "Package was null!", new Throwable());
9916            return;
9917        }
9918        clearAppProfilesLeafLIF(pkg);
9919        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9920        for (int i = 0; i < childCount; i++) {
9921            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9922        }
9923    }
9924
9925    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9926        try {
9927            mInstaller.clearAppProfiles(pkg.packageName);
9928        } catch (InstallerException e) {
9929            Slog.w(TAG, String.valueOf(e));
9930        }
9931    }
9932
9933    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9934            long lastUpdateTime) {
9935        // Set parent install/update time
9936        PackageSetting ps = (PackageSetting) pkg.mExtras;
9937        if (ps != null) {
9938            ps.firstInstallTime = firstInstallTime;
9939            ps.lastUpdateTime = lastUpdateTime;
9940        }
9941        // Set children install/update time
9942        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9943        for (int i = 0; i < childCount; i++) {
9944            PackageParser.Package childPkg = pkg.childPackages.get(i);
9945            ps = (PackageSetting) childPkg.mExtras;
9946            if (ps != null) {
9947                ps.firstInstallTime = firstInstallTime;
9948                ps.lastUpdateTime = lastUpdateTime;
9949            }
9950        }
9951    }
9952
9953    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9954            PackageParser.Package changingLib) {
9955        if (file.path != null) {
9956            usesLibraryFiles.add(file.path);
9957            return;
9958        }
9959        PackageParser.Package p = mPackages.get(file.apk);
9960        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9961            // If we are doing this while in the middle of updating a library apk,
9962            // then we need to make sure to use that new apk for determining the
9963            // dependencies here.  (We haven't yet finished committing the new apk
9964            // to the package manager state.)
9965            if (p == null || p.packageName.equals(changingLib.packageName)) {
9966                p = changingLib;
9967            }
9968        }
9969        if (p != null) {
9970            usesLibraryFiles.addAll(p.getAllCodePaths());
9971            if (p.usesLibraryFiles != null) {
9972                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9973            }
9974        }
9975    }
9976
9977    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9978            PackageParser.Package changingLib) throws PackageManagerException {
9979        if (pkg == null) {
9980            return;
9981        }
9982        ArraySet<String> usesLibraryFiles = null;
9983        if (pkg.usesLibraries != null) {
9984            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9985                    null, null, pkg.packageName, changingLib, true, null);
9986        }
9987        if (pkg.usesStaticLibraries != null) {
9988            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9989                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9990                    pkg.packageName, changingLib, true, usesLibraryFiles);
9991        }
9992        if (pkg.usesOptionalLibraries != null) {
9993            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9994                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9995        }
9996        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9997            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9998        } else {
9999            pkg.usesLibraryFiles = null;
10000        }
10001    }
10002
10003    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10004            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10005            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10006            boolean required, @Nullable ArraySet<String> outUsedLibraries)
10007            throws PackageManagerException {
10008        final int libCount = requestedLibraries.size();
10009        for (int i = 0; i < libCount; i++) {
10010            final String libName = requestedLibraries.get(i);
10011            final int libVersion = requiredVersions != null ? requiredVersions[i]
10012                    : SharedLibraryInfo.VERSION_UNDEFINED;
10013            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10014            if (libEntry == null) {
10015                if (required) {
10016                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10017                            "Package " + packageName + " requires unavailable shared library "
10018                                    + libName + "; failing!");
10019                } else if (DEBUG_SHARED_LIBRARIES) {
10020                    Slog.i(TAG, "Package " + packageName
10021                            + " desires unavailable shared library "
10022                            + libName + "; ignoring!");
10023                }
10024            } else {
10025                if (requiredVersions != null && requiredCertDigests != null) {
10026                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10027                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10028                            "Package " + packageName + " requires unavailable static shared"
10029                                    + " library " + libName + " version "
10030                                    + libEntry.info.getVersion() + "; failing!");
10031                    }
10032
10033                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10034                    if (libPkg == null) {
10035                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10036                                "Package " + packageName + " requires unavailable static shared"
10037                                        + " library; failing!");
10038                    }
10039
10040                    String expectedCertDigest = requiredCertDigests[i];
10041                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10042                                libPkg.mSignatures[0]);
10043                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10044                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10045                                "Package " + packageName + " requires differently signed" +
10046                                        " static shared library; failing!");
10047                    }
10048                }
10049
10050                if (outUsedLibraries == null) {
10051                    outUsedLibraries = new ArraySet<>();
10052                }
10053                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10054            }
10055        }
10056        return outUsedLibraries;
10057    }
10058
10059    private static boolean hasString(List<String> list, List<String> which) {
10060        if (list == null) {
10061            return false;
10062        }
10063        for (int i=list.size()-1; i>=0; i--) {
10064            for (int j=which.size()-1; j>=0; j--) {
10065                if (which.get(j).equals(list.get(i))) {
10066                    return true;
10067                }
10068            }
10069        }
10070        return false;
10071    }
10072
10073    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10074            PackageParser.Package changingPkg) {
10075        ArrayList<PackageParser.Package> res = null;
10076        for (PackageParser.Package pkg : mPackages.values()) {
10077            if (changingPkg != null
10078                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10079                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10080                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10081                            changingPkg.staticSharedLibName)) {
10082                return null;
10083            }
10084            if (res == null) {
10085                res = new ArrayList<>();
10086            }
10087            res.add(pkg);
10088            try {
10089                updateSharedLibrariesLPr(pkg, changingPkg);
10090            } catch (PackageManagerException e) {
10091                // If a system app update or an app and a required lib missing we
10092                // delete the package and for updated system apps keep the data as
10093                // it is better for the user to reinstall than to be in an limbo
10094                // state. Also libs disappearing under an app should never happen
10095                // - just in case.
10096                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10097                    final int flags = pkg.isUpdatedSystemApp()
10098                            ? PackageManager.DELETE_KEEP_DATA : 0;
10099                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10100                            flags , null, true, null);
10101                }
10102                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10103            }
10104        }
10105        return res;
10106    }
10107
10108    /**
10109     * Derive the value of the {@code cpuAbiOverride} based on the provided
10110     * value and an optional stored value from the package settings.
10111     */
10112    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10113        String cpuAbiOverride = null;
10114
10115        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10116            cpuAbiOverride = null;
10117        } else if (abiOverride != null) {
10118            cpuAbiOverride = abiOverride;
10119        } else if (settings != null) {
10120            cpuAbiOverride = settings.cpuAbiOverrideString;
10121        }
10122
10123        return cpuAbiOverride;
10124    }
10125
10126    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10127            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10128                    throws PackageManagerException {
10129        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10130        // If the package has children and this is the first dive in the function
10131        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10132        // whether all packages (parent and children) would be successfully scanned
10133        // before the actual scan since scanning mutates internal state and we want
10134        // to atomically install the package and its children.
10135        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10136            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10137                scanFlags |= SCAN_CHECK_ONLY;
10138            }
10139        } else {
10140            scanFlags &= ~SCAN_CHECK_ONLY;
10141        }
10142
10143        final PackageParser.Package scannedPkg;
10144        try {
10145            // Scan the parent
10146            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10147            // Scan the children
10148            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10149            for (int i = 0; i < childCount; i++) {
10150                PackageParser.Package childPkg = pkg.childPackages.get(i);
10151                scanPackageLI(childPkg, policyFlags,
10152                        scanFlags, currentTime, user);
10153            }
10154        } finally {
10155            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10156        }
10157
10158        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10159            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10160        }
10161
10162        return scannedPkg;
10163    }
10164
10165    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10166            int scanFlags, long currentTime, @Nullable UserHandle user)
10167                    throws PackageManagerException {
10168        boolean success = false;
10169        try {
10170            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10171                    currentTime, user);
10172            success = true;
10173            return res;
10174        } finally {
10175            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10176                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10177                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10178                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10179                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10180            }
10181        }
10182    }
10183
10184    /**
10185     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10186     */
10187    private static boolean apkHasCode(String fileName) {
10188        StrictJarFile jarFile = null;
10189        try {
10190            jarFile = new StrictJarFile(fileName,
10191                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10192            return jarFile.findEntry("classes.dex") != null;
10193        } catch (IOException ignore) {
10194        } finally {
10195            try {
10196                if (jarFile != null) {
10197                    jarFile.close();
10198                }
10199            } catch (IOException ignore) {}
10200        }
10201        return false;
10202    }
10203
10204    /**
10205     * Enforces code policy for the package. This ensures that if an APK has
10206     * declared hasCode="true" in its manifest that the APK actually contains
10207     * code.
10208     *
10209     * @throws PackageManagerException If bytecode could not be found when it should exist
10210     */
10211    private static void assertCodePolicy(PackageParser.Package pkg)
10212            throws PackageManagerException {
10213        final boolean shouldHaveCode =
10214                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10215        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10216            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10217                    "Package " + pkg.baseCodePath + " code is missing");
10218        }
10219
10220        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10221            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10222                final boolean splitShouldHaveCode =
10223                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10224                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10225                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10226                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10227                }
10228            }
10229        }
10230    }
10231
10232    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10233            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10234                    throws PackageManagerException {
10235        if (DEBUG_PACKAGE_SCANNING) {
10236            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10237                Log.d(TAG, "Scanning package " + pkg.packageName);
10238        }
10239
10240        applyPolicy(pkg, policyFlags);
10241
10242        assertPackageIsValid(pkg, policyFlags, scanFlags);
10243
10244        // Initialize package source and resource directories
10245        final File scanFile = new File(pkg.codePath);
10246        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10247        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10248
10249        SharedUserSetting suid = null;
10250        PackageSetting pkgSetting = null;
10251
10252        // Getting the package setting may have a side-effect, so if we
10253        // are only checking if scan would succeed, stash a copy of the
10254        // old setting to restore at the end.
10255        PackageSetting nonMutatedPs = null;
10256
10257        // We keep references to the derived CPU Abis from settings in oder to reuse
10258        // them in the case where we're not upgrading or booting for the first time.
10259        String primaryCpuAbiFromSettings = null;
10260        String secondaryCpuAbiFromSettings = null;
10261
10262        // writer
10263        synchronized (mPackages) {
10264            if (pkg.mSharedUserId != null) {
10265                // SIDE EFFECTS; may potentially allocate a new shared user
10266                suid = mSettings.getSharedUserLPw(
10267                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10268                if (DEBUG_PACKAGE_SCANNING) {
10269                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10270                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10271                                + "): packages=" + suid.packages);
10272                }
10273            }
10274
10275            // Check if we are renaming from an original package name.
10276            PackageSetting origPackage = null;
10277            String realName = null;
10278            if (pkg.mOriginalPackages != null) {
10279                // This package may need to be renamed to a previously
10280                // installed name.  Let's check on that...
10281                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10282                if (pkg.mOriginalPackages.contains(renamed)) {
10283                    // This package had originally been installed as the
10284                    // original name, and we have already taken care of
10285                    // transitioning to the new one.  Just update the new
10286                    // one to continue using the old name.
10287                    realName = pkg.mRealPackage;
10288                    if (!pkg.packageName.equals(renamed)) {
10289                        // Callers into this function may have already taken
10290                        // care of renaming the package; only do it here if
10291                        // it is not already done.
10292                        pkg.setPackageName(renamed);
10293                    }
10294                } else {
10295                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10296                        if ((origPackage = mSettings.getPackageLPr(
10297                                pkg.mOriginalPackages.get(i))) != null) {
10298                            // We do have the package already installed under its
10299                            // original name...  should we use it?
10300                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10301                                // New package is not compatible with original.
10302                                origPackage = null;
10303                                continue;
10304                            } else if (origPackage.sharedUser != null) {
10305                                // Make sure uid is compatible between packages.
10306                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10307                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10308                                            + " to " + pkg.packageName + ": old uid "
10309                                            + origPackage.sharedUser.name
10310                                            + " differs from " + pkg.mSharedUserId);
10311                                    origPackage = null;
10312                                    continue;
10313                                }
10314                                // TODO: Add case when shared user id is added [b/28144775]
10315                            } else {
10316                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10317                                        + pkg.packageName + " to old name " + origPackage.name);
10318                            }
10319                            break;
10320                        }
10321                    }
10322                }
10323            }
10324
10325            if (mTransferedPackages.contains(pkg.packageName)) {
10326                Slog.w(TAG, "Package " + pkg.packageName
10327                        + " was transferred to another, but its .apk remains");
10328            }
10329
10330            // See comments in nonMutatedPs declaration
10331            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10332                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10333                if (foundPs != null) {
10334                    nonMutatedPs = new PackageSetting(foundPs);
10335                }
10336            }
10337
10338            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10339                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10340                if (foundPs != null) {
10341                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10342                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10343                }
10344            }
10345
10346            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10347            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10348                PackageManagerService.reportSettingsProblem(Log.WARN,
10349                        "Package " + pkg.packageName + " shared user changed from "
10350                                + (pkgSetting.sharedUser != null
10351                                        ? pkgSetting.sharedUser.name : "<nothing>")
10352                                + " to "
10353                                + (suid != null ? suid.name : "<nothing>")
10354                                + "; replacing with new");
10355                pkgSetting = null;
10356            }
10357            final PackageSetting oldPkgSetting =
10358                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10359            final PackageSetting disabledPkgSetting =
10360                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10361
10362            String[] usesStaticLibraries = null;
10363            if (pkg.usesStaticLibraries != null) {
10364                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10365                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10366            }
10367
10368            if (pkgSetting == null) {
10369                final String parentPackageName = (pkg.parentPackage != null)
10370                        ? pkg.parentPackage.packageName : null;
10371                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10372                // REMOVE SharedUserSetting from method; update in a separate call
10373                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10374                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10375                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10376                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10377                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10378                        true /*allowInstall*/, instantApp, parentPackageName,
10379                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10380                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10381                // SIDE EFFECTS; updates system state; move elsewhere
10382                if (origPackage != null) {
10383                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10384                }
10385                mSettings.addUserToSettingLPw(pkgSetting);
10386            } else {
10387                // REMOVE SharedUserSetting from method; update in a separate call.
10388                //
10389                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10390                // secondaryCpuAbi are not known at this point so we always update them
10391                // to null here, only to reset them at a later point.
10392                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10393                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10394                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10395                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10396                        UserManagerService.getInstance(), usesStaticLibraries,
10397                        pkg.usesStaticLibrariesVersions);
10398            }
10399            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10400            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10401
10402            // SIDE EFFECTS; modifies system state; move elsewhere
10403            if (pkgSetting.origPackage != null) {
10404                // If we are first transitioning from an original package,
10405                // fix up the new package's name now.  We need to do this after
10406                // looking up the package under its new name, so getPackageLP
10407                // can take care of fiddling things correctly.
10408                pkg.setPackageName(origPackage.name);
10409
10410                // File a report about this.
10411                String msg = "New package " + pkgSetting.realName
10412                        + " renamed to replace old package " + pkgSetting.name;
10413                reportSettingsProblem(Log.WARN, msg);
10414
10415                // Make a note of it.
10416                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10417                    mTransferedPackages.add(origPackage.name);
10418                }
10419
10420                // No longer need to retain this.
10421                pkgSetting.origPackage = null;
10422            }
10423
10424            // SIDE EFFECTS; modifies system state; move elsewhere
10425            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10426                // Make a note of it.
10427                mTransferedPackages.add(pkg.packageName);
10428            }
10429
10430            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10431                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10432            }
10433
10434            if ((scanFlags & SCAN_BOOTING) == 0
10435                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10436                // Check all shared libraries and map to their actual file path.
10437                // We only do this here for apps not on a system dir, because those
10438                // are the only ones that can fail an install due to this.  We
10439                // will take care of the system apps by updating all of their
10440                // library paths after the scan is done. Also during the initial
10441                // scan don't update any libs as we do this wholesale after all
10442                // apps are scanned to avoid dependency based scanning.
10443                updateSharedLibrariesLPr(pkg, null);
10444            }
10445
10446            if (mFoundPolicyFile) {
10447                SELinuxMMAC.assignSeInfoValue(pkg);
10448            }
10449            pkg.applicationInfo.uid = pkgSetting.appId;
10450            pkg.mExtras = pkgSetting;
10451
10452
10453            // Static shared libs have same package with different versions where
10454            // we internally use a synthetic package name to allow multiple versions
10455            // of the same package, therefore we need to compare signatures against
10456            // the package setting for the latest library version.
10457            PackageSetting signatureCheckPs = pkgSetting;
10458            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10459                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10460                if (libraryEntry != null) {
10461                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10462                }
10463            }
10464
10465            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10466                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10467                    // We just determined the app is signed correctly, so bring
10468                    // over the latest parsed certs.
10469                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10470                } else {
10471                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10472                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10473                                "Package " + pkg.packageName + " upgrade keys do not match the "
10474                                + "previously installed version");
10475                    } else {
10476                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10477                        String msg = "System package " + pkg.packageName
10478                                + " signature changed; retaining data.";
10479                        reportSettingsProblem(Log.WARN, msg);
10480                    }
10481                }
10482            } else {
10483                try {
10484                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10485                    verifySignaturesLP(signatureCheckPs, pkg);
10486                    // We just determined the app is signed correctly, so bring
10487                    // over the latest parsed certs.
10488                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10489                } catch (PackageManagerException e) {
10490                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10491                        throw e;
10492                    }
10493                    // The signature has changed, but this package is in the system
10494                    // image...  let's recover!
10495                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10496                    // However...  if this package is part of a shared user, but it
10497                    // doesn't match the signature of the shared user, let's fail.
10498                    // What this means is that you can't change the signatures
10499                    // associated with an overall shared user, which doesn't seem all
10500                    // that unreasonable.
10501                    if (signatureCheckPs.sharedUser != null) {
10502                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10503                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10504                            throw new PackageManagerException(
10505                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10506                                    "Signature mismatch for shared user: "
10507                                            + pkgSetting.sharedUser);
10508                        }
10509                    }
10510                    // File a report about this.
10511                    String msg = "System package " + pkg.packageName
10512                            + " signature changed; retaining data.";
10513                    reportSettingsProblem(Log.WARN, msg);
10514                }
10515            }
10516
10517            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10518                // This package wants to adopt ownership of permissions from
10519                // another package.
10520                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10521                    final String origName = pkg.mAdoptPermissions.get(i);
10522                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10523                    if (orig != null) {
10524                        if (verifyPackageUpdateLPr(orig, pkg)) {
10525                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10526                                    + pkg.packageName);
10527                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10528                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10529                        }
10530                    }
10531                }
10532            }
10533        }
10534
10535        pkg.applicationInfo.processName = fixProcessName(
10536                pkg.applicationInfo.packageName,
10537                pkg.applicationInfo.processName);
10538
10539        if (pkg != mPlatformPackage) {
10540            // Get all of our default paths setup
10541            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10542        }
10543
10544        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10545
10546        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10547            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10548                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10549                final boolean extractNativeLibs = !pkg.isLibrary();
10550                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10551                        mAppLib32InstallDir);
10552                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10553
10554                // Some system apps still use directory structure for native libraries
10555                // in which case we might end up not detecting abi solely based on apk
10556                // structure. Try to detect abi based on directory structure.
10557                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10558                        pkg.applicationInfo.primaryCpuAbi == null) {
10559                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10560                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10561                }
10562            } else {
10563                // This is not a first boot or an upgrade, don't bother deriving the
10564                // ABI during the scan. Instead, trust the value that was stored in the
10565                // package setting.
10566                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10567                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10568
10569                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10570
10571                if (DEBUG_ABI_SELECTION) {
10572                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10573                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10574                        pkg.applicationInfo.secondaryCpuAbi);
10575                }
10576            }
10577        } else {
10578            if ((scanFlags & SCAN_MOVE) != 0) {
10579                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10580                // but we already have this packages package info in the PackageSetting. We just
10581                // use that and derive the native library path based on the new codepath.
10582                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10583                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10584            }
10585
10586            // Set native library paths again. For moves, the path will be updated based on the
10587            // ABIs we've determined above. For non-moves, the path will be updated based on the
10588            // ABIs we determined during compilation, but the path will depend on the final
10589            // package path (after the rename away from the stage path).
10590            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10591        }
10592
10593        // This is a special case for the "system" package, where the ABI is
10594        // dictated by the zygote configuration (and init.rc). We should keep track
10595        // of this ABI so that we can deal with "normal" applications that run under
10596        // the same UID correctly.
10597        if (mPlatformPackage == pkg) {
10598            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10599                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10600        }
10601
10602        // If there's a mismatch between the abi-override in the package setting
10603        // and the abiOverride specified for the install. Warn about this because we
10604        // would've already compiled the app without taking the package setting into
10605        // account.
10606        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10607            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10608                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10609                        " for package " + pkg.packageName);
10610            }
10611        }
10612
10613        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10614        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10615        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10616
10617        // Copy the derived override back to the parsed package, so that we can
10618        // update the package settings accordingly.
10619        pkg.cpuAbiOverride = cpuAbiOverride;
10620
10621        if (DEBUG_ABI_SELECTION) {
10622            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10623                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10624                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10625        }
10626
10627        // Push the derived path down into PackageSettings so we know what to
10628        // clean up at uninstall time.
10629        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10630
10631        if (DEBUG_ABI_SELECTION) {
10632            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10633                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10634                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10635        }
10636
10637        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10638        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10639            // We don't do this here during boot because we can do it all
10640            // at once after scanning all existing packages.
10641            //
10642            // We also do this *before* we perform dexopt on this package, so that
10643            // we can avoid redundant dexopts, and also to make sure we've got the
10644            // code and package path correct.
10645            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10646        }
10647
10648        if (mFactoryTest && pkg.requestedPermissions.contains(
10649                android.Manifest.permission.FACTORY_TEST)) {
10650            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10651        }
10652
10653        if (isSystemApp(pkg)) {
10654            pkgSetting.isOrphaned = true;
10655        }
10656
10657        // Take care of first install / last update times.
10658        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10659        if (currentTime != 0) {
10660            if (pkgSetting.firstInstallTime == 0) {
10661                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10662            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10663                pkgSetting.lastUpdateTime = currentTime;
10664            }
10665        } else if (pkgSetting.firstInstallTime == 0) {
10666            // We need *something*.  Take time time stamp of the file.
10667            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10668        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10669            if (scanFileTime != pkgSetting.timeStamp) {
10670                // A package on the system image has changed; consider this
10671                // to be an update.
10672                pkgSetting.lastUpdateTime = scanFileTime;
10673            }
10674        }
10675        pkgSetting.setTimeStamp(scanFileTime);
10676
10677        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10678            if (nonMutatedPs != null) {
10679                synchronized (mPackages) {
10680                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10681                }
10682            }
10683        } else {
10684            final int userId = user == null ? 0 : user.getIdentifier();
10685            // Modify state for the given package setting
10686            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10687                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10688            if (pkgSetting.getInstantApp(userId)) {
10689                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10690            }
10691        }
10692        return pkg;
10693    }
10694
10695    /**
10696     * Applies policy to the parsed package based upon the given policy flags.
10697     * Ensures the package is in a good state.
10698     * <p>
10699     * Implementation detail: This method must NOT have any side effect. It would
10700     * ideally be static, but, it requires locks to read system state.
10701     */
10702    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10703        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10704            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10705            if (pkg.applicationInfo.isDirectBootAware()) {
10706                // we're direct boot aware; set for all components
10707                for (PackageParser.Service s : pkg.services) {
10708                    s.info.encryptionAware = s.info.directBootAware = true;
10709                }
10710                for (PackageParser.Provider p : pkg.providers) {
10711                    p.info.encryptionAware = p.info.directBootAware = true;
10712                }
10713                for (PackageParser.Activity a : pkg.activities) {
10714                    a.info.encryptionAware = a.info.directBootAware = true;
10715                }
10716                for (PackageParser.Activity r : pkg.receivers) {
10717                    r.info.encryptionAware = r.info.directBootAware = true;
10718                }
10719            }
10720        } else {
10721            // Only allow system apps to be flagged as core apps.
10722            pkg.coreApp = false;
10723            // clear flags not applicable to regular apps
10724            pkg.applicationInfo.privateFlags &=
10725                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10726            pkg.applicationInfo.privateFlags &=
10727                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10728        }
10729        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10730
10731        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10732            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10733        }
10734
10735        if (!isSystemApp(pkg)) {
10736            // Only system apps can use these features.
10737            pkg.mOriginalPackages = null;
10738            pkg.mRealPackage = null;
10739            pkg.mAdoptPermissions = null;
10740        }
10741    }
10742
10743    /**
10744     * Asserts the parsed package is valid according to the given policy. If the
10745     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10746     * <p>
10747     * Implementation detail: This method must NOT have any side effects. It would
10748     * ideally be static, but, it requires locks to read system state.
10749     *
10750     * @throws PackageManagerException If the package fails any of the validation checks
10751     */
10752    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10753            throws PackageManagerException {
10754        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10755            assertCodePolicy(pkg);
10756        }
10757
10758        if (pkg.applicationInfo.getCodePath() == null ||
10759                pkg.applicationInfo.getResourcePath() == null) {
10760            // Bail out. The resource and code paths haven't been set.
10761            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10762                    "Code and resource paths haven't been set correctly");
10763        }
10764
10765        // Make sure we're not adding any bogus keyset info
10766        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10767        ksms.assertScannedPackageValid(pkg);
10768
10769        synchronized (mPackages) {
10770            // The special "android" package can only be defined once
10771            if (pkg.packageName.equals("android")) {
10772                if (mAndroidApplication != null) {
10773                    Slog.w(TAG, "*************************************************");
10774                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10775                    Slog.w(TAG, " codePath=" + pkg.codePath);
10776                    Slog.w(TAG, "*************************************************");
10777                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10778                            "Core android package being redefined.  Skipping.");
10779                }
10780            }
10781
10782            // A package name must be unique; don't allow duplicates
10783            if (mPackages.containsKey(pkg.packageName)) {
10784                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10785                        "Application package " + pkg.packageName
10786                        + " already installed.  Skipping duplicate.");
10787            }
10788
10789            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10790                // Static libs have a synthetic package name containing the version
10791                // but we still want the base name to be unique.
10792                if (mPackages.containsKey(pkg.manifestPackageName)) {
10793                    throw new PackageManagerException(
10794                            "Duplicate static shared lib provider package");
10795                }
10796
10797                // Static shared libraries should have at least O target SDK
10798                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10799                    throw new PackageManagerException(
10800                            "Packages declaring static-shared libs must target O SDK or higher");
10801                }
10802
10803                // Package declaring static a shared lib cannot be instant apps
10804                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10805                    throw new PackageManagerException(
10806                            "Packages declaring static-shared libs cannot be instant apps");
10807                }
10808
10809                // Package declaring static a shared lib cannot be renamed since the package
10810                // name is synthetic and apps can't code around package manager internals.
10811                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10812                    throw new PackageManagerException(
10813                            "Packages declaring static-shared libs cannot be renamed");
10814                }
10815
10816                // Package declaring static a shared lib cannot declare child packages
10817                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10818                    throw new PackageManagerException(
10819                            "Packages declaring static-shared libs cannot have child packages");
10820                }
10821
10822                // Package declaring static a shared lib cannot declare dynamic libs
10823                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10824                    throw new PackageManagerException(
10825                            "Packages declaring static-shared libs cannot declare dynamic libs");
10826                }
10827
10828                // Package declaring static a shared lib cannot declare shared users
10829                if (pkg.mSharedUserId != null) {
10830                    throw new PackageManagerException(
10831                            "Packages declaring static-shared libs cannot declare shared users");
10832                }
10833
10834                // Static shared libs cannot declare activities
10835                if (!pkg.activities.isEmpty()) {
10836                    throw new PackageManagerException(
10837                            "Static shared libs cannot declare activities");
10838                }
10839
10840                // Static shared libs cannot declare services
10841                if (!pkg.services.isEmpty()) {
10842                    throw new PackageManagerException(
10843                            "Static shared libs cannot declare services");
10844                }
10845
10846                // Static shared libs cannot declare providers
10847                if (!pkg.providers.isEmpty()) {
10848                    throw new PackageManagerException(
10849                            "Static shared libs cannot declare content providers");
10850                }
10851
10852                // Static shared libs cannot declare receivers
10853                if (!pkg.receivers.isEmpty()) {
10854                    throw new PackageManagerException(
10855                            "Static shared libs cannot declare broadcast receivers");
10856                }
10857
10858                // Static shared libs cannot declare permission groups
10859                if (!pkg.permissionGroups.isEmpty()) {
10860                    throw new PackageManagerException(
10861                            "Static shared libs cannot declare permission groups");
10862                }
10863
10864                // Static shared libs cannot declare permissions
10865                if (!pkg.permissions.isEmpty()) {
10866                    throw new PackageManagerException(
10867                            "Static shared libs cannot declare permissions");
10868                }
10869
10870                // Static shared libs cannot declare protected broadcasts
10871                if (pkg.protectedBroadcasts != null) {
10872                    throw new PackageManagerException(
10873                            "Static shared libs cannot declare protected broadcasts");
10874                }
10875
10876                // Static shared libs cannot be overlay targets
10877                if (pkg.mOverlayTarget != null) {
10878                    throw new PackageManagerException(
10879                            "Static shared libs cannot be overlay targets");
10880                }
10881
10882                // The version codes must be ordered as lib versions
10883                int minVersionCode = Integer.MIN_VALUE;
10884                int maxVersionCode = Integer.MAX_VALUE;
10885
10886                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10887                        pkg.staticSharedLibName);
10888                if (versionedLib != null) {
10889                    final int versionCount = versionedLib.size();
10890                    for (int i = 0; i < versionCount; i++) {
10891                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10892                        final int libVersionCode = libInfo.getDeclaringPackage()
10893                                .getVersionCode();
10894                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10895                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10896                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10897                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10898                        } else {
10899                            minVersionCode = maxVersionCode = libVersionCode;
10900                            break;
10901                        }
10902                    }
10903                }
10904                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10905                    throw new PackageManagerException("Static shared"
10906                            + " lib version codes must be ordered as lib versions");
10907                }
10908            }
10909
10910            // Only privileged apps and updated privileged apps can add child packages.
10911            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10912                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10913                    throw new PackageManagerException("Only privileged apps can add child "
10914                            + "packages. Ignoring package " + pkg.packageName);
10915                }
10916                final int childCount = pkg.childPackages.size();
10917                for (int i = 0; i < childCount; i++) {
10918                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10919                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10920                            childPkg.packageName)) {
10921                        throw new PackageManagerException("Can't override child of "
10922                                + "another disabled app. Ignoring package " + pkg.packageName);
10923                    }
10924                }
10925            }
10926
10927            // If we're only installing presumed-existing packages, require that the
10928            // scanned APK is both already known and at the path previously established
10929            // for it.  Previously unknown packages we pick up normally, but if we have an
10930            // a priori expectation about this package's install presence, enforce it.
10931            // With a singular exception for new system packages. When an OTA contains
10932            // a new system package, we allow the codepath to change from a system location
10933            // to the user-installed location. If we don't allow this change, any newer,
10934            // user-installed version of the application will be ignored.
10935            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10936                if (mExpectingBetter.containsKey(pkg.packageName)) {
10937                    logCriticalInfo(Log.WARN,
10938                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10939                } else {
10940                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10941                    if (known != null) {
10942                        if (DEBUG_PACKAGE_SCANNING) {
10943                            Log.d(TAG, "Examining " + pkg.codePath
10944                                    + " and requiring known paths " + known.codePathString
10945                                    + " & " + known.resourcePathString);
10946                        }
10947                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10948                                || !pkg.applicationInfo.getResourcePath().equals(
10949                                        known.resourcePathString)) {
10950                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10951                                    "Application package " + pkg.packageName
10952                                    + " found at " + pkg.applicationInfo.getCodePath()
10953                                    + " but expected at " + known.codePathString
10954                                    + "; ignoring.");
10955                        }
10956                    }
10957                }
10958            }
10959
10960            // Verify that this new package doesn't have any content providers
10961            // that conflict with existing packages.  Only do this if the
10962            // package isn't already installed, since we don't want to break
10963            // things that are installed.
10964            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10965                final int N = pkg.providers.size();
10966                int i;
10967                for (i=0; i<N; i++) {
10968                    PackageParser.Provider p = pkg.providers.get(i);
10969                    if (p.info.authority != null) {
10970                        String names[] = p.info.authority.split(";");
10971                        for (int j = 0; j < names.length; j++) {
10972                            if (mProvidersByAuthority.containsKey(names[j])) {
10973                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10974                                final String otherPackageName =
10975                                        ((other != null && other.getComponentName() != null) ?
10976                                                other.getComponentName().getPackageName() : "?");
10977                                throw new PackageManagerException(
10978                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10979                                        "Can't install because provider name " + names[j]
10980                                                + " (in package " + pkg.applicationInfo.packageName
10981                                                + ") is already used by " + otherPackageName);
10982                            }
10983                        }
10984                    }
10985                }
10986            }
10987        }
10988    }
10989
10990    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10991            int type, String declaringPackageName, int declaringVersionCode) {
10992        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10993        if (versionedLib == null) {
10994            versionedLib = new SparseArray<>();
10995            mSharedLibraries.put(name, versionedLib);
10996            if (type == SharedLibraryInfo.TYPE_STATIC) {
10997                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10998            }
10999        } else if (versionedLib.indexOfKey(version) >= 0) {
11000            return false;
11001        }
11002        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11003                version, type, declaringPackageName, declaringVersionCode);
11004        versionedLib.put(version, libEntry);
11005        return true;
11006    }
11007
11008    private boolean removeSharedLibraryLPw(String name, int version) {
11009        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11010        if (versionedLib == null) {
11011            return false;
11012        }
11013        final int libIdx = versionedLib.indexOfKey(version);
11014        if (libIdx < 0) {
11015            return false;
11016        }
11017        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11018        versionedLib.remove(version);
11019        if (versionedLib.size() <= 0) {
11020            mSharedLibraries.remove(name);
11021            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11022                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11023                        .getPackageName());
11024            }
11025        }
11026        return true;
11027    }
11028
11029    /**
11030     * Adds a scanned package to the system. When this method is finished, the package will
11031     * be available for query, resolution, etc...
11032     */
11033    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11034            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11035        final String pkgName = pkg.packageName;
11036        if (mCustomResolverComponentName != null &&
11037                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11038            setUpCustomResolverActivity(pkg);
11039        }
11040
11041        if (pkg.packageName.equals("android")) {
11042            synchronized (mPackages) {
11043                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11044                    // Set up information for our fall-back user intent resolution activity.
11045                    mPlatformPackage = pkg;
11046                    pkg.mVersionCode = mSdkVersion;
11047                    mAndroidApplication = pkg.applicationInfo;
11048                    if (!mResolverReplaced) {
11049                        mResolveActivity.applicationInfo = mAndroidApplication;
11050                        mResolveActivity.name = ResolverActivity.class.getName();
11051                        mResolveActivity.packageName = mAndroidApplication.packageName;
11052                        mResolveActivity.processName = "system:ui";
11053                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11054                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11055                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11056                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11057                        mResolveActivity.exported = true;
11058                        mResolveActivity.enabled = true;
11059                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11060                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11061                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11062                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11063                                | ActivityInfo.CONFIG_ORIENTATION
11064                                | ActivityInfo.CONFIG_KEYBOARD
11065                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11066                        mResolveInfo.activityInfo = mResolveActivity;
11067                        mResolveInfo.priority = 0;
11068                        mResolveInfo.preferredOrder = 0;
11069                        mResolveInfo.match = 0;
11070                        mResolveComponentName = new ComponentName(
11071                                mAndroidApplication.packageName, mResolveActivity.name);
11072                    }
11073                }
11074            }
11075        }
11076
11077        ArrayList<PackageParser.Package> clientLibPkgs = null;
11078        // writer
11079        synchronized (mPackages) {
11080            boolean hasStaticSharedLibs = false;
11081
11082            // Any app can add new static shared libraries
11083            if (pkg.staticSharedLibName != null) {
11084                // Static shared libs don't allow renaming as they have synthetic package
11085                // names to allow install of multiple versions, so use name from manifest.
11086                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11087                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11088                        pkg.manifestPackageName, pkg.mVersionCode)) {
11089                    hasStaticSharedLibs = true;
11090                } else {
11091                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11092                                + pkg.staticSharedLibName + " already exists; skipping");
11093                }
11094                // Static shared libs cannot be updated once installed since they
11095                // use synthetic package name which includes the version code, so
11096                // not need to update other packages's shared lib dependencies.
11097            }
11098
11099            if (!hasStaticSharedLibs
11100                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11101                // Only system apps can add new dynamic shared libraries.
11102                if (pkg.libraryNames != null) {
11103                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11104                        String name = pkg.libraryNames.get(i);
11105                        boolean allowed = false;
11106                        if (pkg.isUpdatedSystemApp()) {
11107                            // New library entries can only be added through the
11108                            // system image.  This is important to get rid of a lot
11109                            // of nasty edge cases: for example if we allowed a non-
11110                            // system update of the app to add a library, then uninstalling
11111                            // the update would make the library go away, and assumptions
11112                            // we made such as through app install filtering would now
11113                            // have allowed apps on the device which aren't compatible
11114                            // with it.  Better to just have the restriction here, be
11115                            // conservative, and create many fewer cases that can negatively
11116                            // impact the user experience.
11117                            final PackageSetting sysPs = mSettings
11118                                    .getDisabledSystemPkgLPr(pkg.packageName);
11119                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11120                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11121                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11122                                        allowed = true;
11123                                        break;
11124                                    }
11125                                }
11126                            }
11127                        } else {
11128                            allowed = true;
11129                        }
11130                        if (allowed) {
11131                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11132                                    SharedLibraryInfo.VERSION_UNDEFINED,
11133                                    SharedLibraryInfo.TYPE_DYNAMIC,
11134                                    pkg.packageName, pkg.mVersionCode)) {
11135                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11136                                        + name + " already exists; skipping");
11137                            }
11138                        } else {
11139                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11140                                    + name + " that is not declared on system image; skipping");
11141                        }
11142                    }
11143
11144                    if ((scanFlags & SCAN_BOOTING) == 0) {
11145                        // If we are not booting, we need to update any applications
11146                        // that are clients of our shared library.  If we are booting,
11147                        // this will all be done once the scan is complete.
11148                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11149                    }
11150                }
11151            }
11152        }
11153
11154        if ((scanFlags & SCAN_BOOTING) != 0) {
11155            // No apps can run during boot scan, so they don't need to be frozen
11156        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11157            // Caller asked to not kill app, so it's probably not frozen
11158        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11159            // Caller asked us to ignore frozen check for some reason; they
11160            // probably didn't know the package name
11161        } else {
11162            // We're doing major surgery on this package, so it better be frozen
11163            // right now to keep it from launching
11164            checkPackageFrozen(pkgName);
11165        }
11166
11167        // Also need to kill any apps that are dependent on the library.
11168        if (clientLibPkgs != null) {
11169            for (int i=0; i<clientLibPkgs.size(); i++) {
11170                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11171                killApplication(clientPkg.applicationInfo.packageName,
11172                        clientPkg.applicationInfo.uid, "update lib");
11173            }
11174        }
11175
11176        // writer
11177        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11178
11179        synchronized (mPackages) {
11180            // We don't expect installation to fail beyond this point
11181
11182            // Add the new setting to mSettings
11183            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11184            // Add the new setting to mPackages
11185            mPackages.put(pkg.applicationInfo.packageName, pkg);
11186            // Make sure we don't accidentally delete its data.
11187            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11188            while (iter.hasNext()) {
11189                PackageCleanItem item = iter.next();
11190                if (pkgName.equals(item.packageName)) {
11191                    iter.remove();
11192                }
11193            }
11194
11195            // Add the package's KeySets to the global KeySetManagerService
11196            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11197            ksms.addScannedPackageLPw(pkg);
11198
11199            int N = pkg.providers.size();
11200            StringBuilder r = null;
11201            int i;
11202            for (i=0; i<N; i++) {
11203                PackageParser.Provider p = pkg.providers.get(i);
11204                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11205                        p.info.processName);
11206                mProviders.addProvider(p);
11207                p.syncable = p.info.isSyncable;
11208                if (p.info.authority != null) {
11209                    String names[] = p.info.authority.split(";");
11210                    p.info.authority = null;
11211                    for (int j = 0; j < names.length; j++) {
11212                        if (j == 1 && p.syncable) {
11213                            // We only want the first authority for a provider to possibly be
11214                            // syncable, so if we already added this provider using a different
11215                            // authority clear the syncable flag. We copy the provider before
11216                            // changing it because the mProviders object contains a reference
11217                            // to a provider that we don't want to change.
11218                            // Only do this for the second authority since the resulting provider
11219                            // object can be the same for all future authorities for this provider.
11220                            p = new PackageParser.Provider(p);
11221                            p.syncable = false;
11222                        }
11223                        if (!mProvidersByAuthority.containsKey(names[j])) {
11224                            mProvidersByAuthority.put(names[j], p);
11225                            if (p.info.authority == null) {
11226                                p.info.authority = names[j];
11227                            } else {
11228                                p.info.authority = p.info.authority + ";" + names[j];
11229                            }
11230                            if (DEBUG_PACKAGE_SCANNING) {
11231                                if (chatty)
11232                                    Log.d(TAG, "Registered content provider: " + names[j]
11233                                            + ", className = " + p.info.name + ", isSyncable = "
11234                                            + p.info.isSyncable);
11235                            }
11236                        } else {
11237                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11238                            Slog.w(TAG, "Skipping provider name " + names[j] +
11239                                    " (in package " + pkg.applicationInfo.packageName +
11240                                    "): name already used by "
11241                                    + ((other != null && other.getComponentName() != null)
11242                                            ? other.getComponentName().getPackageName() : "?"));
11243                        }
11244                    }
11245                }
11246                if (chatty) {
11247                    if (r == null) {
11248                        r = new StringBuilder(256);
11249                    } else {
11250                        r.append(' ');
11251                    }
11252                    r.append(p.info.name);
11253                }
11254            }
11255            if (r != null) {
11256                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11257            }
11258
11259            N = pkg.services.size();
11260            r = null;
11261            for (i=0; i<N; i++) {
11262                PackageParser.Service s = pkg.services.get(i);
11263                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11264                        s.info.processName);
11265                mServices.addService(s);
11266                if (chatty) {
11267                    if (r == null) {
11268                        r = new StringBuilder(256);
11269                    } else {
11270                        r.append(' ');
11271                    }
11272                    r.append(s.info.name);
11273                }
11274            }
11275            if (r != null) {
11276                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11277            }
11278
11279            N = pkg.receivers.size();
11280            r = null;
11281            for (i=0; i<N; i++) {
11282                PackageParser.Activity a = pkg.receivers.get(i);
11283                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11284                        a.info.processName);
11285                mReceivers.addActivity(a, "receiver");
11286                if (chatty) {
11287                    if (r == null) {
11288                        r = new StringBuilder(256);
11289                    } else {
11290                        r.append(' ');
11291                    }
11292                    r.append(a.info.name);
11293                }
11294            }
11295            if (r != null) {
11296                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11297            }
11298
11299            N = pkg.activities.size();
11300            r = null;
11301            for (i=0; i<N; i++) {
11302                PackageParser.Activity a = pkg.activities.get(i);
11303                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11304                        a.info.processName);
11305                mActivities.addActivity(a, "activity");
11306                if (chatty) {
11307                    if (r == null) {
11308                        r = new StringBuilder(256);
11309                    } else {
11310                        r.append(' ');
11311                    }
11312                    r.append(a.info.name);
11313                }
11314            }
11315            if (r != null) {
11316                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11317            }
11318
11319            N = pkg.permissionGroups.size();
11320            r = null;
11321            for (i=0; i<N; i++) {
11322                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11323                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11324                final String curPackageName = cur == null ? null : cur.info.packageName;
11325                // Dont allow ephemeral apps to define new permission groups.
11326                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11327                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11328                            + pg.info.packageName
11329                            + " ignored: instant apps cannot define new permission groups.");
11330                    continue;
11331                }
11332                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11333                if (cur == null || isPackageUpdate) {
11334                    mPermissionGroups.put(pg.info.name, pg);
11335                    if (chatty) {
11336                        if (r == null) {
11337                            r = new StringBuilder(256);
11338                        } else {
11339                            r.append(' ');
11340                        }
11341                        if (isPackageUpdate) {
11342                            r.append("UPD:");
11343                        }
11344                        r.append(pg.info.name);
11345                    }
11346                } else {
11347                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11348                            + pg.info.packageName + " ignored: original from "
11349                            + cur.info.packageName);
11350                    if (chatty) {
11351                        if (r == null) {
11352                            r = new StringBuilder(256);
11353                        } else {
11354                            r.append(' ');
11355                        }
11356                        r.append("DUP:");
11357                        r.append(pg.info.name);
11358                    }
11359                }
11360            }
11361            if (r != null) {
11362                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11363            }
11364
11365            N = pkg.permissions.size();
11366            r = null;
11367            for (i=0; i<N; i++) {
11368                PackageParser.Permission p = pkg.permissions.get(i);
11369
11370                // Dont allow ephemeral apps to define new permissions.
11371                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11372                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11373                            + p.info.packageName
11374                            + " ignored: instant apps cannot define new permissions.");
11375                    continue;
11376                }
11377
11378                // Assume by default that we did not install this permission into the system.
11379                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11380
11381                // Now that permission groups have a special meaning, we ignore permission
11382                // groups for legacy apps to prevent unexpected behavior. In particular,
11383                // permissions for one app being granted to someone just because they happen
11384                // to be in a group defined by another app (before this had no implications).
11385                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11386                    p.group = mPermissionGroups.get(p.info.group);
11387                    // Warn for a permission in an unknown group.
11388                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11389                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11390                                + p.info.packageName + " in an unknown group " + p.info.group);
11391                    }
11392                }
11393
11394                ArrayMap<String, BasePermission> permissionMap =
11395                        p.tree ? mSettings.mPermissionTrees
11396                                : mSettings.mPermissions;
11397                BasePermission bp = permissionMap.get(p.info.name);
11398
11399                // Allow system apps to redefine non-system permissions
11400                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11401                    final boolean currentOwnerIsSystem = (bp.perm != null
11402                            && isSystemApp(bp.perm.owner));
11403                    if (isSystemApp(p.owner)) {
11404                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11405                            // It's a built-in permission and no owner, take ownership now
11406                            bp.packageSetting = pkgSetting;
11407                            bp.perm = p;
11408                            bp.uid = pkg.applicationInfo.uid;
11409                            bp.sourcePackage = p.info.packageName;
11410                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11411                        } else if (!currentOwnerIsSystem) {
11412                            String msg = "New decl " + p.owner + " of permission  "
11413                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11414                            reportSettingsProblem(Log.WARN, msg);
11415                            bp = null;
11416                        }
11417                    }
11418                }
11419
11420                if (bp == null) {
11421                    bp = new BasePermission(p.info.name, p.info.packageName,
11422                            BasePermission.TYPE_NORMAL);
11423                    permissionMap.put(p.info.name, bp);
11424                }
11425
11426                if (bp.perm == null) {
11427                    if (bp.sourcePackage == null
11428                            || bp.sourcePackage.equals(p.info.packageName)) {
11429                        BasePermission tree = findPermissionTreeLP(p.info.name);
11430                        if (tree == null
11431                                || tree.sourcePackage.equals(p.info.packageName)) {
11432                            bp.packageSetting = pkgSetting;
11433                            bp.perm = p;
11434                            bp.uid = pkg.applicationInfo.uid;
11435                            bp.sourcePackage = p.info.packageName;
11436                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11437                            if (chatty) {
11438                                if (r == null) {
11439                                    r = new StringBuilder(256);
11440                                } else {
11441                                    r.append(' ');
11442                                }
11443                                r.append(p.info.name);
11444                            }
11445                        } else {
11446                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11447                                    + p.info.packageName + " ignored: base tree "
11448                                    + tree.name + " is from package "
11449                                    + tree.sourcePackage);
11450                        }
11451                    } else {
11452                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11453                                + p.info.packageName + " ignored: original from "
11454                                + bp.sourcePackage);
11455                    }
11456                } else if (chatty) {
11457                    if (r == null) {
11458                        r = new StringBuilder(256);
11459                    } else {
11460                        r.append(' ');
11461                    }
11462                    r.append("DUP:");
11463                    r.append(p.info.name);
11464                }
11465                if (bp.perm == p) {
11466                    bp.protectionLevel = p.info.protectionLevel;
11467                }
11468            }
11469
11470            if (r != null) {
11471                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11472            }
11473
11474            N = pkg.instrumentation.size();
11475            r = null;
11476            for (i=0; i<N; i++) {
11477                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11478                a.info.packageName = pkg.applicationInfo.packageName;
11479                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11480                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11481                a.info.splitNames = pkg.splitNames;
11482                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11483                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11484                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11485                a.info.dataDir = pkg.applicationInfo.dataDir;
11486                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11487                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11488                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11489                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11490                mInstrumentation.put(a.getComponentName(), a);
11491                if (chatty) {
11492                    if (r == null) {
11493                        r = new StringBuilder(256);
11494                    } else {
11495                        r.append(' ');
11496                    }
11497                    r.append(a.info.name);
11498                }
11499            }
11500            if (r != null) {
11501                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11502            }
11503
11504            if (pkg.protectedBroadcasts != null) {
11505                N = pkg.protectedBroadcasts.size();
11506                synchronized (mProtectedBroadcasts) {
11507                    for (i = 0; i < N; i++) {
11508                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11509                    }
11510                }
11511            }
11512        }
11513
11514        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11515    }
11516
11517    /**
11518     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11519     * is derived purely on the basis of the contents of {@code scanFile} and
11520     * {@code cpuAbiOverride}.
11521     *
11522     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11523     */
11524    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11525                                 String cpuAbiOverride, boolean extractLibs,
11526                                 File appLib32InstallDir)
11527            throws PackageManagerException {
11528        // Give ourselves some initial paths; we'll come back for another
11529        // pass once we've determined ABI below.
11530        setNativeLibraryPaths(pkg, appLib32InstallDir);
11531
11532        // We would never need to extract libs for forward-locked and external packages,
11533        // since the container service will do it for us. We shouldn't attempt to
11534        // extract libs from system app when it was not updated.
11535        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11536                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11537            extractLibs = false;
11538        }
11539
11540        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11541        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11542
11543        NativeLibraryHelper.Handle handle = null;
11544        try {
11545            handle = NativeLibraryHelper.Handle.create(pkg);
11546            // TODO(multiArch): This can be null for apps that didn't go through the
11547            // usual installation process. We can calculate it again, like we
11548            // do during install time.
11549            //
11550            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11551            // unnecessary.
11552            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11553
11554            // Null out the abis so that they can be recalculated.
11555            pkg.applicationInfo.primaryCpuAbi = null;
11556            pkg.applicationInfo.secondaryCpuAbi = null;
11557            if (isMultiArch(pkg.applicationInfo)) {
11558                // Warn if we've set an abiOverride for multi-lib packages..
11559                // By definition, we need to copy both 32 and 64 bit libraries for
11560                // such packages.
11561                if (pkg.cpuAbiOverride != null
11562                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11563                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11564                }
11565
11566                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11567                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11568                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11569                    if (extractLibs) {
11570                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11571                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11572                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11573                                useIsaSpecificSubdirs);
11574                    } else {
11575                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11576                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11577                    }
11578                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11579                }
11580
11581                // Shared library native code should be in the APK zip aligned
11582                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11583                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11584                            "Shared library native lib extraction not supported");
11585                }
11586
11587                maybeThrowExceptionForMultiArchCopy(
11588                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11589
11590                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11591                    if (extractLibs) {
11592                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11593                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11594                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11595                                useIsaSpecificSubdirs);
11596                    } else {
11597                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11598                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11599                    }
11600                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11601                }
11602
11603                maybeThrowExceptionForMultiArchCopy(
11604                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11605
11606                if (abi64 >= 0) {
11607                    // Shared library native libs should be in the APK zip aligned
11608                    if (extractLibs && pkg.isLibrary()) {
11609                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11610                                "Shared library native lib extraction not supported");
11611                    }
11612                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11613                }
11614
11615                if (abi32 >= 0) {
11616                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11617                    if (abi64 >= 0) {
11618                        if (pkg.use32bitAbi) {
11619                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11620                            pkg.applicationInfo.primaryCpuAbi = abi;
11621                        } else {
11622                            pkg.applicationInfo.secondaryCpuAbi = abi;
11623                        }
11624                    } else {
11625                        pkg.applicationInfo.primaryCpuAbi = abi;
11626                    }
11627                }
11628            } else {
11629                String[] abiList = (cpuAbiOverride != null) ?
11630                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11631
11632                // Enable gross and lame hacks for apps that are built with old
11633                // SDK tools. We must scan their APKs for renderscript bitcode and
11634                // not launch them if it's present. Don't bother checking on devices
11635                // that don't have 64 bit support.
11636                boolean needsRenderScriptOverride = false;
11637                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11638                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11639                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11640                    needsRenderScriptOverride = true;
11641                }
11642
11643                final int copyRet;
11644                if (extractLibs) {
11645                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11646                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11647                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11648                } else {
11649                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11650                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11651                }
11652                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11653
11654                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11655                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11656                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11657                }
11658
11659                if (copyRet >= 0) {
11660                    // Shared libraries that have native libs must be multi-architecture
11661                    if (pkg.isLibrary()) {
11662                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11663                                "Shared library with native libs must be multiarch");
11664                    }
11665                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11666                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11667                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11668                } else if (needsRenderScriptOverride) {
11669                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11670                }
11671            }
11672        } catch (IOException ioe) {
11673            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11674        } finally {
11675            IoUtils.closeQuietly(handle);
11676        }
11677
11678        // Now that we've calculated the ABIs and determined if it's an internal app,
11679        // we will go ahead and populate the nativeLibraryPath.
11680        setNativeLibraryPaths(pkg, appLib32InstallDir);
11681    }
11682
11683    /**
11684     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11685     * i.e, so that all packages can be run inside a single process if required.
11686     *
11687     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11688     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11689     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11690     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11691     * updating a package that belongs to a shared user.
11692     *
11693     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11694     * adds unnecessary complexity.
11695     */
11696    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11697            PackageParser.Package scannedPackage) {
11698        String requiredInstructionSet = null;
11699        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11700            requiredInstructionSet = VMRuntime.getInstructionSet(
11701                     scannedPackage.applicationInfo.primaryCpuAbi);
11702        }
11703
11704        PackageSetting requirer = null;
11705        for (PackageSetting ps : packagesForUser) {
11706            // If packagesForUser contains scannedPackage, we skip it. This will happen
11707            // when scannedPackage is an update of an existing package. Without this check,
11708            // we will never be able to change the ABI of any package belonging to a shared
11709            // user, even if it's compatible with other packages.
11710            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11711                if (ps.primaryCpuAbiString == null) {
11712                    continue;
11713                }
11714
11715                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11716                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11717                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11718                    // this but there's not much we can do.
11719                    String errorMessage = "Instruction set mismatch, "
11720                            + ((requirer == null) ? "[caller]" : requirer)
11721                            + " requires " + requiredInstructionSet + " whereas " + ps
11722                            + " requires " + instructionSet;
11723                    Slog.w(TAG, errorMessage);
11724                }
11725
11726                if (requiredInstructionSet == null) {
11727                    requiredInstructionSet = instructionSet;
11728                    requirer = ps;
11729                }
11730            }
11731        }
11732
11733        if (requiredInstructionSet != null) {
11734            String adjustedAbi;
11735            if (requirer != null) {
11736                // requirer != null implies that either scannedPackage was null or that scannedPackage
11737                // did not require an ABI, in which case we have to adjust scannedPackage to match
11738                // the ABI of the set (which is the same as requirer's ABI)
11739                adjustedAbi = requirer.primaryCpuAbiString;
11740                if (scannedPackage != null) {
11741                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11742                }
11743            } else {
11744                // requirer == null implies that we're updating all ABIs in the set to
11745                // match scannedPackage.
11746                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11747            }
11748
11749            for (PackageSetting ps : packagesForUser) {
11750                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11751                    if (ps.primaryCpuAbiString != null) {
11752                        continue;
11753                    }
11754
11755                    ps.primaryCpuAbiString = adjustedAbi;
11756                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11757                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11758                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11759                        if (DEBUG_ABI_SELECTION) {
11760                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11761                                    + " (requirer="
11762                                    + (requirer != null ? requirer.pkg : "null")
11763                                    + ", scannedPackage="
11764                                    + (scannedPackage != null ? scannedPackage : "null")
11765                                    + ")");
11766                        }
11767                        try {
11768                            mInstaller.rmdex(ps.codePathString,
11769                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11770                        } catch (InstallerException ignored) {
11771                        }
11772                    }
11773                }
11774            }
11775        }
11776    }
11777
11778    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11779        synchronized (mPackages) {
11780            mResolverReplaced = true;
11781            // Set up information for custom user intent resolution activity.
11782            mResolveActivity.applicationInfo = pkg.applicationInfo;
11783            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11784            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11785            mResolveActivity.processName = pkg.applicationInfo.packageName;
11786            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11787            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11788                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11789            mResolveActivity.theme = 0;
11790            mResolveActivity.exported = true;
11791            mResolveActivity.enabled = true;
11792            mResolveInfo.activityInfo = mResolveActivity;
11793            mResolveInfo.priority = 0;
11794            mResolveInfo.preferredOrder = 0;
11795            mResolveInfo.match = 0;
11796            mResolveComponentName = mCustomResolverComponentName;
11797            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11798                    mResolveComponentName);
11799        }
11800    }
11801
11802    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11803        if (installerActivity == null) {
11804            if (DEBUG_EPHEMERAL) {
11805                Slog.d(TAG, "Clear ephemeral installer activity");
11806            }
11807            mInstantAppInstallerActivity = null;
11808            return;
11809        }
11810
11811        if (DEBUG_EPHEMERAL) {
11812            Slog.d(TAG, "Set ephemeral installer activity: "
11813                    + installerActivity.getComponentName());
11814        }
11815        // Set up information for ephemeral installer activity
11816        mInstantAppInstallerActivity = installerActivity;
11817        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11818                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11819        mInstantAppInstallerActivity.exported = true;
11820        mInstantAppInstallerActivity.enabled = true;
11821        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11822        mInstantAppInstallerInfo.priority = 0;
11823        mInstantAppInstallerInfo.preferredOrder = 1;
11824        mInstantAppInstallerInfo.isDefault = true;
11825        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11826                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11827    }
11828
11829    private static String calculateBundledApkRoot(final String codePathString) {
11830        final File codePath = new File(codePathString);
11831        final File codeRoot;
11832        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11833            codeRoot = Environment.getRootDirectory();
11834        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11835            codeRoot = Environment.getOemDirectory();
11836        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11837            codeRoot = Environment.getVendorDirectory();
11838        } else {
11839            // Unrecognized code path; take its top real segment as the apk root:
11840            // e.g. /something/app/blah.apk => /something
11841            try {
11842                File f = codePath.getCanonicalFile();
11843                File parent = f.getParentFile();    // non-null because codePath is a file
11844                File tmp;
11845                while ((tmp = parent.getParentFile()) != null) {
11846                    f = parent;
11847                    parent = tmp;
11848                }
11849                codeRoot = f;
11850                Slog.w(TAG, "Unrecognized code path "
11851                        + codePath + " - using " + codeRoot);
11852            } catch (IOException e) {
11853                // Can't canonicalize the code path -- shenanigans?
11854                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11855                return Environment.getRootDirectory().getPath();
11856            }
11857        }
11858        return codeRoot.getPath();
11859    }
11860
11861    /**
11862     * Derive and set the location of native libraries for the given package,
11863     * which varies depending on where and how the package was installed.
11864     */
11865    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11866        final ApplicationInfo info = pkg.applicationInfo;
11867        final String codePath = pkg.codePath;
11868        final File codeFile = new File(codePath);
11869        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11870        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11871
11872        info.nativeLibraryRootDir = null;
11873        info.nativeLibraryRootRequiresIsa = false;
11874        info.nativeLibraryDir = null;
11875        info.secondaryNativeLibraryDir = null;
11876
11877        if (isApkFile(codeFile)) {
11878            // Monolithic install
11879            if (bundledApp) {
11880                // If "/system/lib64/apkname" exists, assume that is the per-package
11881                // native library directory to use; otherwise use "/system/lib/apkname".
11882                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11883                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11884                        getPrimaryInstructionSet(info));
11885
11886                // This is a bundled system app so choose the path based on the ABI.
11887                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11888                // is just the default path.
11889                final String apkName = deriveCodePathName(codePath);
11890                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11891                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11892                        apkName).getAbsolutePath();
11893
11894                if (info.secondaryCpuAbi != null) {
11895                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11896                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11897                            secondaryLibDir, apkName).getAbsolutePath();
11898                }
11899            } else if (asecApp) {
11900                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11901                        .getAbsolutePath();
11902            } else {
11903                final String apkName = deriveCodePathName(codePath);
11904                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11905                        .getAbsolutePath();
11906            }
11907
11908            info.nativeLibraryRootRequiresIsa = false;
11909            info.nativeLibraryDir = info.nativeLibraryRootDir;
11910        } else {
11911            // Cluster install
11912            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11913            info.nativeLibraryRootRequiresIsa = true;
11914
11915            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11916                    getPrimaryInstructionSet(info)).getAbsolutePath();
11917
11918            if (info.secondaryCpuAbi != null) {
11919                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11920                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11921            }
11922        }
11923    }
11924
11925    /**
11926     * Calculate the abis and roots for a bundled app. These can uniquely
11927     * be determined from the contents of the system partition, i.e whether
11928     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11929     * of this information, and instead assume that the system was built
11930     * sensibly.
11931     */
11932    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11933                                           PackageSetting pkgSetting) {
11934        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11935
11936        // If "/system/lib64/apkname" exists, assume that is the per-package
11937        // native library directory to use; otherwise use "/system/lib/apkname".
11938        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11939        setBundledAppAbi(pkg, apkRoot, apkName);
11940        // pkgSetting might be null during rescan following uninstall of updates
11941        // to a bundled app, so accommodate that possibility.  The settings in
11942        // that case will be established later from the parsed package.
11943        //
11944        // If the settings aren't null, sync them up with what we've just derived.
11945        // note that apkRoot isn't stored in the package settings.
11946        if (pkgSetting != null) {
11947            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11948            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11949        }
11950    }
11951
11952    /**
11953     * Deduces the ABI of a bundled app and sets the relevant fields on the
11954     * parsed pkg object.
11955     *
11956     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11957     *        under which system libraries are installed.
11958     * @param apkName the name of the installed package.
11959     */
11960    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11961        final File codeFile = new File(pkg.codePath);
11962
11963        final boolean has64BitLibs;
11964        final boolean has32BitLibs;
11965        if (isApkFile(codeFile)) {
11966            // Monolithic install
11967            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11968            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11969        } else {
11970            // Cluster install
11971            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11972            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11973                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11974                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11975                has64BitLibs = (new File(rootDir, isa)).exists();
11976            } else {
11977                has64BitLibs = false;
11978            }
11979            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11980                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11981                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11982                has32BitLibs = (new File(rootDir, isa)).exists();
11983            } else {
11984                has32BitLibs = false;
11985            }
11986        }
11987
11988        if (has64BitLibs && !has32BitLibs) {
11989            // The package has 64 bit libs, but not 32 bit libs. Its primary
11990            // ABI should be 64 bit. We can safely assume here that the bundled
11991            // native libraries correspond to the most preferred ABI in the list.
11992
11993            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11994            pkg.applicationInfo.secondaryCpuAbi = null;
11995        } else if (has32BitLibs && !has64BitLibs) {
11996            // The package has 32 bit libs but not 64 bit libs. Its primary
11997            // ABI should be 32 bit.
11998
11999            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12000            pkg.applicationInfo.secondaryCpuAbi = null;
12001        } else if (has32BitLibs && has64BitLibs) {
12002            // The application has both 64 and 32 bit bundled libraries. We check
12003            // here that the app declares multiArch support, and warn if it doesn't.
12004            //
12005            // We will be lenient here and record both ABIs. The primary will be the
12006            // ABI that's higher on the list, i.e, a device that's configured to prefer
12007            // 64 bit apps will see a 64 bit primary ABI,
12008
12009            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12010                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12011            }
12012
12013            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12014                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12015                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12016            } else {
12017                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12018                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12019            }
12020        } else {
12021            pkg.applicationInfo.primaryCpuAbi = null;
12022            pkg.applicationInfo.secondaryCpuAbi = null;
12023        }
12024    }
12025
12026    private void killApplication(String pkgName, int appId, String reason) {
12027        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12028    }
12029
12030    private void killApplication(String pkgName, int appId, int userId, String reason) {
12031        // Request the ActivityManager to kill the process(only for existing packages)
12032        // so that we do not end up in a confused state while the user is still using the older
12033        // version of the application while the new one gets installed.
12034        final long token = Binder.clearCallingIdentity();
12035        try {
12036            IActivityManager am = ActivityManager.getService();
12037            if (am != null) {
12038                try {
12039                    am.killApplication(pkgName, appId, userId, reason);
12040                } catch (RemoteException e) {
12041                }
12042            }
12043        } finally {
12044            Binder.restoreCallingIdentity(token);
12045        }
12046    }
12047
12048    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12049        // Remove the parent package setting
12050        PackageSetting ps = (PackageSetting) pkg.mExtras;
12051        if (ps != null) {
12052            removePackageLI(ps, chatty);
12053        }
12054        // Remove the child package setting
12055        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12056        for (int i = 0; i < childCount; i++) {
12057            PackageParser.Package childPkg = pkg.childPackages.get(i);
12058            ps = (PackageSetting) childPkg.mExtras;
12059            if (ps != null) {
12060                removePackageLI(ps, chatty);
12061            }
12062        }
12063    }
12064
12065    void removePackageLI(PackageSetting ps, boolean chatty) {
12066        if (DEBUG_INSTALL) {
12067            if (chatty)
12068                Log.d(TAG, "Removing package " + ps.name);
12069        }
12070
12071        // writer
12072        synchronized (mPackages) {
12073            mPackages.remove(ps.name);
12074            final PackageParser.Package pkg = ps.pkg;
12075            if (pkg != null) {
12076                cleanPackageDataStructuresLILPw(pkg, chatty);
12077            }
12078        }
12079    }
12080
12081    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12082        if (DEBUG_INSTALL) {
12083            if (chatty)
12084                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12085        }
12086
12087        // writer
12088        synchronized (mPackages) {
12089            // Remove the parent package
12090            mPackages.remove(pkg.applicationInfo.packageName);
12091            cleanPackageDataStructuresLILPw(pkg, chatty);
12092
12093            // Remove the child packages
12094            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12095            for (int i = 0; i < childCount; i++) {
12096                PackageParser.Package childPkg = pkg.childPackages.get(i);
12097                mPackages.remove(childPkg.applicationInfo.packageName);
12098                cleanPackageDataStructuresLILPw(childPkg, chatty);
12099            }
12100        }
12101    }
12102
12103    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12104        int N = pkg.providers.size();
12105        StringBuilder r = null;
12106        int i;
12107        for (i=0; i<N; i++) {
12108            PackageParser.Provider p = pkg.providers.get(i);
12109            mProviders.removeProvider(p);
12110            if (p.info.authority == null) {
12111
12112                /* There was another ContentProvider with this authority when
12113                 * this app was installed so this authority is null,
12114                 * Ignore it as we don't have to unregister the provider.
12115                 */
12116                continue;
12117            }
12118            String names[] = p.info.authority.split(";");
12119            for (int j = 0; j < names.length; j++) {
12120                if (mProvidersByAuthority.get(names[j]) == p) {
12121                    mProvidersByAuthority.remove(names[j]);
12122                    if (DEBUG_REMOVE) {
12123                        if (chatty)
12124                            Log.d(TAG, "Unregistered content provider: " + names[j]
12125                                    + ", className = " + p.info.name + ", isSyncable = "
12126                                    + p.info.isSyncable);
12127                    }
12128                }
12129            }
12130            if (DEBUG_REMOVE && chatty) {
12131                if (r == null) {
12132                    r = new StringBuilder(256);
12133                } else {
12134                    r.append(' ');
12135                }
12136                r.append(p.info.name);
12137            }
12138        }
12139        if (r != null) {
12140            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12141        }
12142
12143        N = pkg.services.size();
12144        r = null;
12145        for (i=0; i<N; i++) {
12146            PackageParser.Service s = pkg.services.get(i);
12147            mServices.removeService(s);
12148            if (chatty) {
12149                if (r == null) {
12150                    r = new StringBuilder(256);
12151                } else {
12152                    r.append(' ');
12153                }
12154                r.append(s.info.name);
12155            }
12156        }
12157        if (r != null) {
12158            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12159        }
12160
12161        N = pkg.receivers.size();
12162        r = null;
12163        for (i=0; i<N; i++) {
12164            PackageParser.Activity a = pkg.receivers.get(i);
12165            mReceivers.removeActivity(a, "receiver");
12166            if (DEBUG_REMOVE && chatty) {
12167                if (r == null) {
12168                    r = new StringBuilder(256);
12169                } else {
12170                    r.append(' ');
12171                }
12172                r.append(a.info.name);
12173            }
12174        }
12175        if (r != null) {
12176            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12177        }
12178
12179        N = pkg.activities.size();
12180        r = null;
12181        for (i=0; i<N; i++) {
12182            PackageParser.Activity a = pkg.activities.get(i);
12183            mActivities.removeActivity(a, "activity");
12184            if (DEBUG_REMOVE && chatty) {
12185                if (r == null) {
12186                    r = new StringBuilder(256);
12187                } else {
12188                    r.append(' ');
12189                }
12190                r.append(a.info.name);
12191            }
12192        }
12193        if (r != null) {
12194            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12195        }
12196
12197        N = pkg.permissions.size();
12198        r = null;
12199        for (i=0; i<N; i++) {
12200            PackageParser.Permission p = pkg.permissions.get(i);
12201            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12202            if (bp == null) {
12203                bp = mSettings.mPermissionTrees.get(p.info.name);
12204            }
12205            if (bp != null && bp.perm == p) {
12206                bp.perm = null;
12207                if (DEBUG_REMOVE && chatty) {
12208                    if (r == null) {
12209                        r = new StringBuilder(256);
12210                    } else {
12211                        r.append(' ');
12212                    }
12213                    r.append(p.info.name);
12214                }
12215            }
12216            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12217                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12218                if (appOpPkgs != null) {
12219                    appOpPkgs.remove(pkg.packageName);
12220                }
12221            }
12222        }
12223        if (r != null) {
12224            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12225        }
12226
12227        N = pkg.requestedPermissions.size();
12228        r = null;
12229        for (i=0; i<N; i++) {
12230            String perm = pkg.requestedPermissions.get(i);
12231            BasePermission bp = mSettings.mPermissions.get(perm);
12232            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12233                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12234                if (appOpPkgs != null) {
12235                    appOpPkgs.remove(pkg.packageName);
12236                    if (appOpPkgs.isEmpty()) {
12237                        mAppOpPermissionPackages.remove(perm);
12238                    }
12239                }
12240            }
12241        }
12242        if (r != null) {
12243            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12244        }
12245
12246        N = pkg.instrumentation.size();
12247        r = null;
12248        for (i=0; i<N; i++) {
12249            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12250            mInstrumentation.remove(a.getComponentName());
12251            if (DEBUG_REMOVE && chatty) {
12252                if (r == null) {
12253                    r = new StringBuilder(256);
12254                } else {
12255                    r.append(' ');
12256                }
12257                r.append(a.info.name);
12258            }
12259        }
12260        if (r != null) {
12261            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12262        }
12263
12264        r = null;
12265        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12266            // Only system apps can hold shared libraries.
12267            if (pkg.libraryNames != null) {
12268                for (i = 0; i < pkg.libraryNames.size(); i++) {
12269                    String name = pkg.libraryNames.get(i);
12270                    if (removeSharedLibraryLPw(name, 0)) {
12271                        if (DEBUG_REMOVE && chatty) {
12272                            if (r == null) {
12273                                r = new StringBuilder(256);
12274                            } else {
12275                                r.append(' ');
12276                            }
12277                            r.append(name);
12278                        }
12279                    }
12280                }
12281            }
12282        }
12283
12284        r = null;
12285
12286        // Any package can hold static shared libraries.
12287        if (pkg.staticSharedLibName != null) {
12288            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12289                if (DEBUG_REMOVE && chatty) {
12290                    if (r == null) {
12291                        r = new StringBuilder(256);
12292                    } else {
12293                        r.append(' ');
12294                    }
12295                    r.append(pkg.staticSharedLibName);
12296                }
12297            }
12298        }
12299
12300        if (r != null) {
12301            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12302        }
12303    }
12304
12305    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12306        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12307            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12308                return true;
12309            }
12310        }
12311        return false;
12312    }
12313
12314    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12315    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12316    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12317
12318    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12319        // Update the parent permissions
12320        updatePermissionsLPw(pkg.packageName, pkg, flags);
12321        // Update the child permissions
12322        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12323        for (int i = 0; i < childCount; i++) {
12324            PackageParser.Package childPkg = pkg.childPackages.get(i);
12325            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12326        }
12327    }
12328
12329    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12330            int flags) {
12331        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12332        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12333    }
12334
12335    private void updatePermissionsLPw(String changingPkg,
12336            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12337        // Make sure there are no dangling permission trees.
12338        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12339        while (it.hasNext()) {
12340            final BasePermission bp = it.next();
12341            if (bp.packageSetting == null) {
12342                // We may not yet have parsed the package, so just see if
12343                // we still know about its settings.
12344                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12345            }
12346            if (bp.packageSetting == null) {
12347                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12348                        + " from package " + bp.sourcePackage);
12349                it.remove();
12350            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12351                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12352                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12353                            + " from package " + bp.sourcePackage);
12354                    flags |= UPDATE_PERMISSIONS_ALL;
12355                    it.remove();
12356                }
12357            }
12358        }
12359
12360        // Make sure all dynamic permissions have been assigned to a package,
12361        // and make sure there are no dangling permissions.
12362        it = mSettings.mPermissions.values().iterator();
12363        while (it.hasNext()) {
12364            final BasePermission bp = it.next();
12365            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12366                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12367                        + bp.name + " pkg=" + bp.sourcePackage
12368                        + " info=" + bp.pendingInfo);
12369                if (bp.packageSetting == null && bp.pendingInfo != null) {
12370                    final BasePermission tree = findPermissionTreeLP(bp.name);
12371                    if (tree != null && tree.perm != null) {
12372                        bp.packageSetting = tree.packageSetting;
12373                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12374                                new PermissionInfo(bp.pendingInfo));
12375                        bp.perm.info.packageName = tree.perm.info.packageName;
12376                        bp.perm.info.name = bp.name;
12377                        bp.uid = tree.uid;
12378                    }
12379                }
12380            }
12381            if (bp.packageSetting == null) {
12382                // We may not yet have parsed the package, so just see if
12383                // we still know about its settings.
12384                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12385            }
12386            if (bp.packageSetting == null) {
12387                Slog.w(TAG, "Removing dangling permission: " + bp.name
12388                        + " from package " + bp.sourcePackage);
12389                it.remove();
12390            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12391                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12392                    Slog.i(TAG, "Removing old permission: " + bp.name
12393                            + " from package " + bp.sourcePackage);
12394                    flags |= UPDATE_PERMISSIONS_ALL;
12395                    it.remove();
12396                }
12397            }
12398        }
12399
12400        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12401        // Now update the permissions for all packages, in particular
12402        // replace the granted permissions of the system packages.
12403        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12404            for (PackageParser.Package pkg : mPackages.values()) {
12405                if (pkg != pkgInfo) {
12406                    // Only replace for packages on requested volume
12407                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12408                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12409                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12410                    grantPermissionsLPw(pkg, replace, changingPkg);
12411                }
12412            }
12413        }
12414
12415        if (pkgInfo != null) {
12416            // Only replace for packages on requested volume
12417            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12418            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12419                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12420            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12421        }
12422        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12423    }
12424
12425    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12426            String packageOfInterest) {
12427        // IMPORTANT: There are two types of permissions: install and runtime.
12428        // Install time permissions are granted when the app is installed to
12429        // all device users and users added in the future. Runtime permissions
12430        // are granted at runtime explicitly to specific users. Normal and signature
12431        // protected permissions are install time permissions. Dangerous permissions
12432        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12433        // otherwise they are runtime permissions. This function does not manage
12434        // runtime permissions except for the case an app targeting Lollipop MR1
12435        // being upgraded to target a newer SDK, in which case dangerous permissions
12436        // are transformed from install time to runtime ones.
12437
12438        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12439        if (ps == null) {
12440            return;
12441        }
12442
12443        PermissionsState permissionsState = ps.getPermissionsState();
12444        PermissionsState origPermissions = permissionsState;
12445
12446        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12447
12448        boolean runtimePermissionsRevoked = false;
12449        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12450
12451        boolean changedInstallPermission = false;
12452
12453        if (replace) {
12454            ps.installPermissionsFixed = false;
12455            if (!ps.isSharedUser()) {
12456                origPermissions = new PermissionsState(permissionsState);
12457                permissionsState.reset();
12458            } else {
12459                // We need to know only about runtime permission changes since the
12460                // calling code always writes the install permissions state but
12461                // the runtime ones are written only if changed. The only cases of
12462                // changed runtime permissions here are promotion of an install to
12463                // runtime and revocation of a runtime from a shared user.
12464                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12465                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12466                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12467                    runtimePermissionsRevoked = true;
12468                }
12469            }
12470        }
12471
12472        permissionsState.setGlobalGids(mGlobalGids);
12473
12474        final int N = pkg.requestedPermissions.size();
12475        for (int i=0; i<N; i++) {
12476            final String name = pkg.requestedPermissions.get(i);
12477            final BasePermission bp = mSettings.mPermissions.get(name);
12478            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12479                    >= Build.VERSION_CODES.M;
12480
12481            if (DEBUG_INSTALL) {
12482                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12483            }
12484
12485            if (bp == null || bp.packageSetting == null) {
12486                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12487                    if (DEBUG_PERMISSIONS) {
12488                        Slog.i(TAG, "Unknown permission " + name
12489                                + " in package " + pkg.packageName);
12490                    }
12491                }
12492                continue;
12493            }
12494
12495
12496            // Limit ephemeral apps to ephemeral allowed permissions.
12497            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12498                if (DEBUG_PERMISSIONS) {
12499                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12500                            + pkg.packageName);
12501                }
12502                continue;
12503            }
12504
12505            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12506                if (DEBUG_PERMISSIONS) {
12507                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12508                            + pkg.packageName);
12509                }
12510                continue;
12511            }
12512
12513            final String perm = bp.name;
12514            boolean allowedSig = false;
12515            int grant = GRANT_DENIED;
12516
12517            // Keep track of app op permissions.
12518            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12519                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12520                if (pkgs == null) {
12521                    pkgs = new ArraySet<>();
12522                    mAppOpPermissionPackages.put(bp.name, pkgs);
12523                }
12524                pkgs.add(pkg.packageName);
12525            }
12526
12527            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12528            switch (level) {
12529                case PermissionInfo.PROTECTION_NORMAL: {
12530                    // For all apps normal permissions are install time ones.
12531                    grant = GRANT_INSTALL;
12532                } break;
12533
12534                case PermissionInfo.PROTECTION_DANGEROUS: {
12535                    // If a permission review is required for legacy apps we represent
12536                    // their permissions as always granted runtime ones since we need
12537                    // to keep the review required permission flag per user while an
12538                    // install permission's state is shared across all users.
12539                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12540                        // For legacy apps dangerous permissions are install time ones.
12541                        grant = GRANT_INSTALL;
12542                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12543                        // For legacy apps that became modern, install becomes runtime.
12544                        grant = GRANT_UPGRADE;
12545                    } else if (mPromoteSystemApps
12546                            && isSystemApp(ps)
12547                            && mExistingSystemPackages.contains(ps.name)) {
12548                        // For legacy system apps, install becomes runtime.
12549                        // We cannot check hasInstallPermission() for system apps since those
12550                        // permissions were granted implicitly and not persisted pre-M.
12551                        grant = GRANT_UPGRADE;
12552                    } else {
12553                        // For modern apps keep runtime permissions unchanged.
12554                        grant = GRANT_RUNTIME;
12555                    }
12556                } break;
12557
12558                case PermissionInfo.PROTECTION_SIGNATURE: {
12559                    // For all apps signature permissions are install time ones.
12560                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12561                    if (allowedSig) {
12562                        grant = GRANT_INSTALL;
12563                    }
12564                } break;
12565            }
12566
12567            if (DEBUG_PERMISSIONS) {
12568                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12569            }
12570
12571            if (grant != GRANT_DENIED) {
12572                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12573                    // If this is an existing, non-system package, then
12574                    // we can't add any new permissions to it.
12575                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12576                        // Except...  if this is a permission that was added
12577                        // to the platform (note: need to only do this when
12578                        // updating the platform).
12579                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12580                            grant = GRANT_DENIED;
12581                        }
12582                    }
12583                }
12584
12585                switch (grant) {
12586                    case GRANT_INSTALL: {
12587                        // Revoke this as runtime permission to handle the case of
12588                        // a runtime permission being downgraded to an install one.
12589                        // Also in permission review mode we keep dangerous permissions
12590                        // for legacy apps
12591                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12592                            if (origPermissions.getRuntimePermissionState(
12593                                    bp.name, userId) != null) {
12594                                // Revoke the runtime permission and clear the flags.
12595                                origPermissions.revokeRuntimePermission(bp, userId);
12596                                origPermissions.updatePermissionFlags(bp, userId,
12597                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12598                                // If we revoked a permission permission, we have to write.
12599                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12600                                        changedRuntimePermissionUserIds, userId);
12601                            }
12602                        }
12603                        // Grant an install permission.
12604                        if (permissionsState.grantInstallPermission(bp) !=
12605                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12606                            changedInstallPermission = true;
12607                        }
12608                    } break;
12609
12610                    case GRANT_RUNTIME: {
12611                        // Grant previously granted runtime permissions.
12612                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12613                            PermissionState permissionState = origPermissions
12614                                    .getRuntimePermissionState(bp.name, userId);
12615                            int flags = permissionState != null
12616                                    ? permissionState.getFlags() : 0;
12617                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12618                                // Don't propagate the permission in a permission review mode if
12619                                // the former was revoked, i.e. marked to not propagate on upgrade.
12620                                // Note that in a permission review mode install permissions are
12621                                // represented as constantly granted runtime ones since we need to
12622                                // keep a per user state associated with the permission. Also the
12623                                // revoke on upgrade flag is no longer applicable and is reset.
12624                                final boolean revokeOnUpgrade = (flags & PackageManager
12625                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12626                                if (revokeOnUpgrade) {
12627                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12628                                    // Since we changed the flags, we have to write.
12629                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12630                                            changedRuntimePermissionUserIds, userId);
12631                                }
12632                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12633                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12634                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12635                                        // If we cannot put the permission as it was,
12636                                        // we have to write.
12637                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12638                                                changedRuntimePermissionUserIds, userId);
12639                                    }
12640                                }
12641
12642                                // If the app supports runtime permissions no need for a review.
12643                                if (mPermissionReviewRequired
12644                                        && appSupportsRuntimePermissions
12645                                        && (flags & PackageManager
12646                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12647                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12648                                    // Since we changed the flags, we have to write.
12649                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12650                                            changedRuntimePermissionUserIds, userId);
12651                                }
12652                            } else if (mPermissionReviewRequired
12653                                    && !appSupportsRuntimePermissions) {
12654                                // For legacy apps that need a permission review, every new
12655                                // runtime permission is granted but it is pending a review.
12656                                // We also need to review only platform defined runtime
12657                                // permissions as these are the only ones the platform knows
12658                                // how to disable the API to simulate revocation as legacy
12659                                // apps don't expect to run with revoked permissions.
12660                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12661                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12662                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12663                                        // We changed the flags, hence have to write.
12664                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12665                                                changedRuntimePermissionUserIds, userId);
12666                                    }
12667                                }
12668                                if (permissionsState.grantRuntimePermission(bp, userId)
12669                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12670                                    // We changed the permission, hence have to write.
12671                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12672                                            changedRuntimePermissionUserIds, userId);
12673                                }
12674                            }
12675                            // Propagate the permission flags.
12676                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12677                        }
12678                    } break;
12679
12680                    case GRANT_UPGRADE: {
12681                        // Grant runtime permissions for a previously held install permission.
12682                        PermissionState permissionState = origPermissions
12683                                .getInstallPermissionState(bp.name);
12684                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12685
12686                        if (origPermissions.revokeInstallPermission(bp)
12687                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12688                            // We will be transferring the permission flags, so clear them.
12689                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12690                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12691                            changedInstallPermission = true;
12692                        }
12693
12694                        // If the permission is not to be promoted to runtime we ignore it and
12695                        // also its other flags as they are not applicable to install permissions.
12696                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12697                            for (int userId : currentUserIds) {
12698                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12699                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12700                                    // Transfer the permission flags.
12701                                    permissionsState.updatePermissionFlags(bp, userId,
12702                                            flags, flags);
12703                                    // If we granted the permission, we have to write.
12704                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12705                                            changedRuntimePermissionUserIds, userId);
12706                                }
12707                            }
12708                        }
12709                    } break;
12710
12711                    default: {
12712                        if (packageOfInterest == null
12713                                || packageOfInterest.equals(pkg.packageName)) {
12714                            if (DEBUG_PERMISSIONS) {
12715                                Slog.i(TAG, "Not granting permission " + perm
12716                                        + " to package " + pkg.packageName
12717                                        + " because it was previously installed without");
12718                            }
12719                        }
12720                    } break;
12721                }
12722            } else {
12723                if (permissionsState.revokeInstallPermission(bp) !=
12724                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12725                    // Also drop the permission flags.
12726                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12727                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12728                    changedInstallPermission = true;
12729                    Slog.i(TAG, "Un-granting permission " + perm
12730                            + " from package " + pkg.packageName
12731                            + " (protectionLevel=" + bp.protectionLevel
12732                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12733                            + ")");
12734                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12735                    // Don't print warning for app op permissions, since it is fine for them
12736                    // not to be granted, there is a UI for the user to decide.
12737                    if (DEBUG_PERMISSIONS
12738                            && (packageOfInterest == null
12739                                    || packageOfInterest.equals(pkg.packageName))) {
12740                        Slog.i(TAG, "Not granting permission " + perm
12741                                + " to package " + pkg.packageName
12742                                + " (protectionLevel=" + bp.protectionLevel
12743                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12744                                + ")");
12745                    }
12746                }
12747            }
12748        }
12749
12750        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12751                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12752            // This is the first that we have heard about this package, so the
12753            // permissions we have now selected are fixed until explicitly
12754            // changed.
12755            ps.installPermissionsFixed = true;
12756        }
12757
12758        // Persist the runtime permissions state for users with changes. If permissions
12759        // were revoked because no app in the shared user declares them we have to
12760        // write synchronously to avoid losing runtime permissions state.
12761        for (int userId : changedRuntimePermissionUserIds) {
12762            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12763        }
12764    }
12765
12766    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12767        boolean allowed = false;
12768        final int NP = PackageParser.NEW_PERMISSIONS.length;
12769        for (int ip=0; ip<NP; ip++) {
12770            final PackageParser.NewPermissionInfo npi
12771                    = PackageParser.NEW_PERMISSIONS[ip];
12772            if (npi.name.equals(perm)
12773                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12774                allowed = true;
12775                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12776                        + pkg.packageName);
12777                break;
12778            }
12779        }
12780        return allowed;
12781    }
12782
12783    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12784            BasePermission bp, PermissionsState origPermissions) {
12785        boolean privilegedPermission = (bp.protectionLevel
12786                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12787        boolean privappPermissionsDisable =
12788                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12789        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12790        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12791        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12792                && !platformPackage && platformPermission) {
12793            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12794                    .getPrivAppPermissions(pkg.packageName);
12795            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12796            if (!whitelisted) {
12797                Slog.w(TAG, "Privileged permission " + perm + " for package "
12798                        + pkg.packageName + " - not in privapp-permissions whitelist");
12799                // Only report violations for apps on system image
12800                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12801                    if (mPrivappPermissionsViolations == null) {
12802                        mPrivappPermissionsViolations = new ArraySet<>();
12803                    }
12804                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12805                }
12806                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12807                    return false;
12808                }
12809            }
12810        }
12811        boolean allowed = (compareSignatures(
12812                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12813                        == PackageManager.SIGNATURE_MATCH)
12814                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12815                        == PackageManager.SIGNATURE_MATCH);
12816        if (!allowed && privilegedPermission) {
12817            if (isSystemApp(pkg)) {
12818                // For updated system applications, a system permission
12819                // is granted only if it had been defined by the original application.
12820                if (pkg.isUpdatedSystemApp()) {
12821                    final PackageSetting sysPs = mSettings
12822                            .getDisabledSystemPkgLPr(pkg.packageName);
12823                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12824                        // If the original was granted this permission, we take
12825                        // that grant decision as read and propagate it to the
12826                        // update.
12827                        if (sysPs.isPrivileged()) {
12828                            allowed = true;
12829                        }
12830                    } else {
12831                        // The system apk may have been updated with an older
12832                        // version of the one on the data partition, but which
12833                        // granted a new system permission that it didn't have
12834                        // before.  In this case we do want to allow the app to
12835                        // now get the new permission if the ancestral apk is
12836                        // privileged to get it.
12837                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12838                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12839                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12840                                    allowed = true;
12841                                    break;
12842                                }
12843                            }
12844                        }
12845                        // Also if a privileged parent package on the system image or any of
12846                        // its children requested a privileged permission, the updated child
12847                        // packages can also get the permission.
12848                        if (pkg.parentPackage != null) {
12849                            final PackageSetting disabledSysParentPs = mSettings
12850                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12851                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12852                                    && disabledSysParentPs.isPrivileged()) {
12853                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12854                                    allowed = true;
12855                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12856                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12857                                    for (int i = 0; i < count; i++) {
12858                                        PackageParser.Package disabledSysChildPkg =
12859                                                disabledSysParentPs.pkg.childPackages.get(i);
12860                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12861                                                perm)) {
12862                                            allowed = true;
12863                                            break;
12864                                        }
12865                                    }
12866                                }
12867                            }
12868                        }
12869                    }
12870                } else {
12871                    allowed = isPrivilegedApp(pkg);
12872                }
12873            }
12874        }
12875        if (!allowed) {
12876            if (!allowed && (bp.protectionLevel
12877                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12878                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12879                // If this was a previously normal/dangerous permission that got moved
12880                // to a system permission as part of the runtime permission redesign, then
12881                // we still want to blindly grant it to old apps.
12882                allowed = true;
12883            }
12884            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12885                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12886                // If this permission is to be granted to the system installer and
12887                // this app is an installer, then it gets the permission.
12888                allowed = true;
12889            }
12890            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12891                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12892                // If this permission is to be granted to the system verifier and
12893                // this app is a verifier, then it gets the permission.
12894                allowed = true;
12895            }
12896            if (!allowed && (bp.protectionLevel
12897                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12898                    && isSystemApp(pkg)) {
12899                // Any pre-installed system app is allowed to get this permission.
12900                allowed = true;
12901            }
12902            if (!allowed && (bp.protectionLevel
12903                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12904                // For development permissions, a development permission
12905                // is granted only if it was already granted.
12906                allowed = origPermissions.hasInstallPermission(perm);
12907            }
12908            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12909                    && pkg.packageName.equals(mSetupWizardPackage)) {
12910                // If this permission is to be granted to the system setup wizard and
12911                // this app is a setup wizard, then it gets the permission.
12912                allowed = true;
12913            }
12914        }
12915        return allowed;
12916    }
12917
12918    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12919        final int permCount = pkg.requestedPermissions.size();
12920        for (int j = 0; j < permCount; j++) {
12921            String requestedPermission = pkg.requestedPermissions.get(j);
12922            if (permission.equals(requestedPermission)) {
12923                return true;
12924            }
12925        }
12926        return false;
12927    }
12928
12929    final class ActivityIntentResolver
12930            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12931        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12932                boolean defaultOnly, int userId) {
12933            if (!sUserManager.exists(userId)) return null;
12934            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12935            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12936        }
12937
12938        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12939                int userId) {
12940            if (!sUserManager.exists(userId)) return null;
12941            mFlags = flags;
12942            return super.queryIntent(intent, resolvedType,
12943                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12944                    userId);
12945        }
12946
12947        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12948                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12949            if (!sUserManager.exists(userId)) return null;
12950            if (packageActivities == null) {
12951                return null;
12952            }
12953            mFlags = flags;
12954            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12955            final int N = packageActivities.size();
12956            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12957                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12958
12959            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12960            for (int i = 0; i < N; ++i) {
12961                intentFilters = packageActivities.get(i).intents;
12962                if (intentFilters != null && intentFilters.size() > 0) {
12963                    PackageParser.ActivityIntentInfo[] array =
12964                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12965                    intentFilters.toArray(array);
12966                    listCut.add(array);
12967                }
12968            }
12969            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12970        }
12971
12972        /**
12973         * Finds a privileged activity that matches the specified activity names.
12974         */
12975        private PackageParser.Activity findMatchingActivity(
12976                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12977            for (PackageParser.Activity sysActivity : activityList) {
12978                if (sysActivity.info.name.equals(activityInfo.name)) {
12979                    return sysActivity;
12980                }
12981                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12982                    return sysActivity;
12983                }
12984                if (sysActivity.info.targetActivity != null) {
12985                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12986                        return sysActivity;
12987                    }
12988                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12989                        return sysActivity;
12990                    }
12991                }
12992            }
12993            return null;
12994        }
12995
12996        public class IterGenerator<E> {
12997            public Iterator<E> generate(ActivityIntentInfo info) {
12998                return null;
12999            }
13000        }
13001
13002        public class ActionIterGenerator extends IterGenerator<String> {
13003            @Override
13004            public Iterator<String> generate(ActivityIntentInfo info) {
13005                return info.actionsIterator();
13006            }
13007        }
13008
13009        public class CategoriesIterGenerator extends IterGenerator<String> {
13010            @Override
13011            public Iterator<String> generate(ActivityIntentInfo info) {
13012                return info.categoriesIterator();
13013            }
13014        }
13015
13016        public class SchemesIterGenerator extends IterGenerator<String> {
13017            @Override
13018            public Iterator<String> generate(ActivityIntentInfo info) {
13019                return info.schemesIterator();
13020            }
13021        }
13022
13023        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13024            @Override
13025            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13026                return info.authoritiesIterator();
13027            }
13028        }
13029
13030        /**
13031         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13032         * MODIFIED. Do not pass in a list that should not be changed.
13033         */
13034        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13035                IterGenerator<T> generator, Iterator<T> searchIterator) {
13036            // loop through the set of actions; every one must be found in the intent filter
13037            while (searchIterator.hasNext()) {
13038                // we must have at least one filter in the list to consider a match
13039                if (intentList.size() == 0) {
13040                    break;
13041                }
13042
13043                final T searchAction = searchIterator.next();
13044
13045                // loop through the set of intent filters
13046                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13047                while (intentIter.hasNext()) {
13048                    final ActivityIntentInfo intentInfo = intentIter.next();
13049                    boolean selectionFound = false;
13050
13051                    // loop through the intent filter's selection criteria; at least one
13052                    // of them must match the searched criteria
13053                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13054                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13055                        final T intentSelection = intentSelectionIter.next();
13056                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13057                            selectionFound = true;
13058                            break;
13059                        }
13060                    }
13061
13062                    // the selection criteria wasn't found in this filter's set; this filter
13063                    // is not a potential match
13064                    if (!selectionFound) {
13065                        intentIter.remove();
13066                    }
13067                }
13068            }
13069        }
13070
13071        private boolean isProtectedAction(ActivityIntentInfo filter) {
13072            final Iterator<String> actionsIter = filter.actionsIterator();
13073            while (actionsIter != null && actionsIter.hasNext()) {
13074                final String filterAction = actionsIter.next();
13075                if (PROTECTED_ACTIONS.contains(filterAction)) {
13076                    return true;
13077                }
13078            }
13079            return false;
13080        }
13081
13082        /**
13083         * Adjusts the priority of the given intent filter according to policy.
13084         * <p>
13085         * <ul>
13086         * <li>The priority for non privileged applications is capped to '0'</li>
13087         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13088         * <li>The priority for unbundled updates to privileged applications is capped to the
13089         *      priority defined on the system partition</li>
13090         * </ul>
13091         * <p>
13092         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13093         * allowed to obtain any priority on any action.
13094         */
13095        private void adjustPriority(
13096                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13097            // nothing to do; priority is fine as-is
13098            if (intent.getPriority() <= 0) {
13099                return;
13100            }
13101
13102            final ActivityInfo activityInfo = intent.activity.info;
13103            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13104
13105            final boolean privilegedApp =
13106                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13107            if (!privilegedApp) {
13108                // non-privileged applications can never define a priority >0
13109                if (DEBUG_FILTERS) {
13110                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13111                            + " package: " + applicationInfo.packageName
13112                            + " activity: " + intent.activity.className
13113                            + " origPrio: " + intent.getPriority());
13114                }
13115                intent.setPriority(0);
13116                return;
13117            }
13118
13119            if (systemActivities == null) {
13120                // the system package is not disabled; we're parsing the system partition
13121                if (isProtectedAction(intent)) {
13122                    if (mDeferProtectedFilters) {
13123                        // We can't deal with these just yet. No component should ever obtain a
13124                        // >0 priority for a protected actions, with ONE exception -- the setup
13125                        // wizard. The setup wizard, however, cannot be known until we're able to
13126                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13127                        // until all intent filters have been processed. Chicken, meet egg.
13128                        // Let the filter temporarily have a high priority and rectify the
13129                        // priorities after all system packages have been scanned.
13130                        mProtectedFilters.add(intent);
13131                        if (DEBUG_FILTERS) {
13132                            Slog.i(TAG, "Protected action; save for later;"
13133                                    + " package: " + applicationInfo.packageName
13134                                    + " activity: " + intent.activity.className
13135                                    + " origPrio: " + intent.getPriority());
13136                        }
13137                        return;
13138                    } else {
13139                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13140                            Slog.i(TAG, "No setup wizard;"
13141                                + " All protected intents capped to priority 0");
13142                        }
13143                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13144                            if (DEBUG_FILTERS) {
13145                                Slog.i(TAG, "Found setup wizard;"
13146                                    + " allow priority " + intent.getPriority() + ";"
13147                                    + " package: " + intent.activity.info.packageName
13148                                    + " activity: " + intent.activity.className
13149                                    + " priority: " + intent.getPriority());
13150                            }
13151                            // setup wizard gets whatever it wants
13152                            return;
13153                        }
13154                        if (DEBUG_FILTERS) {
13155                            Slog.i(TAG, "Protected action; cap priority to 0;"
13156                                    + " package: " + intent.activity.info.packageName
13157                                    + " activity: " + intent.activity.className
13158                                    + " origPrio: " + intent.getPriority());
13159                        }
13160                        intent.setPriority(0);
13161                        return;
13162                    }
13163                }
13164                // privileged apps on the system image get whatever priority they request
13165                return;
13166            }
13167
13168            // privileged app unbundled update ... try to find the same activity
13169            final PackageParser.Activity foundActivity =
13170                    findMatchingActivity(systemActivities, activityInfo);
13171            if (foundActivity == null) {
13172                // this is a new activity; it cannot obtain >0 priority
13173                if (DEBUG_FILTERS) {
13174                    Slog.i(TAG, "New activity; cap priority to 0;"
13175                            + " package: " + applicationInfo.packageName
13176                            + " activity: " + intent.activity.className
13177                            + " origPrio: " + intent.getPriority());
13178                }
13179                intent.setPriority(0);
13180                return;
13181            }
13182
13183            // found activity, now check for filter equivalence
13184
13185            // a shallow copy is enough; we modify the list, not its contents
13186            final List<ActivityIntentInfo> intentListCopy =
13187                    new ArrayList<>(foundActivity.intents);
13188            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13189
13190            // find matching action subsets
13191            final Iterator<String> actionsIterator = intent.actionsIterator();
13192            if (actionsIterator != null) {
13193                getIntentListSubset(
13194                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13195                if (intentListCopy.size() == 0) {
13196                    // no more intents to match; we're not equivalent
13197                    if (DEBUG_FILTERS) {
13198                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13199                                + " package: " + applicationInfo.packageName
13200                                + " activity: " + intent.activity.className
13201                                + " origPrio: " + intent.getPriority());
13202                    }
13203                    intent.setPriority(0);
13204                    return;
13205                }
13206            }
13207
13208            // find matching category subsets
13209            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13210            if (categoriesIterator != null) {
13211                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13212                        categoriesIterator);
13213                if (intentListCopy.size() == 0) {
13214                    // no more intents to match; we're not equivalent
13215                    if (DEBUG_FILTERS) {
13216                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13217                                + " package: " + applicationInfo.packageName
13218                                + " activity: " + intent.activity.className
13219                                + " origPrio: " + intent.getPriority());
13220                    }
13221                    intent.setPriority(0);
13222                    return;
13223                }
13224            }
13225
13226            // find matching schemes subsets
13227            final Iterator<String> schemesIterator = intent.schemesIterator();
13228            if (schemesIterator != null) {
13229                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13230                        schemesIterator);
13231                if (intentListCopy.size() == 0) {
13232                    // no more intents to match; we're not equivalent
13233                    if (DEBUG_FILTERS) {
13234                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13235                                + " package: " + applicationInfo.packageName
13236                                + " activity: " + intent.activity.className
13237                                + " origPrio: " + intent.getPriority());
13238                    }
13239                    intent.setPriority(0);
13240                    return;
13241                }
13242            }
13243
13244            // find matching authorities subsets
13245            final Iterator<IntentFilter.AuthorityEntry>
13246                    authoritiesIterator = intent.authoritiesIterator();
13247            if (authoritiesIterator != null) {
13248                getIntentListSubset(intentListCopy,
13249                        new AuthoritiesIterGenerator(),
13250                        authoritiesIterator);
13251                if (intentListCopy.size() == 0) {
13252                    // no more intents to match; we're not equivalent
13253                    if (DEBUG_FILTERS) {
13254                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13255                                + " package: " + applicationInfo.packageName
13256                                + " activity: " + intent.activity.className
13257                                + " origPrio: " + intent.getPriority());
13258                    }
13259                    intent.setPriority(0);
13260                    return;
13261                }
13262            }
13263
13264            // we found matching filter(s); app gets the max priority of all intents
13265            int cappedPriority = 0;
13266            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13267                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13268            }
13269            if (intent.getPriority() > cappedPriority) {
13270                if (DEBUG_FILTERS) {
13271                    Slog.i(TAG, "Found matching filter(s);"
13272                            + " cap priority to " + cappedPriority + ";"
13273                            + " package: " + applicationInfo.packageName
13274                            + " activity: " + intent.activity.className
13275                            + " origPrio: " + intent.getPriority());
13276                }
13277                intent.setPriority(cappedPriority);
13278                return;
13279            }
13280            // all this for nothing; the requested priority was <= what was on the system
13281        }
13282
13283        public final void addActivity(PackageParser.Activity a, String type) {
13284            mActivities.put(a.getComponentName(), a);
13285            if (DEBUG_SHOW_INFO)
13286                Log.v(
13287                TAG, "  " + type + " " +
13288                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13289            if (DEBUG_SHOW_INFO)
13290                Log.v(TAG, "    Class=" + a.info.name);
13291            final int NI = a.intents.size();
13292            for (int j=0; j<NI; j++) {
13293                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13294                if ("activity".equals(type)) {
13295                    final PackageSetting ps =
13296                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13297                    final List<PackageParser.Activity> systemActivities =
13298                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13299                    adjustPriority(systemActivities, intent);
13300                }
13301                if (DEBUG_SHOW_INFO) {
13302                    Log.v(TAG, "    IntentFilter:");
13303                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13304                }
13305                if (!intent.debugCheck()) {
13306                    Log.w(TAG, "==> For Activity " + a.info.name);
13307                }
13308                addFilter(intent);
13309            }
13310        }
13311
13312        public final void removeActivity(PackageParser.Activity a, String type) {
13313            mActivities.remove(a.getComponentName());
13314            if (DEBUG_SHOW_INFO) {
13315                Log.v(TAG, "  " + type + " "
13316                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13317                                : a.info.name) + ":");
13318                Log.v(TAG, "    Class=" + a.info.name);
13319            }
13320            final int NI = a.intents.size();
13321            for (int j=0; j<NI; j++) {
13322                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13323                if (DEBUG_SHOW_INFO) {
13324                    Log.v(TAG, "    IntentFilter:");
13325                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13326                }
13327                removeFilter(intent);
13328            }
13329        }
13330
13331        @Override
13332        protected boolean allowFilterResult(
13333                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13334            ActivityInfo filterAi = filter.activity.info;
13335            for (int i=dest.size()-1; i>=0; i--) {
13336                ActivityInfo destAi = dest.get(i).activityInfo;
13337                if (destAi.name == filterAi.name
13338                        && destAi.packageName == filterAi.packageName) {
13339                    return false;
13340                }
13341            }
13342            return true;
13343        }
13344
13345        @Override
13346        protected ActivityIntentInfo[] newArray(int size) {
13347            return new ActivityIntentInfo[size];
13348        }
13349
13350        @Override
13351        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13352            if (!sUserManager.exists(userId)) return true;
13353            PackageParser.Package p = filter.activity.owner;
13354            if (p != null) {
13355                PackageSetting ps = (PackageSetting)p.mExtras;
13356                if (ps != null) {
13357                    // System apps are never considered stopped for purposes of
13358                    // filtering, because there may be no way for the user to
13359                    // actually re-launch them.
13360                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13361                            && ps.getStopped(userId);
13362                }
13363            }
13364            return false;
13365        }
13366
13367        @Override
13368        protected boolean isPackageForFilter(String packageName,
13369                PackageParser.ActivityIntentInfo info) {
13370            return packageName.equals(info.activity.owner.packageName);
13371        }
13372
13373        @Override
13374        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13375                int match, int userId) {
13376            if (!sUserManager.exists(userId)) return null;
13377            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13378                return null;
13379            }
13380            final PackageParser.Activity activity = info.activity;
13381            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13382            if (ps == null) {
13383                return null;
13384            }
13385            final PackageUserState userState = ps.readUserState(userId);
13386            ActivityInfo ai =
13387                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13388            if (ai == null) {
13389                return null;
13390            }
13391            final boolean matchExplicitlyVisibleOnly =
13392                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13393            final boolean matchVisibleToInstantApp =
13394                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13395            final boolean componentVisible =
13396                    matchVisibleToInstantApp
13397                    && info.isVisibleToInstantApp()
13398                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13399            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13400            // throw out filters that aren't visible to ephemeral apps
13401            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13402                return null;
13403            }
13404            // throw out instant app filters if we're not explicitly requesting them
13405            if (!matchInstantApp && userState.instantApp) {
13406                return null;
13407            }
13408            // throw out instant app filters if updates are available; will trigger
13409            // instant app resolution
13410            if (userState.instantApp && ps.isUpdateAvailable()) {
13411                return null;
13412            }
13413            final ResolveInfo res = new ResolveInfo();
13414            res.activityInfo = ai;
13415            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13416                res.filter = info;
13417            }
13418            if (info != null) {
13419                res.handleAllWebDataURI = info.handleAllWebDataURI();
13420            }
13421            res.priority = info.getPriority();
13422            res.preferredOrder = activity.owner.mPreferredOrder;
13423            //System.out.println("Result: " + res.activityInfo.className +
13424            //                   " = " + res.priority);
13425            res.match = match;
13426            res.isDefault = info.hasDefault;
13427            res.labelRes = info.labelRes;
13428            res.nonLocalizedLabel = info.nonLocalizedLabel;
13429            if (userNeedsBadging(userId)) {
13430                res.noResourceId = true;
13431            } else {
13432                res.icon = info.icon;
13433            }
13434            res.iconResourceId = info.icon;
13435            res.system = res.activityInfo.applicationInfo.isSystemApp();
13436            res.isInstantAppAvailable = userState.instantApp;
13437            return res;
13438        }
13439
13440        @Override
13441        protected void sortResults(List<ResolveInfo> results) {
13442            Collections.sort(results, mResolvePrioritySorter);
13443        }
13444
13445        @Override
13446        protected void dumpFilter(PrintWriter out, String prefix,
13447                PackageParser.ActivityIntentInfo filter) {
13448            out.print(prefix); out.print(
13449                    Integer.toHexString(System.identityHashCode(filter.activity)));
13450                    out.print(' ');
13451                    filter.activity.printComponentShortName(out);
13452                    out.print(" filter ");
13453                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13454        }
13455
13456        @Override
13457        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13458            return filter.activity;
13459        }
13460
13461        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13462            PackageParser.Activity activity = (PackageParser.Activity)label;
13463            out.print(prefix); out.print(
13464                    Integer.toHexString(System.identityHashCode(activity)));
13465                    out.print(' ');
13466                    activity.printComponentShortName(out);
13467            if (count > 1) {
13468                out.print(" ("); out.print(count); out.print(" filters)");
13469            }
13470            out.println();
13471        }
13472
13473        // Keys are String (activity class name), values are Activity.
13474        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13475                = new ArrayMap<ComponentName, PackageParser.Activity>();
13476        private int mFlags;
13477    }
13478
13479    private final class ServiceIntentResolver
13480            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13481        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13482                boolean defaultOnly, int userId) {
13483            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13484            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13485        }
13486
13487        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13488                int userId) {
13489            if (!sUserManager.exists(userId)) return null;
13490            mFlags = flags;
13491            return super.queryIntent(intent, resolvedType,
13492                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13493                    userId);
13494        }
13495
13496        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13497                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13498            if (!sUserManager.exists(userId)) return null;
13499            if (packageServices == null) {
13500                return null;
13501            }
13502            mFlags = flags;
13503            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13504            final int N = packageServices.size();
13505            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13506                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13507
13508            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13509            for (int i = 0; i < N; ++i) {
13510                intentFilters = packageServices.get(i).intents;
13511                if (intentFilters != null && intentFilters.size() > 0) {
13512                    PackageParser.ServiceIntentInfo[] array =
13513                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13514                    intentFilters.toArray(array);
13515                    listCut.add(array);
13516                }
13517            }
13518            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13519        }
13520
13521        public final void addService(PackageParser.Service s) {
13522            mServices.put(s.getComponentName(), s);
13523            if (DEBUG_SHOW_INFO) {
13524                Log.v(TAG, "  "
13525                        + (s.info.nonLocalizedLabel != null
13526                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13527                Log.v(TAG, "    Class=" + s.info.name);
13528            }
13529            final int NI = s.intents.size();
13530            int j;
13531            for (j=0; j<NI; j++) {
13532                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13533                if (DEBUG_SHOW_INFO) {
13534                    Log.v(TAG, "    IntentFilter:");
13535                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13536                }
13537                if (!intent.debugCheck()) {
13538                    Log.w(TAG, "==> For Service " + s.info.name);
13539                }
13540                addFilter(intent);
13541            }
13542        }
13543
13544        public final void removeService(PackageParser.Service s) {
13545            mServices.remove(s.getComponentName());
13546            if (DEBUG_SHOW_INFO) {
13547                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13548                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13549                Log.v(TAG, "    Class=" + s.info.name);
13550            }
13551            final int NI = s.intents.size();
13552            int j;
13553            for (j=0; j<NI; j++) {
13554                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13555                if (DEBUG_SHOW_INFO) {
13556                    Log.v(TAG, "    IntentFilter:");
13557                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13558                }
13559                removeFilter(intent);
13560            }
13561        }
13562
13563        @Override
13564        protected boolean allowFilterResult(
13565                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13566            ServiceInfo filterSi = filter.service.info;
13567            for (int i=dest.size()-1; i>=0; i--) {
13568                ServiceInfo destAi = dest.get(i).serviceInfo;
13569                if (destAi.name == filterSi.name
13570                        && destAi.packageName == filterSi.packageName) {
13571                    return false;
13572                }
13573            }
13574            return true;
13575        }
13576
13577        @Override
13578        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13579            return new PackageParser.ServiceIntentInfo[size];
13580        }
13581
13582        @Override
13583        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13584            if (!sUserManager.exists(userId)) return true;
13585            PackageParser.Package p = filter.service.owner;
13586            if (p != null) {
13587                PackageSetting ps = (PackageSetting)p.mExtras;
13588                if (ps != null) {
13589                    // System apps are never considered stopped for purposes of
13590                    // filtering, because there may be no way for the user to
13591                    // actually re-launch them.
13592                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13593                            && ps.getStopped(userId);
13594                }
13595            }
13596            return false;
13597        }
13598
13599        @Override
13600        protected boolean isPackageForFilter(String packageName,
13601                PackageParser.ServiceIntentInfo info) {
13602            return packageName.equals(info.service.owner.packageName);
13603        }
13604
13605        @Override
13606        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13607                int match, int userId) {
13608            if (!sUserManager.exists(userId)) return null;
13609            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13610            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13611                return null;
13612            }
13613            final PackageParser.Service service = info.service;
13614            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13615            if (ps == null) {
13616                return null;
13617            }
13618            final PackageUserState userState = ps.readUserState(userId);
13619            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13620                    userState, userId);
13621            if (si == null) {
13622                return null;
13623            }
13624            final boolean matchVisibleToInstantApp =
13625                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13626            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13627            // throw out filters that aren't visible to ephemeral apps
13628            if (matchVisibleToInstantApp
13629                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13630                return null;
13631            }
13632            // throw out ephemeral filters if we're not explicitly requesting them
13633            if (!isInstantApp && userState.instantApp) {
13634                return null;
13635            }
13636            // throw out instant app filters if updates are available; will trigger
13637            // instant app resolution
13638            if (userState.instantApp && ps.isUpdateAvailable()) {
13639                return null;
13640            }
13641            final ResolveInfo res = new ResolveInfo();
13642            res.serviceInfo = si;
13643            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13644                res.filter = filter;
13645            }
13646            res.priority = info.getPriority();
13647            res.preferredOrder = service.owner.mPreferredOrder;
13648            res.match = match;
13649            res.isDefault = info.hasDefault;
13650            res.labelRes = info.labelRes;
13651            res.nonLocalizedLabel = info.nonLocalizedLabel;
13652            res.icon = info.icon;
13653            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13654            return res;
13655        }
13656
13657        @Override
13658        protected void sortResults(List<ResolveInfo> results) {
13659            Collections.sort(results, mResolvePrioritySorter);
13660        }
13661
13662        @Override
13663        protected void dumpFilter(PrintWriter out, String prefix,
13664                PackageParser.ServiceIntentInfo filter) {
13665            out.print(prefix); out.print(
13666                    Integer.toHexString(System.identityHashCode(filter.service)));
13667                    out.print(' ');
13668                    filter.service.printComponentShortName(out);
13669                    out.print(" filter ");
13670                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13671        }
13672
13673        @Override
13674        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13675            return filter.service;
13676        }
13677
13678        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13679            PackageParser.Service service = (PackageParser.Service)label;
13680            out.print(prefix); out.print(
13681                    Integer.toHexString(System.identityHashCode(service)));
13682                    out.print(' ');
13683                    service.printComponentShortName(out);
13684            if (count > 1) {
13685                out.print(" ("); out.print(count); out.print(" filters)");
13686            }
13687            out.println();
13688        }
13689
13690//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13691//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13692//            final List<ResolveInfo> retList = Lists.newArrayList();
13693//            while (i.hasNext()) {
13694//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13695//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13696//                    retList.add(resolveInfo);
13697//                }
13698//            }
13699//            return retList;
13700//        }
13701
13702        // Keys are String (activity class name), values are Activity.
13703        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13704                = new ArrayMap<ComponentName, PackageParser.Service>();
13705        private int mFlags;
13706    }
13707
13708    private final class ProviderIntentResolver
13709            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13710        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13711                boolean defaultOnly, int userId) {
13712            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13713            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13714        }
13715
13716        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13717                int userId) {
13718            if (!sUserManager.exists(userId))
13719                return null;
13720            mFlags = flags;
13721            return super.queryIntent(intent, resolvedType,
13722                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13723                    userId);
13724        }
13725
13726        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13727                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13728            if (!sUserManager.exists(userId))
13729                return null;
13730            if (packageProviders == null) {
13731                return null;
13732            }
13733            mFlags = flags;
13734            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13735            final int N = packageProviders.size();
13736            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13737                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13738
13739            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13740            for (int i = 0; i < N; ++i) {
13741                intentFilters = packageProviders.get(i).intents;
13742                if (intentFilters != null && intentFilters.size() > 0) {
13743                    PackageParser.ProviderIntentInfo[] array =
13744                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13745                    intentFilters.toArray(array);
13746                    listCut.add(array);
13747                }
13748            }
13749            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13750        }
13751
13752        public final void addProvider(PackageParser.Provider p) {
13753            if (mProviders.containsKey(p.getComponentName())) {
13754                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13755                return;
13756            }
13757
13758            mProviders.put(p.getComponentName(), p);
13759            if (DEBUG_SHOW_INFO) {
13760                Log.v(TAG, "  "
13761                        + (p.info.nonLocalizedLabel != null
13762                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13763                Log.v(TAG, "    Class=" + p.info.name);
13764            }
13765            final int NI = p.intents.size();
13766            int j;
13767            for (j = 0; j < NI; j++) {
13768                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13769                if (DEBUG_SHOW_INFO) {
13770                    Log.v(TAG, "    IntentFilter:");
13771                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13772                }
13773                if (!intent.debugCheck()) {
13774                    Log.w(TAG, "==> For Provider " + p.info.name);
13775                }
13776                addFilter(intent);
13777            }
13778        }
13779
13780        public final void removeProvider(PackageParser.Provider p) {
13781            mProviders.remove(p.getComponentName());
13782            if (DEBUG_SHOW_INFO) {
13783                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13784                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13785                Log.v(TAG, "    Class=" + p.info.name);
13786            }
13787            final int NI = p.intents.size();
13788            int j;
13789            for (j = 0; j < NI; j++) {
13790                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13791                if (DEBUG_SHOW_INFO) {
13792                    Log.v(TAG, "    IntentFilter:");
13793                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13794                }
13795                removeFilter(intent);
13796            }
13797        }
13798
13799        @Override
13800        protected boolean allowFilterResult(
13801                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13802            ProviderInfo filterPi = filter.provider.info;
13803            for (int i = dest.size() - 1; i >= 0; i--) {
13804                ProviderInfo destPi = dest.get(i).providerInfo;
13805                if (destPi.name == filterPi.name
13806                        && destPi.packageName == filterPi.packageName) {
13807                    return false;
13808                }
13809            }
13810            return true;
13811        }
13812
13813        @Override
13814        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13815            return new PackageParser.ProviderIntentInfo[size];
13816        }
13817
13818        @Override
13819        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13820            if (!sUserManager.exists(userId))
13821                return true;
13822            PackageParser.Package p = filter.provider.owner;
13823            if (p != null) {
13824                PackageSetting ps = (PackageSetting) p.mExtras;
13825                if (ps != null) {
13826                    // System apps are never considered stopped for purposes of
13827                    // filtering, because there may be no way for the user to
13828                    // actually re-launch them.
13829                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13830                            && ps.getStopped(userId);
13831                }
13832            }
13833            return false;
13834        }
13835
13836        @Override
13837        protected boolean isPackageForFilter(String packageName,
13838                PackageParser.ProviderIntentInfo info) {
13839            return packageName.equals(info.provider.owner.packageName);
13840        }
13841
13842        @Override
13843        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13844                int match, int userId) {
13845            if (!sUserManager.exists(userId))
13846                return null;
13847            final PackageParser.ProviderIntentInfo info = filter;
13848            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13849                return null;
13850            }
13851            final PackageParser.Provider provider = info.provider;
13852            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13853            if (ps == null) {
13854                return null;
13855            }
13856            final PackageUserState userState = ps.readUserState(userId);
13857            final boolean matchVisibleToInstantApp =
13858                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13859            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13860            // throw out filters that aren't visible to instant applications
13861            if (matchVisibleToInstantApp
13862                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13863                return null;
13864            }
13865            // throw out instant application filters if we're not explicitly requesting them
13866            if (!isInstantApp && userState.instantApp) {
13867                return null;
13868            }
13869            // throw out instant application filters if updates are available; will trigger
13870            // instant application resolution
13871            if (userState.instantApp && ps.isUpdateAvailable()) {
13872                return null;
13873            }
13874            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13875                    userState, userId);
13876            if (pi == null) {
13877                return null;
13878            }
13879            final ResolveInfo res = new ResolveInfo();
13880            res.providerInfo = pi;
13881            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13882                res.filter = filter;
13883            }
13884            res.priority = info.getPriority();
13885            res.preferredOrder = provider.owner.mPreferredOrder;
13886            res.match = match;
13887            res.isDefault = info.hasDefault;
13888            res.labelRes = info.labelRes;
13889            res.nonLocalizedLabel = info.nonLocalizedLabel;
13890            res.icon = info.icon;
13891            res.system = res.providerInfo.applicationInfo.isSystemApp();
13892            return res;
13893        }
13894
13895        @Override
13896        protected void sortResults(List<ResolveInfo> results) {
13897            Collections.sort(results, mResolvePrioritySorter);
13898        }
13899
13900        @Override
13901        protected void dumpFilter(PrintWriter out, String prefix,
13902                PackageParser.ProviderIntentInfo filter) {
13903            out.print(prefix);
13904            out.print(
13905                    Integer.toHexString(System.identityHashCode(filter.provider)));
13906            out.print(' ');
13907            filter.provider.printComponentShortName(out);
13908            out.print(" filter ");
13909            out.println(Integer.toHexString(System.identityHashCode(filter)));
13910        }
13911
13912        @Override
13913        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13914            return filter.provider;
13915        }
13916
13917        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13918            PackageParser.Provider provider = (PackageParser.Provider)label;
13919            out.print(prefix); out.print(
13920                    Integer.toHexString(System.identityHashCode(provider)));
13921                    out.print(' ');
13922                    provider.printComponentShortName(out);
13923            if (count > 1) {
13924                out.print(" ("); out.print(count); out.print(" filters)");
13925            }
13926            out.println();
13927        }
13928
13929        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13930                = new ArrayMap<ComponentName, PackageParser.Provider>();
13931        private int mFlags;
13932    }
13933
13934    static final class EphemeralIntentResolver
13935            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13936        /**
13937         * The result that has the highest defined order. Ordering applies on a
13938         * per-package basis. Mapping is from package name to Pair of order and
13939         * EphemeralResolveInfo.
13940         * <p>
13941         * NOTE: This is implemented as a field variable for convenience and efficiency.
13942         * By having a field variable, we're able to track filter ordering as soon as
13943         * a non-zero order is defined. Otherwise, multiple loops across the result set
13944         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13945         * this needs to be contained entirely within {@link #filterResults}.
13946         */
13947        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13948
13949        @Override
13950        protected AuxiliaryResolveInfo[] newArray(int size) {
13951            return new AuxiliaryResolveInfo[size];
13952        }
13953
13954        @Override
13955        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13956            return true;
13957        }
13958
13959        @Override
13960        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13961                int userId) {
13962            if (!sUserManager.exists(userId)) {
13963                return null;
13964            }
13965            final String packageName = responseObj.resolveInfo.getPackageName();
13966            final Integer order = responseObj.getOrder();
13967            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13968                    mOrderResult.get(packageName);
13969            // ordering is enabled and this item's order isn't high enough
13970            if (lastOrderResult != null && lastOrderResult.first >= order) {
13971                return null;
13972            }
13973            final InstantAppResolveInfo res = responseObj.resolveInfo;
13974            if (order > 0) {
13975                // non-zero order, enable ordering
13976                mOrderResult.put(packageName, new Pair<>(order, res));
13977            }
13978            return responseObj;
13979        }
13980
13981        @Override
13982        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13983            // only do work if ordering is enabled [most of the time it won't be]
13984            if (mOrderResult.size() == 0) {
13985                return;
13986            }
13987            int resultSize = results.size();
13988            for (int i = 0; i < resultSize; i++) {
13989                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13990                final String packageName = info.getPackageName();
13991                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13992                if (savedInfo == null) {
13993                    // package doesn't having ordering
13994                    continue;
13995                }
13996                if (savedInfo.second == info) {
13997                    // circled back to the highest ordered item; remove from order list
13998                    mOrderResult.remove(savedInfo);
13999                    if (mOrderResult.size() == 0) {
14000                        // no more ordered items
14001                        break;
14002                    }
14003                    continue;
14004                }
14005                // item has a worse order, remove it from the result list
14006                results.remove(i);
14007                resultSize--;
14008                i--;
14009            }
14010        }
14011    }
14012
14013    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14014            new Comparator<ResolveInfo>() {
14015        public int compare(ResolveInfo r1, ResolveInfo r2) {
14016            int v1 = r1.priority;
14017            int v2 = r2.priority;
14018            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14019            if (v1 != v2) {
14020                return (v1 > v2) ? -1 : 1;
14021            }
14022            v1 = r1.preferredOrder;
14023            v2 = r2.preferredOrder;
14024            if (v1 != v2) {
14025                return (v1 > v2) ? -1 : 1;
14026            }
14027            if (r1.isDefault != r2.isDefault) {
14028                return r1.isDefault ? -1 : 1;
14029            }
14030            v1 = r1.match;
14031            v2 = r2.match;
14032            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14033            if (v1 != v2) {
14034                return (v1 > v2) ? -1 : 1;
14035            }
14036            if (r1.system != r2.system) {
14037                return r1.system ? -1 : 1;
14038            }
14039            if (r1.activityInfo != null) {
14040                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14041            }
14042            if (r1.serviceInfo != null) {
14043                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14044            }
14045            if (r1.providerInfo != null) {
14046                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14047            }
14048            return 0;
14049        }
14050    };
14051
14052    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14053            new Comparator<ProviderInfo>() {
14054        public int compare(ProviderInfo p1, ProviderInfo p2) {
14055            final int v1 = p1.initOrder;
14056            final int v2 = p2.initOrder;
14057            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14058        }
14059    };
14060
14061    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14062            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14063            final int[] userIds) {
14064        mHandler.post(new Runnable() {
14065            @Override
14066            public void run() {
14067                try {
14068                    final IActivityManager am = ActivityManager.getService();
14069                    if (am == null) return;
14070                    final int[] resolvedUserIds;
14071                    if (userIds == null) {
14072                        resolvedUserIds = am.getRunningUserIds();
14073                    } else {
14074                        resolvedUserIds = userIds;
14075                    }
14076                    for (int id : resolvedUserIds) {
14077                        final Intent intent = new Intent(action,
14078                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14079                        if (extras != null) {
14080                            intent.putExtras(extras);
14081                        }
14082                        if (targetPkg != null) {
14083                            intent.setPackage(targetPkg);
14084                        }
14085                        // Modify the UID when posting to other users
14086                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14087                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14088                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14089                            intent.putExtra(Intent.EXTRA_UID, uid);
14090                        }
14091                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14092                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14093                        if (DEBUG_BROADCASTS) {
14094                            RuntimeException here = new RuntimeException("here");
14095                            here.fillInStackTrace();
14096                            Slog.d(TAG, "Sending to user " + id + ": "
14097                                    + intent.toShortString(false, true, false, false)
14098                                    + " " + intent.getExtras(), here);
14099                        }
14100                        am.broadcastIntent(null, intent, null, finishedReceiver,
14101                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14102                                null, finishedReceiver != null, false, id);
14103                    }
14104                } catch (RemoteException ex) {
14105                }
14106            }
14107        });
14108    }
14109
14110    /**
14111     * Check if the external storage media is available. This is true if there
14112     * is a mounted external storage medium or if the external storage is
14113     * emulated.
14114     */
14115    private boolean isExternalMediaAvailable() {
14116        return mMediaMounted || Environment.isExternalStorageEmulated();
14117    }
14118
14119    @Override
14120    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14121        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14122            return null;
14123        }
14124        // writer
14125        synchronized (mPackages) {
14126            if (!isExternalMediaAvailable()) {
14127                // If the external storage is no longer mounted at this point,
14128                // the caller may not have been able to delete all of this
14129                // packages files and can not delete any more.  Bail.
14130                return null;
14131            }
14132            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14133            if (lastPackage != null) {
14134                pkgs.remove(lastPackage);
14135            }
14136            if (pkgs.size() > 0) {
14137                return pkgs.get(0);
14138            }
14139        }
14140        return null;
14141    }
14142
14143    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14144        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14145                userId, andCode ? 1 : 0, packageName);
14146        if (mSystemReady) {
14147            msg.sendToTarget();
14148        } else {
14149            if (mPostSystemReadyMessages == null) {
14150                mPostSystemReadyMessages = new ArrayList<>();
14151            }
14152            mPostSystemReadyMessages.add(msg);
14153        }
14154    }
14155
14156    void startCleaningPackages() {
14157        // reader
14158        if (!isExternalMediaAvailable()) {
14159            return;
14160        }
14161        synchronized (mPackages) {
14162            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14163                return;
14164            }
14165        }
14166        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14167        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14168        IActivityManager am = ActivityManager.getService();
14169        if (am != null) {
14170            int dcsUid = -1;
14171            synchronized (mPackages) {
14172                if (!mDefaultContainerWhitelisted) {
14173                    mDefaultContainerWhitelisted = true;
14174                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14175                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14176                }
14177            }
14178            try {
14179                if (dcsUid > 0) {
14180                    am.backgroundWhitelistUid(dcsUid);
14181                }
14182                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14183                        UserHandle.USER_SYSTEM);
14184            } catch (RemoteException e) {
14185            }
14186        }
14187    }
14188
14189    @Override
14190    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14191            int installFlags, String installerPackageName, int userId) {
14192        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14193
14194        final int callingUid = Binder.getCallingUid();
14195        enforceCrossUserPermission(callingUid, userId,
14196                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14197
14198        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14199            try {
14200                if (observer != null) {
14201                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14202                }
14203            } catch (RemoteException re) {
14204            }
14205            return;
14206        }
14207
14208        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14209            installFlags |= PackageManager.INSTALL_FROM_ADB;
14210
14211        } else {
14212            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14213            // about installerPackageName.
14214
14215            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14216            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14217        }
14218
14219        UserHandle user;
14220        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14221            user = UserHandle.ALL;
14222        } else {
14223            user = new UserHandle(userId);
14224        }
14225
14226        // Only system components can circumvent runtime permissions when installing.
14227        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14228                && mContext.checkCallingOrSelfPermission(Manifest.permission
14229                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14230            throw new SecurityException("You need the "
14231                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14232                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14233        }
14234
14235        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14236                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14237            throw new IllegalArgumentException(
14238                    "New installs into ASEC containers no longer supported");
14239        }
14240
14241        final File originFile = new File(originPath);
14242        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14243
14244        final Message msg = mHandler.obtainMessage(INIT_COPY);
14245        final VerificationInfo verificationInfo = new VerificationInfo(
14246                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14247        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14248                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14249                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14250                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14251        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14252        msg.obj = params;
14253
14254        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14255                System.identityHashCode(msg.obj));
14256        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14257                System.identityHashCode(msg.obj));
14258
14259        mHandler.sendMessage(msg);
14260    }
14261
14262
14263    /**
14264     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14265     * it is acting on behalf on an enterprise or the user).
14266     *
14267     * Note that the ordering of the conditionals in this method is important. The checks we perform
14268     * are as follows, in this order:
14269     *
14270     * 1) If the install is being performed by a system app, we can trust the app to have set the
14271     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14272     *    what it is.
14273     * 2) If the install is being performed by a device or profile owner app, the install reason
14274     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14275     *    set the install reason correctly. If the app targets an older SDK version where install
14276     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14277     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14278     * 3) In all other cases, the install is being performed by a regular app that is neither part
14279     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14280     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14281     *    set to enterprise policy and if so, change it to unknown instead.
14282     */
14283    private int fixUpInstallReason(String installerPackageName, int installerUid,
14284            int installReason) {
14285        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14286                == PERMISSION_GRANTED) {
14287            // If the install is being performed by a system app, we trust that app to have set the
14288            // install reason correctly.
14289            return installReason;
14290        }
14291
14292        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14293            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14294        if (dpm != null) {
14295            ComponentName owner = null;
14296            try {
14297                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14298                if (owner == null) {
14299                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14300                }
14301            } catch (RemoteException e) {
14302            }
14303            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14304                // If the install is being performed by a device or profile owner, the install
14305                // reason should be enterprise policy.
14306                return PackageManager.INSTALL_REASON_POLICY;
14307            }
14308        }
14309
14310        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14311            // If the install is being performed by a regular app (i.e. neither system app nor
14312            // device or profile owner), we have no reason to believe that the app is acting on
14313            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14314            // change it to unknown instead.
14315            return PackageManager.INSTALL_REASON_UNKNOWN;
14316        }
14317
14318        // If the install is being performed by a regular app and the install reason was set to any
14319        // value but enterprise policy, leave the install reason unchanged.
14320        return installReason;
14321    }
14322
14323    void installStage(String packageName, File stagedDir, String stagedCid,
14324            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14325            String installerPackageName, int installerUid, UserHandle user,
14326            Certificate[][] certificates) {
14327        if (DEBUG_EPHEMERAL) {
14328            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14329                Slog.d(TAG, "Ephemeral install of " + packageName);
14330            }
14331        }
14332        final VerificationInfo verificationInfo = new VerificationInfo(
14333                sessionParams.originatingUri, sessionParams.referrerUri,
14334                sessionParams.originatingUid, installerUid);
14335
14336        final OriginInfo origin;
14337        if (stagedDir != null) {
14338            origin = OriginInfo.fromStagedFile(stagedDir);
14339        } else {
14340            origin = OriginInfo.fromStagedContainer(stagedCid);
14341        }
14342
14343        final Message msg = mHandler.obtainMessage(INIT_COPY);
14344        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14345                sessionParams.installReason);
14346        final InstallParams params = new InstallParams(origin, null, observer,
14347                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14348                verificationInfo, user, sessionParams.abiOverride,
14349                sessionParams.grantedRuntimePermissions, certificates, installReason);
14350        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14351        msg.obj = params;
14352
14353        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14354                System.identityHashCode(msg.obj));
14355        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14356                System.identityHashCode(msg.obj));
14357
14358        mHandler.sendMessage(msg);
14359    }
14360
14361    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14362            int userId) {
14363        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14364        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14365
14366        // Send a session commit broadcast
14367        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14368        info.installReason = pkgSetting.getInstallReason(userId);
14369        info.appPackageName = packageName;
14370        sendSessionCommitBroadcast(info, userId);
14371    }
14372
14373    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14374        if (ArrayUtils.isEmpty(userIds)) {
14375            return;
14376        }
14377        Bundle extras = new Bundle(1);
14378        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14379        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14380
14381        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14382                packageName, extras, 0, null, null, userIds);
14383        if (isSystem) {
14384            mHandler.post(() -> {
14385                        for (int userId : userIds) {
14386                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14387                        }
14388                    }
14389            );
14390        }
14391    }
14392
14393    /**
14394     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14395     * automatically without needing an explicit launch.
14396     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14397     */
14398    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14399        // If user is not running, the app didn't miss any broadcast
14400        if (!mUserManagerInternal.isUserRunning(userId)) {
14401            return;
14402        }
14403        final IActivityManager am = ActivityManager.getService();
14404        try {
14405            // Deliver LOCKED_BOOT_COMPLETED first
14406            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14407                    .setPackage(packageName);
14408            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14409            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14410                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14411
14412            // Deliver BOOT_COMPLETED only if user is unlocked
14413            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14414                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14415                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14416                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14417            }
14418        } catch (RemoteException e) {
14419            throw e.rethrowFromSystemServer();
14420        }
14421    }
14422
14423    @Override
14424    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14425            int userId) {
14426        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14427        PackageSetting pkgSetting;
14428        final int callingUid = Binder.getCallingUid();
14429        enforceCrossUserPermission(callingUid, userId,
14430                true /* requireFullPermission */, true /* checkShell */,
14431                "setApplicationHiddenSetting for user " + userId);
14432
14433        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14434            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14435            return false;
14436        }
14437
14438        long callingId = Binder.clearCallingIdentity();
14439        try {
14440            boolean sendAdded = false;
14441            boolean sendRemoved = false;
14442            // writer
14443            synchronized (mPackages) {
14444                pkgSetting = mSettings.mPackages.get(packageName);
14445                if (pkgSetting == null) {
14446                    return false;
14447                }
14448                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14449                    return false;
14450                }
14451                // Do not allow "android" is being disabled
14452                if ("android".equals(packageName)) {
14453                    Slog.w(TAG, "Cannot hide package: android");
14454                    return false;
14455                }
14456                // Cannot hide static shared libs as they are considered
14457                // a part of the using app (emulating static linking). Also
14458                // static libs are installed always on internal storage.
14459                PackageParser.Package pkg = mPackages.get(packageName);
14460                if (pkg != null && pkg.staticSharedLibName != null) {
14461                    Slog.w(TAG, "Cannot hide package: " + packageName
14462                            + " providing static shared library: "
14463                            + pkg.staticSharedLibName);
14464                    return false;
14465                }
14466                // Only allow protected packages to hide themselves.
14467                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14468                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14469                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14470                    return false;
14471                }
14472
14473                if (pkgSetting.getHidden(userId) != hidden) {
14474                    pkgSetting.setHidden(hidden, userId);
14475                    mSettings.writePackageRestrictionsLPr(userId);
14476                    if (hidden) {
14477                        sendRemoved = true;
14478                    } else {
14479                        sendAdded = true;
14480                    }
14481                }
14482            }
14483            if (sendAdded) {
14484                sendPackageAddedForUser(packageName, pkgSetting, userId);
14485                return true;
14486            }
14487            if (sendRemoved) {
14488                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14489                        "hiding pkg");
14490                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14491                return true;
14492            }
14493        } finally {
14494            Binder.restoreCallingIdentity(callingId);
14495        }
14496        return false;
14497    }
14498
14499    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14500            int userId) {
14501        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14502        info.removedPackage = packageName;
14503        info.installerPackageName = pkgSetting.installerPackageName;
14504        info.removedUsers = new int[] {userId};
14505        info.broadcastUsers = new int[] {userId};
14506        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14507        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14508    }
14509
14510    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14511        if (pkgList.length > 0) {
14512            Bundle extras = new Bundle(1);
14513            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14514
14515            sendPackageBroadcast(
14516                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14517                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14518                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14519                    new int[] {userId});
14520        }
14521    }
14522
14523    /**
14524     * Returns true if application is not found or there was an error. Otherwise it returns
14525     * the hidden state of the package for the given user.
14526     */
14527    @Override
14528    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14529        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14530        final int callingUid = Binder.getCallingUid();
14531        enforceCrossUserPermission(callingUid, userId,
14532                true /* requireFullPermission */, false /* checkShell */,
14533                "getApplicationHidden for user " + userId);
14534        PackageSetting ps;
14535        long callingId = Binder.clearCallingIdentity();
14536        try {
14537            // writer
14538            synchronized (mPackages) {
14539                ps = mSettings.mPackages.get(packageName);
14540                if (ps == null) {
14541                    return true;
14542                }
14543                if (filterAppAccessLPr(ps, callingUid, userId)) {
14544                    return true;
14545                }
14546                return ps.getHidden(userId);
14547            }
14548        } finally {
14549            Binder.restoreCallingIdentity(callingId);
14550        }
14551    }
14552
14553    /**
14554     * @hide
14555     */
14556    @Override
14557    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14558            int installReason) {
14559        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14560                null);
14561        PackageSetting pkgSetting;
14562        final int callingUid = Binder.getCallingUid();
14563        enforceCrossUserPermission(callingUid, userId,
14564                true /* requireFullPermission */, true /* checkShell */,
14565                "installExistingPackage for user " + userId);
14566        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14567            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14568        }
14569
14570        long callingId = Binder.clearCallingIdentity();
14571        try {
14572            boolean installed = false;
14573            final boolean instantApp =
14574                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14575            final boolean fullApp =
14576                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14577
14578            // writer
14579            synchronized (mPackages) {
14580                pkgSetting = mSettings.mPackages.get(packageName);
14581                if (pkgSetting == null) {
14582                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14583                }
14584                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14585                    // only allow the existing package to be used if it's installed as a full
14586                    // application for at least one user
14587                    boolean installAllowed = false;
14588                    for (int checkUserId : sUserManager.getUserIds()) {
14589                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14590                        if (installAllowed) {
14591                            break;
14592                        }
14593                    }
14594                    if (!installAllowed) {
14595                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14596                    }
14597                }
14598                if (!pkgSetting.getInstalled(userId)) {
14599                    pkgSetting.setInstalled(true, userId);
14600                    pkgSetting.setHidden(false, userId);
14601                    pkgSetting.setInstallReason(installReason, userId);
14602                    mSettings.writePackageRestrictionsLPr(userId);
14603                    mSettings.writeKernelMappingLPr(pkgSetting);
14604                    installed = true;
14605                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14606                    // upgrade app from instant to full; we don't allow app downgrade
14607                    installed = true;
14608                }
14609                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14610            }
14611
14612            if (installed) {
14613                if (pkgSetting.pkg != null) {
14614                    synchronized (mInstallLock) {
14615                        // We don't need to freeze for a brand new install
14616                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14617                    }
14618                }
14619                sendPackageAddedForUser(packageName, pkgSetting, userId);
14620                synchronized (mPackages) {
14621                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14622                }
14623            }
14624        } finally {
14625            Binder.restoreCallingIdentity(callingId);
14626        }
14627
14628        return PackageManager.INSTALL_SUCCEEDED;
14629    }
14630
14631    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14632            boolean instantApp, boolean fullApp) {
14633        // no state specified; do nothing
14634        if (!instantApp && !fullApp) {
14635            return;
14636        }
14637        if (userId != UserHandle.USER_ALL) {
14638            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14639                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14640            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14641                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14642            }
14643        } else {
14644            for (int currentUserId : sUserManager.getUserIds()) {
14645                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14646                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14647                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14648                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14649                }
14650            }
14651        }
14652    }
14653
14654    boolean isUserRestricted(int userId, String restrictionKey) {
14655        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14656        if (restrictions.getBoolean(restrictionKey, false)) {
14657            Log.w(TAG, "User is restricted: " + restrictionKey);
14658            return true;
14659        }
14660        return false;
14661    }
14662
14663    @Override
14664    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14665            int userId) {
14666        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14667        final int callingUid = Binder.getCallingUid();
14668        enforceCrossUserPermission(callingUid, userId,
14669                true /* requireFullPermission */, true /* checkShell */,
14670                "setPackagesSuspended for user " + userId);
14671
14672        if (ArrayUtils.isEmpty(packageNames)) {
14673            return packageNames;
14674        }
14675
14676        // List of package names for whom the suspended state has changed.
14677        List<String> changedPackages = new ArrayList<>(packageNames.length);
14678        // List of package names for whom the suspended state is not set as requested in this
14679        // method.
14680        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14681        long callingId = Binder.clearCallingIdentity();
14682        try {
14683            for (int i = 0; i < packageNames.length; i++) {
14684                String packageName = packageNames[i];
14685                boolean changed = false;
14686                final int appId;
14687                synchronized (mPackages) {
14688                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14689                    if (pkgSetting == null
14690                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14691                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14692                                + "\". Skipping suspending/un-suspending.");
14693                        unactionedPackages.add(packageName);
14694                        continue;
14695                    }
14696                    appId = pkgSetting.appId;
14697                    if (pkgSetting.getSuspended(userId) != suspended) {
14698                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14699                            unactionedPackages.add(packageName);
14700                            continue;
14701                        }
14702                        pkgSetting.setSuspended(suspended, userId);
14703                        mSettings.writePackageRestrictionsLPr(userId);
14704                        changed = true;
14705                        changedPackages.add(packageName);
14706                    }
14707                }
14708
14709                if (changed && suspended) {
14710                    killApplication(packageName, UserHandle.getUid(userId, appId),
14711                            "suspending package");
14712                }
14713            }
14714        } finally {
14715            Binder.restoreCallingIdentity(callingId);
14716        }
14717
14718        if (!changedPackages.isEmpty()) {
14719            sendPackagesSuspendedForUser(changedPackages.toArray(
14720                    new String[changedPackages.size()]), userId, suspended);
14721        }
14722
14723        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14724    }
14725
14726    @Override
14727    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14728        final int callingUid = Binder.getCallingUid();
14729        enforceCrossUserPermission(callingUid, userId,
14730                true /* requireFullPermission */, false /* checkShell */,
14731                "isPackageSuspendedForUser for user " + userId);
14732        synchronized (mPackages) {
14733            final PackageSetting ps = mSettings.mPackages.get(packageName);
14734            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14735                throw new IllegalArgumentException("Unknown target package: " + packageName);
14736            }
14737            return ps.getSuspended(userId);
14738        }
14739    }
14740
14741    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14742        if (isPackageDeviceAdmin(packageName, userId)) {
14743            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14744                    + "\": has an active device admin");
14745            return false;
14746        }
14747
14748        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14749        if (packageName.equals(activeLauncherPackageName)) {
14750            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14751                    + "\": contains the active launcher");
14752            return false;
14753        }
14754
14755        if (packageName.equals(mRequiredInstallerPackage)) {
14756            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14757                    + "\": required for package installation");
14758            return false;
14759        }
14760
14761        if (packageName.equals(mRequiredUninstallerPackage)) {
14762            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14763                    + "\": required for package uninstallation");
14764            return false;
14765        }
14766
14767        if (packageName.equals(mRequiredVerifierPackage)) {
14768            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14769                    + "\": required for package verification");
14770            return false;
14771        }
14772
14773        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14774            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14775                    + "\": is the default dialer");
14776            return false;
14777        }
14778
14779        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14780            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14781                    + "\": protected package");
14782            return false;
14783        }
14784
14785        // Cannot suspend static shared libs as they are considered
14786        // a part of the using app (emulating static linking). Also
14787        // static libs are installed always on internal storage.
14788        PackageParser.Package pkg = mPackages.get(packageName);
14789        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14790            Slog.w(TAG, "Cannot suspend package: " + packageName
14791                    + " providing static shared library: "
14792                    + pkg.staticSharedLibName);
14793            return false;
14794        }
14795
14796        return true;
14797    }
14798
14799    private String getActiveLauncherPackageName(int userId) {
14800        Intent intent = new Intent(Intent.ACTION_MAIN);
14801        intent.addCategory(Intent.CATEGORY_HOME);
14802        ResolveInfo resolveInfo = resolveIntent(
14803                intent,
14804                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14805                PackageManager.MATCH_DEFAULT_ONLY,
14806                userId);
14807
14808        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14809    }
14810
14811    private String getDefaultDialerPackageName(int userId) {
14812        synchronized (mPackages) {
14813            return mSettings.getDefaultDialerPackageNameLPw(userId);
14814        }
14815    }
14816
14817    @Override
14818    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14819        mContext.enforceCallingOrSelfPermission(
14820                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14821                "Only package verification agents can verify applications");
14822
14823        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14824        final PackageVerificationResponse response = new PackageVerificationResponse(
14825                verificationCode, Binder.getCallingUid());
14826        msg.arg1 = id;
14827        msg.obj = response;
14828        mHandler.sendMessage(msg);
14829    }
14830
14831    @Override
14832    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14833            long millisecondsToDelay) {
14834        mContext.enforceCallingOrSelfPermission(
14835                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14836                "Only package verification agents can extend verification timeouts");
14837
14838        final PackageVerificationState state = mPendingVerification.get(id);
14839        final PackageVerificationResponse response = new PackageVerificationResponse(
14840                verificationCodeAtTimeout, Binder.getCallingUid());
14841
14842        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14843            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14844        }
14845        if (millisecondsToDelay < 0) {
14846            millisecondsToDelay = 0;
14847        }
14848        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14849                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14850            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14851        }
14852
14853        if ((state != null) && !state.timeoutExtended()) {
14854            state.extendTimeout();
14855
14856            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14857            msg.arg1 = id;
14858            msg.obj = response;
14859            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14860        }
14861    }
14862
14863    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14864            int verificationCode, UserHandle user) {
14865        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14866        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14867        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14868        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14869        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14870
14871        mContext.sendBroadcastAsUser(intent, user,
14872                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14873    }
14874
14875    private ComponentName matchComponentForVerifier(String packageName,
14876            List<ResolveInfo> receivers) {
14877        ActivityInfo targetReceiver = null;
14878
14879        final int NR = receivers.size();
14880        for (int i = 0; i < NR; i++) {
14881            final ResolveInfo info = receivers.get(i);
14882            if (info.activityInfo == null) {
14883                continue;
14884            }
14885
14886            if (packageName.equals(info.activityInfo.packageName)) {
14887                targetReceiver = info.activityInfo;
14888                break;
14889            }
14890        }
14891
14892        if (targetReceiver == null) {
14893            return null;
14894        }
14895
14896        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14897    }
14898
14899    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14900            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14901        if (pkgInfo.verifiers.length == 0) {
14902            return null;
14903        }
14904
14905        final int N = pkgInfo.verifiers.length;
14906        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14907        for (int i = 0; i < N; i++) {
14908            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14909
14910            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14911                    receivers);
14912            if (comp == null) {
14913                continue;
14914            }
14915
14916            final int verifierUid = getUidForVerifier(verifierInfo);
14917            if (verifierUid == -1) {
14918                continue;
14919            }
14920
14921            if (DEBUG_VERIFY) {
14922                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14923                        + " with the correct signature");
14924            }
14925            sufficientVerifiers.add(comp);
14926            verificationState.addSufficientVerifier(verifierUid);
14927        }
14928
14929        return sufficientVerifiers;
14930    }
14931
14932    private int getUidForVerifier(VerifierInfo verifierInfo) {
14933        synchronized (mPackages) {
14934            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14935            if (pkg == null) {
14936                return -1;
14937            } else if (pkg.mSignatures.length != 1) {
14938                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14939                        + " has more than one signature; ignoring");
14940                return -1;
14941            }
14942
14943            /*
14944             * If the public key of the package's signature does not match
14945             * our expected public key, then this is a different package and
14946             * we should skip.
14947             */
14948
14949            final byte[] expectedPublicKey;
14950            try {
14951                final Signature verifierSig = pkg.mSignatures[0];
14952                final PublicKey publicKey = verifierSig.getPublicKey();
14953                expectedPublicKey = publicKey.getEncoded();
14954            } catch (CertificateException e) {
14955                return -1;
14956            }
14957
14958            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14959
14960            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14961                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14962                        + " does not have the expected public key; ignoring");
14963                return -1;
14964            }
14965
14966            return pkg.applicationInfo.uid;
14967        }
14968    }
14969
14970    @Override
14971    public void finishPackageInstall(int token, boolean didLaunch) {
14972        enforceSystemOrRoot("Only the system is allowed to finish installs");
14973
14974        if (DEBUG_INSTALL) {
14975            Slog.v(TAG, "BM finishing package install for " + token);
14976        }
14977        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14978
14979        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14980        mHandler.sendMessage(msg);
14981    }
14982
14983    /**
14984     * Get the verification agent timeout.  Used for both the APK verifier and the
14985     * intent filter verifier.
14986     *
14987     * @return verification timeout in milliseconds
14988     */
14989    private long getVerificationTimeout() {
14990        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14991                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14992                DEFAULT_VERIFICATION_TIMEOUT);
14993    }
14994
14995    /**
14996     * Get the default verification agent response code.
14997     *
14998     * @return default verification response code
14999     */
15000    private int getDefaultVerificationResponse(UserHandle user) {
15001        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15002            return PackageManager.VERIFICATION_REJECT;
15003        }
15004        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15005                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15006                DEFAULT_VERIFICATION_RESPONSE);
15007    }
15008
15009    /**
15010     * Check whether or not package verification has been enabled.
15011     *
15012     * @return true if verification should be performed
15013     */
15014    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15015        if (!DEFAULT_VERIFY_ENABLE) {
15016            return false;
15017        }
15018
15019        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15020
15021        // Check if installing from ADB
15022        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15023            // Do not run verification in a test harness environment
15024            if (ActivityManager.isRunningInTestHarness()) {
15025                return false;
15026            }
15027            if (ensureVerifyAppsEnabled) {
15028                return true;
15029            }
15030            // Check if the developer does not want package verification for ADB installs
15031            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15032                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15033                return false;
15034            }
15035        } else {
15036            // only when not installed from ADB, skip verification for instant apps when
15037            // the installer and verifier are the same.
15038            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15039                if (mInstantAppInstallerActivity != null
15040                        && mInstantAppInstallerActivity.packageName.equals(
15041                                mRequiredVerifierPackage)) {
15042                    try {
15043                        mContext.getSystemService(AppOpsManager.class)
15044                                .checkPackage(installerUid, mRequiredVerifierPackage);
15045                        if (DEBUG_VERIFY) {
15046                            Slog.i(TAG, "disable verification for instant app");
15047                        }
15048                        return false;
15049                    } catch (SecurityException ignore) { }
15050                }
15051            }
15052        }
15053
15054        if (ensureVerifyAppsEnabled) {
15055            return true;
15056        }
15057
15058        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15059                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15060    }
15061
15062    @Override
15063    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15064            throws RemoteException {
15065        mContext.enforceCallingOrSelfPermission(
15066                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15067                "Only intentfilter verification agents can verify applications");
15068
15069        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15070        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15071                Binder.getCallingUid(), verificationCode, failedDomains);
15072        msg.arg1 = id;
15073        msg.obj = response;
15074        mHandler.sendMessage(msg);
15075    }
15076
15077    @Override
15078    public int getIntentVerificationStatus(String packageName, int userId) {
15079        final int callingUid = Binder.getCallingUid();
15080        if (getInstantAppPackageName(callingUid) != null) {
15081            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15082        }
15083        synchronized (mPackages) {
15084            final PackageSetting ps = mSettings.mPackages.get(packageName);
15085            if (ps == null
15086                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15087                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15088            }
15089            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15090        }
15091    }
15092
15093    @Override
15094    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15095        mContext.enforceCallingOrSelfPermission(
15096                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15097
15098        boolean result = false;
15099        synchronized (mPackages) {
15100            final PackageSetting ps = mSettings.mPackages.get(packageName);
15101            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15102                return false;
15103            }
15104            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15105        }
15106        if (result) {
15107            scheduleWritePackageRestrictionsLocked(userId);
15108        }
15109        return result;
15110    }
15111
15112    @Override
15113    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15114            String packageName) {
15115        final int callingUid = Binder.getCallingUid();
15116        if (getInstantAppPackageName(callingUid) != null) {
15117            return ParceledListSlice.emptyList();
15118        }
15119        synchronized (mPackages) {
15120            final PackageSetting ps = mSettings.mPackages.get(packageName);
15121            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15122                return ParceledListSlice.emptyList();
15123            }
15124            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15125        }
15126    }
15127
15128    @Override
15129    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15130        if (TextUtils.isEmpty(packageName)) {
15131            return ParceledListSlice.emptyList();
15132        }
15133        final int callingUid = Binder.getCallingUid();
15134        final int callingUserId = UserHandle.getUserId(callingUid);
15135        synchronized (mPackages) {
15136            PackageParser.Package pkg = mPackages.get(packageName);
15137            if (pkg == null || pkg.activities == null) {
15138                return ParceledListSlice.emptyList();
15139            }
15140            if (pkg.mExtras == null) {
15141                return ParceledListSlice.emptyList();
15142            }
15143            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15144            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15145                return ParceledListSlice.emptyList();
15146            }
15147            final int count = pkg.activities.size();
15148            ArrayList<IntentFilter> result = new ArrayList<>();
15149            for (int n=0; n<count; n++) {
15150                PackageParser.Activity activity = pkg.activities.get(n);
15151                if (activity.intents != null && activity.intents.size() > 0) {
15152                    result.addAll(activity.intents);
15153                }
15154            }
15155            return new ParceledListSlice<>(result);
15156        }
15157    }
15158
15159    @Override
15160    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15161        mContext.enforceCallingOrSelfPermission(
15162                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15163
15164        synchronized (mPackages) {
15165            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15166            if (packageName != null) {
15167                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15168                        packageName, userId);
15169            }
15170            return result;
15171        }
15172    }
15173
15174    @Override
15175    public String getDefaultBrowserPackageName(int userId) {
15176        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15177            return null;
15178        }
15179        synchronized (mPackages) {
15180            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15181        }
15182    }
15183
15184    /**
15185     * Get the "allow unknown sources" setting.
15186     *
15187     * @return the current "allow unknown sources" setting
15188     */
15189    private int getUnknownSourcesSettings() {
15190        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15191                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15192                -1);
15193    }
15194
15195    @Override
15196    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15197        final int callingUid = Binder.getCallingUid();
15198        if (getInstantAppPackageName(callingUid) != null) {
15199            return;
15200        }
15201        // writer
15202        synchronized (mPackages) {
15203            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15204            if (targetPackageSetting == null
15205                    || filterAppAccessLPr(
15206                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15207                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15208            }
15209
15210            PackageSetting installerPackageSetting;
15211            if (installerPackageName != null) {
15212                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15213                if (installerPackageSetting == null) {
15214                    throw new IllegalArgumentException("Unknown installer package: "
15215                            + installerPackageName);
15216                }
15217            } else {
15218                installerPackageSetting = null;
15219            }
15220
15221            Signature[] callerSignature;
15222            Object obj = mSettings.getUserIdLPr(callingUid);
15223            if (obj != null) {
15224                if (obj instanceof SharedUserSetting) {
15225                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15226                } else if (obj instanceof PackageSetting) {
15227                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15228                } else {
15229                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15230                }
15231            } else {
15232                throw new SecurityException("Unknown calling UID: " + callingUid);
15233            }
15234
15235            // Verify: can't set installerPackageName to a package that is
15236            // not signed with the same cert as the caller.
15237            if (installerPackageSetting != null) {
15238                if (compareSignatures(callerSignature,
15239                        installerPackageSetting.signatures.mSignatures)
15240                        != PackageManager.SIGNATURE_MATCH) {
15241                    throw new SecurityException(
15242                            "Caller does not have same cert as new installer package "
15243                            + installerPackageName);
15244                }
15245            }
15246
15247            // Verify: if target already has an installer package, it must
15248            // be signed with the same cert as the caller.
15249            if (targetPackageSetting.installerPackageName != null) {
15250                PackageSetting setting = mSettings.mPackages.get(
15251                        targetPackageSetting.installerPackageName);
15252                // If the currently set package isn't valid, then it's always
15253                // okay to change it.
15254                if (setting != null) {
15255                    if (compareSignatures(callerSignature,
15256                            setting.signatures.mSignatures)
15257                            != PackageManager.SIGNATURE_MATCH) {
15258                        throw new SecurityException(
15259                                "Caller does not have same cert as old installer package "
15260                                + targetPackageSetting.installerPackageName);
15261                    }
15262                }
15263            }
15264
15265            // Okay!
15266            targetPackageSetting.installerPackageName = installerPackageName;
15267            if (installerPackageName != null) {
15268                mSettings.mInstallerPackages.add(installerPackageName);
15269            }
15270            scheduleWriteSettingsLocked();
15271        }
15272    }
15273
15274    @Override
15275    public void setApplicationCategoryHint(String packageName, int categoryHint,
15276            String callerPackageName) {
15277        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15278            throw new SecurityException("Instant applications don't have access to this method");
15279        }
15280        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15281                callerPackageName);
15282        synchronized (mPackages) {
15283            PackageSetting ps = mSettings.mPackages.get(packageName);
15284            if (ps == null) {
15285                throw new IllegalArgumentException("Unknown target package " + packageName);
15286            }
15287            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15288                throw new IllegalArgumentException("Unknown target package " + packageName);
15289            }
15290            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15291                throw new IllegalArgumentException("Calling package " + callerPackageName
15292                        + " is not installer for " + packageName);
15293            }
15294
15295            if (ps.categoryHint != categoryHint) {
15296                ps.categoryHint = categoryHint;
15297                scheduleWriteSettingsLocked();
15298            }
15299        }
15300    }
15301
15302    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15303        // Queue up an async operation since the package installation may take a little while.
15304        mHandler.post(new Runnable() {
15305            public void run() {
15306                mHandler.removeCallbacks(this);
15307                 // Result object to be returned
15308                PackageInstalledInfo res = new PackageInstalledInfo();
15309                res.setReturnCode(currentStatus);
15310                res.uid = -1;
15311                res.pkg = null;
15312                res.removedInfo = null;
15313                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15314                    args.doPreInstall(res.returnCode);
15315                    synchronized (mInstallLock) {
15316                        installPackageTracedLI(args, res);
15317                    }
15318                    args.doPostInstall(res.returnCode, res.uid);
15319                }
15320
15321                // A restore should be performed at this point if (a) the install
15322                // succeeded, (b) the operation is not an update, and (c) the new
15323                // package has not opted out of backup participation.
15324                final boolean update = res.removedInfo != null
15325                        && res.removedInfo.removedPackage != null;
15326                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15327                boolean doRestore = !update
15328                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15329
15330                // Set up the post-install work request bookkeeping.  This will be used
15331                // and cleaned up by the post-install event handling regardless of whether
15332                // there's a restore pass performed.  Token values are >= 1.
15333                int token;
15334                if (mNextInstallToken < 0) mNextInstallToken = 1;
15335                token = mNextInstallToken++;
15336
15337                PostInstallData data = new PostInstallData(args, res);
15338                mRunningInstalls.put(token, data);
15339                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15340
15341                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15342                    // Pass responsibility to the Backup Manager.  It will perform a
15343                    // restore if appropriate, then pass responsibility back to the
15344                    // Package Manager to run the post-install observer callbacks
15345                    // and broadcasts.
15346                    IBackupManager bm = IBackupManager.Stub.asInterface(
15347                            ServiceManager.getService(Context.BACKUP_SERVICE));
15348                    if (bm != null) {
15349                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15350                                + " to BM for possible restore");
15351                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15352                        try {
15353                            // TODO: http://b/22388012
15354                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15355                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15356                            } else {
15357                                doRestore = false;
15358                            }
15359                        } catch (RemoteException e) {
15360                            // can't happen; the backup manager is local
15361                        } catch (Exception e) {
15362                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15363                            doRestore = false;
15364                        }
15365                    } else {
15366                        Slog.e(TAG, "Backup Manager not found!");
15367                        doRestore = false;
15368                    }
15369                }
15370
15371                if (!doRestore) {
15372                    // No restore possible, or the Backup Manager was mysteriously not
15373                    // available -- just fire the post-install work request directly.
15374                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15375
15376                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15377
15378                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15379                    mHandler.sendMessage(msg);
15380                }
15381            }
15382        });
15383    }
15384
15385    /**
15386     * Callback from PackageSettings whenever an app is first transitioned out of the
15387     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15388     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15389     * here whether the app is the target of an ongoing install, and only send the
15390     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15391     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15392     * handling.
15393     */
15394    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15395        // Serialize this with the rest of the install-process message chain.  In the
15396        // restore-at-install case, this Runnable will necessarily run before the
15397        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15398        // are coherent.  In the non-restore case, the app has already completed install
15399        // and been launched through some other means, so it is not in a problematic
15400        // state for observers to see the FIRST_LAUNCH signal.
15401        mHandler.post(new Runnable() {
15402            @Override
15403            public void run() {
15404                for (int i = 0; i < mRunningInstalls.size(); i++) {
15405                    final PostInstallData data = mRunningInstalls.valueAt(i);
15406                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15407                        continue;
15408                    }
15409                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15410                        // right package; but is it for the right user?
15411                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15412                            if (userId == data.res.newUsers[uIndex]) {
15413                                if (DEBUG_BACKUP) {
15414                                    Slog.i(TAG, "Package " + pkgName
15415                                            + " being restored so deferring FIRST_LAUNCH");
15416                                }
15417                                return;
15418                            }
15419                        }
15420                    }
15421                }
15422                // didn't find it, so not being restored
15423                if (DEBUG_BACKUP) {
15424                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15425                }
15426                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15427            }
15428        });
15429    }
15430
15431    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15432        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15433                installerPkg, null, userIds);
15434    }
15435
15436    private abstract class HandlerParams {
15437        private static final int MAX_RETRIES = 4;
15438
15439        /**
15440         * Number of times startCopy() has been attempted and had a non-fatal
15441         * error.
15442         */
15443        private int mRetries = 0;
15444
15445        /** User handle for the user requesting the information or installation. */
15446        private final UserHandle mUser;
15447        String traceMethod;
15448        int traceCookie;
15449
15450        HandlerParams(UserHandle user) {
15451            mUser = user;
15452        }
15453
15454        UserHandle getUser() {
15455            return mUser;
15456        }
15457
15458        HandlerParams setTraceMethod(String traceMethod) {
15459            this.traceMethod = traceMethod;
15460            return this;
15461        }
15462
15463        HandlerParams setTraceCookie(int traceCookie) {
15464            this.traceCookie = traceCookie;
15465            return this;
15466        }
15467
15468        final boolean startCopy() {
15469            boolean res;
15470            try {
15471                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15472
15473                if (++mRetries > MAX_RETRIES) {
15474                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15475                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15476                    handleServiceError();
15477                    return false;
15478                } else {
15479                    handleStartCopy();
15480                    res = true;
15481                }
15482            } catch (RemoteException e) {
15483                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15484                mHandler.sendEmptyMessage(MCS_RECONNECT);
15485                res = false;
15486            }
15487            handleReturnCode();
15488            return res;
15489        }
15490
15491        final void serviceError() {
15492            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15493            handleServiceError();
15494            handleReturnCode();
15495        }
15496
15497        abstract void handleStartCopy() throws RemoteException;
15498        abstract void handleServiceError();
15499        abstract void handleReturnCode();
15500    }
15501
15502    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15503        for (File path : paths) {
15504            try {
15505                mcs.clearDirectory(path.getAbsolutePath());
15506            } catch (RemoteException e) {
15507            }
15508        }
15509    }
15510
15511    static class OriginInfo {
15512        /**
15513         * Location where install is coming from, before it has been
15514         * copied/renamed into place. This could be a single monolithic APK
15515         * file, or a cluster directory. This location may be untrusted.
15516         */
15517        final File file;
15518        final String cid;
15519
15520        /**
15521         * Flag indicating that {@link #file} or {@link #cid} has already been
15522         * staged, meaning downstream users don't need to defensively copy the
15523         * contents.
15524         */
15525        final boolean staged;
15526
15527        /**
15528         * Flag indicating that {@link #file} or {@link #cid} is an already
15529         * installed app that is being moved.
15530         */
15531        final boolean existing;
15532
15533        final String resolvedPath;
15534        final File resolvedFile;
15535
15536        static OriginInfo fromNothing() {
15537            return new OriginInfo(null, null, false, false);
15538        }
15539
15540        static OriginInfo fromUntrustedFile(File file) {
15541            return new OriginInfo(file, null, false, false);
15542        }
15543
15544        static OriginInfo fromExistingFile(File file) {
15545            return new OriginInfo(file, null, false, true);
15546        }
15547
15548        static OriginInfo fromStagedFile(File file) {
15549            return new OriginInfo(file, null, true, false);
15550        }
15551
15552        static OriginInfo fromStagedContainer(String cid) {
15553            return new OriginInfo(null, cid, true, false);
15554        }
15555
15556        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15557            this.file = file;
15558            this.cid = cid;
15559            this.staged = staged;
15560            this.existing = existing;
15561
15562            if (cid != null) {
15563                resolvedPath = PackageHelper.getSdDir(cid);
15564                resolvedFile = new File(resolvedPath);
15565            } else if (file != null) {
15566                resolvedPath = file.getAbsolutePath();
15567                resolvedFile = file;
15568            } else {
15569                resolvedPath = null;
15570                resolvedFile = null;
15571            }
15572        }
15573    }
15574
15575    static class MoveInfo {
15576        final int moveId;
15577        final String fromUuid;
15578        final String toUuid;
15579        final String packageName;
15580        final String dataAppName;
15581        final int appId;
15582        final String seinfo;
15583        final int targetSdkVersion;
15584
15585        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15586                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15587            this.moveId = moveId;
15588            this.fromUuid = fromUuid;
15589            this.toUuid = toUuid;
15590            this.packageName = packageName;
15591            this.dataAppName = dataAppName;
15592            this.appId = appId;
15593            this.seinfo = seinfo;
15594            this.targetSdkVersion = targetSdkVersion;
15595        }
15596    }
15597
15598    static class VerificationInfo {
15599        /** A constant used to indicate that a uid value is not present. */
15600        public static final int NO_UID = -1;
15601
15602        /** URI referencing where the package was downloaded from. */
15603        final Uri originatingUri;
15604
15605        /** HTTP referrer URI associated with the originatingURI. */
15606        final Uri referrer;
15607
15608        /** UID of the application that the install request originated from. */
15609        final int originatingUid;
15610
15611        /** UID of application requesting the install */
15612        final int installerUid;
15613
15614        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15615            this.originatingUri = originatingUri;
15616            this.referrer = referrer;
15617            this.originatingUid = originatingUid;
15618            this.installerUid = installerUid;
15619        }
15620    }
15621
15622    class InstallParams extends HandlerParams {
15623        final OriginInfo origin;
15624        final MoveInfo move;
15625        final IPackageInstallObserver2 observer;
15626        int installFlags;
15627        final String installerPackageName;
15628        final String volumeUuid;
15629        private InstallArgs mArgs;
15630        private int mRet;
15631        final String packageAbiOverride;
15632        final String[] grantedRuntimePermissions;
15633        final VerificationInfo verificationInfo;
15634        final Certificate[][] certificates;
15635        final int installReason;
15636
15637        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15638                int installFlags, String installerPackageName, String volumeUuid,
15639                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15640                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15641            super(user);
15642            this.origin = origin;
15643            this.move = move;
15644            this.observer = observer;
15645            this.installFlags = installFlags;
15646            this.installerPackageName = installerPackageName;
15647            this.volumeUuid = volumeUuid;
15648            this.verificationInfo = verificationInfo;
15649            this.packageAbiOverride = packageAbiOverride;
15650            this.grantedRuntimePermissions = grantedPermissions;
15651            this.certificates = certificates;
15652            this.installReason = installReason;
15653        }
15654
15655        @Override
15656        public String toString() {
15657            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15658                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15659        }
15660
15661        private int installLocationPolicy(PackageInfoLite pkgLite) {
15662            String packageName = pkgLite.packageName;
15663            int installLocation = pkgLite.installLocation;
15664            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15665            // reader
15666            synchronized (mPackages) {
15667                // Currently installed package which the new package is attempting to replace or
15668                // null if no such package is installed.
15669                PackageParser.Package installedPkg = mPackages.get(packageName);
15670                // Package which currently owns the data which the new package will own if installed.
15671                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15672                // will be null whereas dataOwnerPkg will contain information about the package
15673                // which was uninstalled while keeping its data.
15674                PackageParser.Package dataOwnerPkg = installedPkg;
15675                if (dataOwnerPkg  == null) {
15676                    PackageSetting ps = mSettings.mPackages.get(packageName);
15677                    if (ps != null) {
15678                        dataOwnerPkg = ps.pkg;
15679                    }
15680                }
15681
15682                if (dataOwnerPkg != null) {
15683                    // If installed, the package will get access to data left on the device by its
15684                    // predecessor. As a security measure, this is permited only if this is not a
15685                    // version downgrade or if the predecessor package is marked as debuggable and
15686                    // a downgrade is explicitly requested.
15687                    //
15688                    // On debuggable platform builds, downgrades are permitted even for
15689                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15690                    // not offer security guarantees and thus it's OK to disable some security
15691                    // mechanisms to make debugging/testing easier on those builds. However, even on
15692                    // debuggable builds downgrades of packages are permitted only if requested via
15693                    // installFlags. This is because we aim to keep the behavior of debuggable
15694                    // platform builds as close as possible to the behavior of non-debuggable
15695                    // platform builds.
15696                    final boolean downgradeRequested =
15697                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15698                    final boolean packageDebuggable =
15699                                (dataOwnerPkg.applicationInfo.flags
15700                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15701                    final boolean downgradePermitted =
15702                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15703                    if (!downgradePermitted) {
15704                        try {
15705                            checkDowngrade(dataOwnerPkg, pkgLite);
15706                        } catch (PackageManagerException e) {
15707                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15708                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15709                        }
15710                    }
15711                }
15712
15713                if (installedPkg != null) {
15714                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15715                        // Check for updated system application.
15716                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15717                            if (onSd) {
15718                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15719                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15720                            }
15721                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15722                        } else {
15723                            if (onSd) {
15724                                // Install flag overrides everything.
15725                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15726                            }
15727                            // If current upgrade specifies particular preference
15728                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15729                                // Application explicitly specified internal.
15730                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15731                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15732                                // App explictly prefers external. Let policy decide
15733                            } else {
15734                                // Prefer previous location
15735                                if (isExternal(installedPkg)) {
15736                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15737                                }
15738                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15739                            }
15740                        }
15741                    } else {
15742                        // Invalid install. Return error code
15743                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15744                    }
15745                }
15746            }
15747            // All the special cases have been taken care of.
15748            // Return result based on recommended install location.
15749            if (onSd) {
15750                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15751            }
15752            return pkgLite.recommendedInstallLocation;
15753        }
15754
15755        /*
15756         * Invoke remote method to get package information and install
15757         * location values. Override install location based on default
15758         * policy if needed and then create install arguments based
15759         * on the install location.
15760         */
15761        public void handleStartCopy() throws RemoteException {
15762            int ret = PackageManager.INSTALL_SUCCEEDED;
15763
15764            // If we're already staged, we've firmly committed to an install location
15765            if (origin.staged) {
15766                if (origin.file != null) {
15767                    installFlags |= PackageManager.INSTALL_INTERNAL;
15768                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15769                } else if (origin.cid != null) {
15770                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15771                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15772                } else {
15773                    throw new IllegalStateException("Invalid stage location");
15774                }
15775            }
15776
15777            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15778            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15779            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15780            PackageInfoLite pkgLite = null;
15781
15782            if (onInt && onSd) {
15783                // Check if both bits are set.
15784                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15785                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15786            } else if (onSd && ephemeral) {
15787                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15788                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15789            } else {
15790                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15791                        packageAbiOverride);
15792
15793                if (DEBUG_EPHEMERAL && ephemeral) {
15794                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15795                }
15796
15797                /*
15798                 * If we have too little free space, try to free cache
15799                 * before giving up.
15800                 */
15801                if (!origin.staged && pkgLite.recommendedInstallLocation
15802                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15803                    // TODO: focus freeing disk space on the target device
15804                    final StorageManager storage = StorageManager.from(mContext);
15805                    final long lowThreshold = storage.getStorageLowBytes(
15806                            Environment.getDataDirectory());
15807
15808                    final long sizeBytes = mContainerService.calculateInstalledSize(
15809                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15810
15811                    try {
15812                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15813                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15814                                installFlags, packageAbiOverride);
15815                    } catch (InstallerException e) {
15816                        Slog.w(TAG, "Failed to free cache", e);
15817                    }
15818
15819                    /*
15820                     * The cache free must have deleted the file we
15821                     * downloaded to install.
15822                     *
15823                     * TODO: fix the "freeCache" call to not delete
15824                     *       the file we care about.
15825                     */
15826                    if (pkgLite.recommendedInstallLocation
15827                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15828                        pkgLite.recommendedInstallLocation
15829                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15830                    }
15831                }
15832            }
15833
15834            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15835                int loc = pkgLite.recommendedInstallLocation;
15836                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15837                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15838                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15839                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15840                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15841                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15842                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15843                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15844                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15845                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15846                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15847                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15848                } else {
15849                    // Override with defaults if needed.
15850                    loc = installLocationPolicy(pkgLite);
15851                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15852                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15853                    } else if (!onSd && !onInt) {
15854                        // Override install location with flags
15855                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15856                            // Set the flag to install on external media.
15857                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15858                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15859                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15860                            if (DEBUG_EPHEMERAL) {
15861                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15862                            }
15863                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15864                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15865                                    |PackageManager.INSTALL_INTERNAL);
15866                        } else {
15867                            // Make sure the flag for installing on external
15868                            // media is unset
15869                            installFlags |= PackageManager.INSTALL_INTERNAL;
15870                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15871                        }
15872                    }
15873                }
15874            }
15875
15876            final InstallArgs args = createInstallArgs(this);
15877            mArgs = args;
15878
15879            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15880                // TODO: http://b/22976637
15881                // Apps installed for "all" users use the device owner to verify the app
15882                UserHandle verifierUser = getUser();
15883                if (verifierUser == UserHandle.ALL) {
15884                    verifierUser = UserHandle.SYSTEM;
15885                }
15886
15887                /*
15888                 * Determine if we have any installed package verifiers. If we
15889                 * do, then we'll defer to them to verify the packages.
15890                 */
15891                final int requiredUid = mRequiredVerifierPackage == null ? -1
15892                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15893                                verifierUser.getIdentifier());
15894                final int installerUid =
15895                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15896                if (!origin.existing && requiredUid != -1
15897                        && isVerificationEnabled(
15898                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15899                    final Intent verification = new Intent(
15900                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15901                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15902                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15903                            PACKAGE_MIME_TYPE);
15904                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15905
15906                    // Query all live verifiers based on current user state
15907                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15908                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15909
15910                    if (DEBUG_VERIFY) {
15911                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15912                                + verification.toString() + " with " + pkgLite.verifiers.length
15913                                + " optional verifiers");
15914                    }
15915
15916                    final int verificationId = mPendingVerificationToken++;
15917
15918                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15919
15920                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15921                            installerPackageName);
15922
15923                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15924                            installFlags);
15925
15926                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15927                            pkgLite.packageName);
15928
15929                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15930                            pkgLite.versionCode);
15931
15932                    if (verificationInfo != null) {
15933                        if (verificationInfo.originatingUri != null) {
15934                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15935                                    verificationInfo.originatingUri);
15936                        }
15937                        if (verificationInfo.referrer != null) {
15938                            verification.putExtra(Intent.EXTRA_REFERRER,
15939                                    verificationInfo.referrer);
15940                        }
15941                        if (verificationInfo.originatingUid >= 0) {
15942                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15943                                    verificationInfo.originatingUid);
15944                        }
15945                        if (verificationInfo.installerUid >= 0) {
15946                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15947                                    verificationInfo.installerUid);
15948                        }
15949                    }
15950
15951                    final PackageVerificationState verificationState = new PackageVerificationState(
15952                            requiredUid, args);
15953
15954                    mPendingVerification.append(verificationId, verificationState);
15955
15956                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15957                            receivers, verificationState);
15958
15959                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15960                    final long idleDuration = getVerificationTimeout();
15961
15962                    /*
15963                     * If any sufficient verifiers were listed in the package
15964                     * manifest, attempt to ask them.
15965                     */
15966                    if (sufficientVerifiers != null) {
15967                        final int N = sufficientVerifiers.size();
15968                        if (N == 0) {
15969                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15970                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15971                        } else {
15972                            for (int i = 0; i < N; i++) {
15973                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15974                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15975                                        verifierComponent.getPackageName(), idleDuration,
15976                                        verifierUser.getIdentifier(), false, "package verifier");
15977
15978                                final Intent sufficientIntent = new Intent(verification);
15979                                sufficientIntent.setComponent(verifierComponent);
15980                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15981                            }
15982                        }
15983                    }
15984
15985                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15986                            mRequiredVerifierPackage, receivers);
15987                    if (ret == PackageManager.INSTALL_SUCCEEDED
15988                            && mRequiredVerifierPackage != null) {
15989                        Trace.asyncTraceBegin(
15990                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15991                        /*
15992                         * Send the intent to the required verification agent,
15993                         * but only start the verification timeout after the
15994                         * target BroadcastReceivers have run.
15995                         */
15996                        verification.setComponent(requiredVerifierComponent);
15997                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15998                                mRequiredVerifierPackage, idleDuration,
15999                                verifierUser.getIdentifier(), false, "package verifier");
16000                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16001                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16002                                new BroadcastReceiver() {
16003                                    @Override
16004                                    public void onReceive(Context context, Intent intent) {
16005                                        final Message msg = mHandler
16006                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16007                                        msg.arg1 = verificationId;
16008                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16009                                    }
16010                                }, null, 0, null, null);
16011
16012                        /*
16013                         * We don't want the copy to proceed until verification
16014                         * succeeds, so null out this field.
16015                         */
16016                        mArgs = null;
16017                    }
16018                } else {
16019                    /*
16020                     * No package verification is enabled, so immediately start
16021                     * the remote call to initiate copy using temporary file.
16022                     */
16023                    ret = args.copyApk(mContainerService, true);
16024                }
16025            }
16026
16027            mRet = ret;
16028        }
16029
16030        @Override
16031        void handleReturnCode() {
16032            // If mArgs is null, then MCS couldn't be reached. When it
16033            // reconnects, it will try again to install. At that point, this
16034            // will succeed.
16035            if (mArgs != null) {
16036                processPendingInstall(mArgs, mRet);
16037            }
16038        }
16039
16040        @Override
16041        void handleServiceError() {
16042            mArgs = createInstallArgs(this);
16043            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16044        }
16045
16046        public boolean isForwardLocked() {
16047            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16048        }
16049    }
16050
16051    /**
16052     * Used during creation of InstallArgs
16053     *
16054     * @param installFlags package installation flags
16055     * @return true if should be installed on external storage
16056     */
16057    private static boolean installOnExternalAsec(int installFlags) {
16058        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16059            return false;
16060        }
16061        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16062            return true;
16063        }
16064        return false;
16065    }
16066
16067    /**
16068     * Used during creation of InstallArgs
16069     *
16070     * @param installFlags package installation flags
16071     * @return true if should be installed as forward locked
16072     */
16073    private static boolean installForwardLocked(int installFlags) {
16074        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16075    }
16076
16077    private InstallArgs createInstallArgs(InstallParams params) {
16078        if (params.move != null) {
16079            return new MoveInstallArgs(params);
16080        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16081            return new AsecInstallArgs(params);
16082        } else {
16083            return new FileInstallArgs(params);
16084        }
16085    }
16086
16087    /**
16088     * Create args that describe an existing installed package. Typically used
16089     * when cleaning up old installs, or used as a move source.
16090     */
16091    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16092            String resourcePath, String[] instructionSets) {
16093        final boolean isInAsec;
16094        if (installOnExternalAsec(installFlags)) {
16095            /* Apps on SD card are always in ASEC containers. */
16096            isInAsec = true;
16097        } else if (installForwardLocked(installFlags)
16098                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16099            /*
16100             * Forward-locked apps are only in ASEC containers if they're the
16101             * new style
16102             */
16103            isInAsec = true;
16104        } else {
16105            isInAsec = false;
16106        }
16107
16108        if (isInAsec) {
16109            return new AsecInstallArgs(codePath, instructionSets,
16110                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16111        } else {
16112            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16113        }
16114    }
16115
16116    static abstract class InstallArgs {
16117        /** @see InstallParams#origin */
16118        final OriginInfo origin;
16119        /** @see InstallParams#move */
16120        final MoveInfo move;
16121
16122        final IPackageInstallObserver2 observer;
16123        // Always refers to PackageManager flags only
16124        final int installFlags;
16125        final String installerPackageName;
16126        final String volumeUuid;
16127        final UserHandle user;
16128        final String abiOverride;
16129        final String[] installGrantPermissions;
16130        /** If non-null, drop an async trace when the install completes */
16131        final String traceMethod;
16132        final int traceCookie;
16133        final Certificate[][] certificates;
16134        final int installReason;
16135
16136        // The list of instruction sets supported by this app. This is currently
16137        // only used during the rmdex() phase to clean up resources. We can get rid of this
16138        // if we move dex files under the common app path.
16139        /* nullable */ String[] instructionSets;
16140
16141        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16142                int installFlags, String installerPackageName, String volumeUuid,
16143                UserHandle user, String[] instructionSets,
16144                String abiOverride, String[] installGrantPermissions,
16145                String traceMethod, int traceCookie, Certificate[][] certificates,
16146                int installReason) {
16147            this.origin = origin;
16148            this.move = move;
16149            this.installFlags = installFlags;
16150            this.observer = observer;
16151            this.installerPackageName = installerPackageName;
16152            this.volumeUuid = volumeUuid;
16153            this.user = user;
16154            this.instructionSets = instructionSets;
16155            this.abiOverride = abiOverride;
16156            this.installGrantPermissions = installGrantPermissions;
16157            this.traceMethod = traceMethod;
16158            this.traceCookie = traceCookie;
16159            this.certificates = certificates;
16160            this.installReason = installReason;
16161        }
16162
16163        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16164        abstract int doPreInstall(int status);
16165
16166        /**
16167         * Rename package into final resting place. All paths on the given
16168         * scanned package should be updated to reflect the rename.
16169         */
16170        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16171        abstract int doPostInstall(int status, int uid);
16172
16173        /** @see PackageSettingBase#codePathString */
16174        abstract String getCodePath();
16175        /** @see PackageSettingBase#resourcePathString */
16176        abstract String getResourcePath();
16177
16178        // Need installer lock especially for dex file removal.
16179        abstract void cleanUpResourcesLI();
16180        abstract boolean doPostDeleteLI(boolean delete);
16181
16182        /**
16183         * Called before the source arguments are copied. This is used mostly
16184         * for MoveParams when it needs to read the source file to put it in the
16185         * destination.
16186         */
16187        int doPreCopy() {
16188            return PackageManager.INSTALL_SUCCEEDED;
16189        }
16190
16191        /**
16192         * Called after the source arguments are copied. This is used mostly for
16193         * MoveParams when it needs to read the source file to put it in the
16194         * destination.
16195         */
16196        int doPostCopy(int uid) {
16197            return PackageManager.INSTALL_SUCCEEDED;
16198        }
16199
16200        protected boolean isFwdLocked() {
16201            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16202        }
16203
16204        protected boolean isExternalAsec() {
16205            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16206        }
16207
16208        protected boolean isEphemeral() {
16209            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16210        }
16211
16212        UserHandle getUser() {
16213            return user;
16214        }
16215    }
16216
16217    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16218        if (!allCodePaths.isEmpty()) {
16219            if (instructionSets == null) {
16220                throw new IllegalStateException("instructionSet == null");
16221            }
16222            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16223            for (String codePath : allCodePaths) {
16224                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16225                    try {
16226                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16227                    } catch (InstallerException ignored) {
16228                    }
16229                }
16230            }
16231        }
16232    }
16233
16234    /**
16235     * Logic to handle installation of non-ASEC applications, including copying
16236     * and renaming logic.
16237     */
16238    class FileInstallArgs extends InstallArgs {
16239        private File codeFile;
16240        private File resourceFile;
16241
16242        // Example topology:
16243        // /data/app/com.example/base.apk
16244        // /data/app/com.example/split_foo.apk
16245        // /data/app/com.example/lib/arm/libfoo.so
16246        // /data/app/com.example/lib/arm64/libfoo.so
16247        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16248
16249        /** New install */
16250        FileInstallArgs(InstallParams params) {
16251            super(params.origin, params.move, params.observer, params.installFlags,
16252                    params.installerPackageName, params.volumeUuid,
16253                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16254                    params.grantedRuntimePermissions,
16255                    params.traceMethod, params.traceCookie, params.certificates,
16256                    params.installReason);
16257            if (isFwdLocked()) {
16258                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16259            }
16260        }
16261
16262        /** Existing install */
16263        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16264            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16265                    null, null, null, 0, null /*certificates*/,
16266                    PackageManager.INSTALL_REASON_UNKNOWN);
16267            this.codeFile = (codePath != null) ? new File(codePath) : null;
16268            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16269        }
16270
16271        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16272            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16273            try {
16274                return doCopyApk(imcs, temp);
16275            } finally {
16276                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16277            }
16278        }
16279
16280        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16281            if (origin.staged) {
16282                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16283                codeFile = origin.file;
16284                resourceFile = origin.file;
16285                return PackageManager.INSTALL_SUCCEEDED;
16286            }
16287
16288            try {
16289                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16290                final File tempDir =
16291                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16292                codeFile = tempDir;
16293                resourceFile = tempDir;
16294            } catch (IOException e) {
16295                Slog.w(TAG, "Failed to create copy file: " + e);
16296                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16297            }
16298
16299            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16300                @Override
16301                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16302                    if (!FileUtils.isValidExtFilename(name)) {
16303                        throw new IllegalArgumentException("Invalid filename: " + name);
16304                    }
16305                    try {
16306                        final File file = new File(codeFile, name);
16307                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16308                                O_RDWR | O_CREAT, 0644);
16309                        Os.chmod(file.getAbsolutePath(), 0644);
16310                        return new ParcelFileDescriptor(fd);
16311                    } catch (ErrnoException e) {
16312                        throw new RemoteException("Failed to open: " + e.getMessage());
16313                    }
16314                }
16315            };
16316
16317            int ret = PackageManager.INSTALL_SUCCEEDED;
16318            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16319            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16320                Slog.e(TAG, "Failed to copy package");
16321                return ret;
16322            }
16323
16324            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16325            NativeLibraryHelper.Handle handle = null;
16326            try {
16327                handle = NativeLibraryHelper.Handle.create(codeFile);
16328                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16329                        abiOverride);
16330            } catch (IOException e) {
16331                Slog.e(TAG, "Copying native libraries failed", e);
16332                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16333            } finally {
16334                IoUtils.closeQuietly(handle);
16335            }
16336
16337            return ret;
16338        }
16339
16340        int doPreInstall(int status) {
16341            if (status != PackageManager.INSTALL_SUCCEEDED) {
16342                cleanUp();
16343            }
16344            return status;
16345        }
16346
16347        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16348            if (status != PackageManager.INSTALL_SUCCEEDED) {
16349                cleanUp();
16350                return false;
16351            }
16352
16353            final File targetDir = codeFile.getParentFile();
16354            final File beforeCodeFile = codeFile;
16355            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16356
16357            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16358            try {
16359                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16360            } catch (ErrnoException e) {
16361                Slog.w(TAG, "Failed to rename", e);
16362                return false;
16363            }
16364
16365            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16366                Slog.w(TAG, "Failed to restorecon");
16367                return false;
16368            }
16369
16370            // Reflect the rename internally
16371            codeFile = afterCodeFile;
16372            resourceFile = afterCodeFile;
16373
16374            // Reflect the rename in scanned details
16375            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16376            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16377                    afterCodeFile, pkg.baseCodePath));
16378            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16379                    afterCodeFile, pkg.splitCodePaths));
16380
16381            // Reflect the rename in app info
16382            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16383            pkg.setApplicationInfoCodePath(pkg.codePath);
16384            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16385            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16386            pkg.setApplicationInfoResourcePath(pkg.codePath);
16387            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16388            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16389
16390            return true;
16391        }
16392
16393        int doPostInstall(int status, int uid) {
16394            if (status != PackageManager.INSTALL_SUCCEEDED) {
16395                cleanUp();
16396            }
16397            return status;
16398        }
16399
16400        @Override
16401        String getCodePath() {
16402            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16403        }
16404
16405        @Override
16406        String getResourcePath() {
16407            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16408        }
16409
16410        private boolean cleanUp() {
16411            if (codeFile == null || !codeFile.exists()) {
16412                return false;
16413            }
16414
16415            removeCodePathLI(codeFile);
16416
16417            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16418                resourceFile.delete();
16419            }
16420
16421            return true;
16422        }
16423
16424        void cleanUpResourcesLI() {
16425            // Try enumerating all code paths before deleting
16426            List<String> allCodePaths = Collections.EMPTY_LIST;
16427            if (codeFile != null && codeFile.exists()) {
16428                try {
16429                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16430                    allCodePaths = pkg.getAllCodePaths();
16431                } catch (PackageParserException e) {
16432                    // Ignored; we tried our best
16433                }
16434            }
16435
16436            cleanUp();
16437            removeDexFiles(allCodePaths, instructionSets);
16438        }
16439
16440        boolean doPostDeleteLI(boolean delete) {
16441            // XXX err, shouldn't we respect the delete flag?
16442            cleanUpResourcesLI();
16443            return true;
16444        }
16445    }
16446
16447    private boolean isAsecExternal(String cid) {
16448        final String asecPath = PackageHelper.getSdFilesystem(cid);
16449        return !asecPath.startsWith(mAsecInternalPath);
16450    }
16451
16452    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16453            PackageManagerException {
16454        if (copyRet < 0) {
16455            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16456                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16457                throw new PackageManagerException(copyRet, message);
16458            }
16459        }
16460    }
16461
16462    /**
16463     * Extract the StorageManagerService "container ID" from the full code path of an
16464     * .apk.
16465     */
16466    static String cidFromCodePath(String fullCodePath) {
16467        int eidx = fullCodePath.lastIndexOf("/");
16468        String subStr1 = fullCodePath.substring(0, eidx);
16469        int sidx = subStr1.lastIndexOf("/");
16470        return subStr1.substring(sidx+1, eidx);
16471    }
16472
16473    /**
16474     * Logic to handle installation of ASEC applications, including copying and
16475     * renaming logic.
16476     */
16477    class AsecInstallArgs extends InstallArgs {
16478        static final String RES_FILE_NAME = "pkg.apk";
16479        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16480
16481        String cid;
16482        String packagePath;
16483        String resourcePath;
16484
16485        /** New install */
16486        AsecInstallArgs(InstallParams params) {
16487            super(params.origin, params.move, params.observer, params.installFlags,
16488                    params.installerPackageName, params.volumeUuid,
16489                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16490                    params.grantedRuntimePermissions,
16491                    params.traceMethod, params.traceCookie, params.certificates,
16492                    params.installReason);
16493        }
16494
16495        /** Existing install */
16496        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16497                        boolean isExternal, boolean isForwardLocked) {
16498            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16499                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16500                    instructionSets, null, null, null, 0, null /*certificates*/,
16501                    PackageManager.INSTALL_REASON_UNKNOWN);
16502            // Hackily pretend we're still looking at a full code path
16503            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16504                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16505            }
16506
16507            // Extract cid from fullCodePath
16508            int eidx = fullCodePath.lastIndexOf("/");
16509            String subStr1 = fullCodePath.substring(0, eidx);
16510            int sidx = subStr1.lastIndexOf("/");
16511            cid = subStr1.substring(sidx+1, eidx);
16512            setMountPath(subStr1);
16513        }
16514
16515        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16516            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16517                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16518                    instructionSets, null, null, null, 0, null /*certificates*/,
16519                    PackageManager.INSTALL_REASON_UNKNOWN);
16520            this.cid = cid;
16521            setMountPath(PackageHelper.getSdDir(cid));
16522        }
16523
16524        void createCopyFile() {
16525            cid = mInstallerService.allocateExternalStageCidLegacy();
16526        }
16527
16528        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16529            if (origin.staged && origin.cid != null) {
16530                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16531                cid = origin.cid;
16532                setMountPath(PackageHelper.getSdDir(cid));
16533                return PackageManager.INSTALL_SUCCEEDED;
16534            }
16535
16536            if (temp) {
16537                createCopyFile();
16538            } else {
16539                /*
16540                 * Pre-emptively destroy the container since it's destroyed if
16541                 * copying fails due to it existing anyway.
16542                 */
16543                PackageHelper.destroySdDir(cid);
16544            }
16545
16546            final String newMountPath = imcs.copyPackageToContainer(
16547                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16548                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16549
16550            if (newMountPath != null) {
16551                setMountPath(newMountPath);
16552                return PackageManager.INSTALL_SUCCEEDED;
16553            } else {
16554                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16555            }
16556        }
16557
16558        @Override
16559        String getCodePath() {
16560            return packagePath;
16561        }
16562
16563        @Override
16564        String getResourcePath() {
16565            return resourcePath;
16566        }
16567
16568        int doPreInstall(int status) {
16569            if (status != PackageManager.INSTALL_SUCCEEDED) {
16570                // Destroy container
16571                PackageHelper.destroySdDir(cid);
16572            } else {
16573                boolean mounted = PackageHelper.isContainerMounted(cid);
16574                if (!mounted) {
16575                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16576                            Process.SYSTEM_UID);
16577                    if (newMountPath != null) {
16578                        setMountPath(newMountPath);
16579                    } else {
16580                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16581                    }
16582                }
16583            }
16584            return status;
16585        }
16586
16587        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16588            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16589            String newMountPath = null;
16590            if (PackageHelper.isContainerMounted(cid)) {
16591                // Unmount the container
16592                if (!PackageHelper.unMountSdDir(cid)) {
16593                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16594                    return false;
16595                }
16596            }
16597            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16598                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16599                        " which might be stale. Will try to clean up.");
16600                // Clean up the stale container and proceed to recreate.
16601                if (!PackageHelper.destroySdDir(newCacheId)) {
16602                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16603                    return false;
16604                }
16605                // Successfully cleaned up stale container. Try to rename again.
16606                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16607                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16608                            + " inspite of cleaning it up.");
16609                    return false;
16610                }
16611            }
16612            if (!PackageHelper.isContainerMounted(newCacheId)) {
16613                Slog.w(TAG, "Mounting container " + newCacheId);
16614                newMountPath = PackageHelper.mountSdDir(newCacheId,
16615                        getEncryptKey(), Process.SYSTEM_UID);
16616            } else {
16617                newMountPath = PackageHelper.getSdDir(newCacheId);
16618            }
16619            if (newMountPath == null) {
16620                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16621                return false;
16622            }
16623            Log.i(TAG, "Succesfully renamed " + cid +
16624                    " to " + newCacheId +
16625                    " at new path: " + newMountPath);
16626            cid = newCacheId;
16627
16628            final File beforeCodeFile = new File(packagePath);
16629            setMountPath(newMountPath);
16630            final File afterCodeFile = new File(packagePath);
16631
16632            // Reflect the rename in scanned details
16633            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16634            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16635                    afterCodeFile, pkg.baseCodePath));
16636            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16637                    afterCodeFile, pkg.splitCodePaths));
16638
16639            // Reflect the rename in app info
16640            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16641            pkg.setApplicationInfoCodePath(pkg.codePath);
16642            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16643            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16644            pkg.setApplicationInfoResourcePath(pkg.codePath);
16645            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16646            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16647
16648            return true;
16649        }
16650
16651        private void setMountPath(String mountPath) {
16652            final File mountFile = new File(mountPath);
16653
16654            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16655            if (monolithicFile.exists()) {
16656                packagePath = monolithicFile.getAbsolutePath();
16657                if (isFwdLocked()) {
16658                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16659                } else {
16660                    resourcePath = packagePath;
16661                }
16662            } else {
16663                packagePath = mountFile.getAbsolutePath();
16664                resourcePath = packagePath;
16665            }
16666        }
16667
16668        int doPostInstall(int status, int uid) {
16669            if (status != PackageManager.INSTALL_SUCCEEDED) {
16670                cleanUp();
16671            } else {
16672                final int groupOwner;
16673                final String protectedFile;
16674                if (isFwdLocked()) {
16675                    groupOwner = UserHandle.getSharedAppGid(uid);
16676                    protectedFile = RES_FILE_NAME;
16677                } else {
16678                    groupOwner = -1;
16679                    protectedFile = null;
16680                }
16681
16682                if (uid < Process.FIRST_APPLICATION_UID
16683                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16684                    Slog.e(TAG, "Failed to finalize " + cid);
16685                    PackageHelper.destroySdDir(cid);
16686                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16687                }
16688
16689                boolean mounted = PackageHelper.isContainerMounted(cid);
16690                if (!mounted) {
16691                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16692                }
16693            }
16694            return status;
16695        }
16696
16697        private void cleanUp() {
16698            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16699
16700            // Destroy secure container
16701            PackageHelper.destroySdDir(cid);
16702        }
16703
16704        private List<String> getAllCodePaths() {
16705            final File codeFile = new File(getCodePath());
16706            if (codeFile != null && codeFile.exists()) {
16707                try {
16708                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16709                    return pkg.getAllCodePaths();
16710                } catch (PackageParserException e) {
16711                    // Ignored; we tried our best
16712                }
16713            }
16714            return Collections.EMPTY_LIST;
16715        }
16716
16717        void cleanUpResourcesLI() {
16718            // Enumerate all code paths before deleting
16719            cleanUpResourcesLI(getAllCodePaths());
16720        }
16721
16722        private void cleanUpResourcesLI(List<String> allCodePaths) {
16723            cleanUp();
16724            removeDexFiles(allCodePaths, instructionSets);
16725        }
16726
16727        String getPackageName() {
16728            return getAsecPackageName(cid);
16729        }
16730
16731        boolean doPostDeleteLI(boolean delete) {
16732            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16733            final List<String> allCodePaths = getAllCodePaths();
16734            boolean mounted = PackageHelper.isContainerMounted(cid);
16735            if (mounted) {
16736                // Unmount first
16737                if (PackageHelper.unMountSdDir(cid)) {
16738                    mounted = false;
16739                }
16740            }
16741            if (!mounted && delete) {
16742                cleanUpResourcesLI(allCodePaths);
16743            }
16744            return !mounted;
16745        }
16746
16747        @Override
16748        int doPreCopy() {
16749            if (isFwdLocked()) {
16750                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16751                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16752                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16753                }
16754            }
16755
16756            return PackageManager.INSTALL_SUCCEEDED;
16757        }
16758
16759        @Override
16760        int doPostCopy(int uid) {
16761            if (isFwdLocked()) {
16762                if (uid < Process.FIRST_APPLICATION_UID
16763                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16764                                RES_FILE_NAME)) {
16765                    Slog.e(TAG, "Failed to finalize " + cid);
16766                    PackageHelper.destroySdDir(cid);
16767                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16768                }
16769            }
16770
16771            return PackageManager.INSTALL_SUCCEEDED;
16772        }
16773    }
16774
16775    /**
16776     * Logic to handle movement of existing installed applications.
16777     */
16778    class MoveInstallArgs extends InstallArgs {
16779        private File codeFile;
16780        private File resourceFile;
16781
16782        /** New install */
16783        MoveInstallArgs(InstallParams params) {
16784            super(params.origin, params.move, params.observer, params.installFlags,
16785                    params.installerPackageName, params.volumeUuid,
16786                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16787                    params.grantedRuntimePermissions,
16788                    params.traceMethod, params.traceCookie, params.certificates,
16789                    params.installReason);
16790        }
16791
16792        int copyApk(IMediaContainerService imcs, boolean temp) {
16793            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16794                    + move.fromUuid + " to " + move.toUuid);
16795            synchronized (mInstaller) {
16796                try {
16797                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16798                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16799                } catch (InstallerException e) {
16800                    Slog.w(TAG, "Failed to move app", e);
16801                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16802                }
16803            }
16804
16805            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16806            resourceFile = codeFile;
16807            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16808
16809            return PackageManager.INSTALL_SUCCEEDED;
16810        }
16811
16812        int doPreInstall(int status) {
16813            if (status != PackageManager.INSTALL_SUCCEEDED) {
16814                cleanUp(move.toUuid);
16815            }
16816            return status;
16817        }
16818
16819        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16820            if (status != PackageManager.INSTALL_SUCCEEDED) {
16821                cleanUp(move.toUuid);
16822                return false;
16823            }
16824
16825            // Reflect the move in app info
16826            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16827            pkg.setApplicationInfoCodePath(pkg.codePath);
16828            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16829            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16830            pkg.setApplicationInfoResourcePath(pkg.codePath);
16831            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16832            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16833
16834            return true;
16835        }
16836
16837        int doPostInstall(int status, int uid) {
16838            if (status == PackageManager.INSTALL_SUCCEEDED) {
16839                cleanUp(move.fromUuid);
16840            } else {
16841                cleanUp(move.toUuid);
16842            }
16843            return status;
16844        }
16845
16846        @Override
16847        String getCodePath() {
16848            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16849        }
16850
16851        @Override
16852        String getResourcePath() {
16853            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16854        }
16855
16856        private boolean cleanUp(String volumeUuid) {
16857            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16858                    move.dataAppName);
16859            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16860            final int[] userIds = sUserManager.getUserIds();
16861            synchronized (mInstallLock) {
16862                // Clean up both app data and code
16863                // All package moves are frozen until finished
16864                for (int userId : userIds) {
16865                    try {
16866                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16867                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16868                    } catch (InstallerException e) {
16869                        Slog.w(TAG, String.valueOf(e));
16870                    }
16871                }
16872                removeCodePathLI(codeFile);
16873            }
16874            return true;
16875        }
16876
16877        void cleanUpResourcesLI() {
16878            throw new UnsupportedOperationException();
16879        }
16880
16881        boolean doPostDeleteLI(boolean delete) {
16882            throw new UnsupportedOperationException();
16883        }
16884    }
16885
16886    static String getAsecPackageName(String packageCid) {
16887        int idx = packageCid.lastIndexOf("-");
16888        if (idx == -1) {
16889            return packageCid;
16890        }
16891        return packageCid.substring(0, idx);
16892    }
16893
16894    // Utility method used to create code paths based on package name and available index.
16895    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16896        String idxStr = "";
16897        int idx = 1;
16898        // Fall back to default value of idx=1 if prefix is not
16899        // part of oldCodePath
16900        if (oldCodePath != null) {
16901            String subStr = oldCodePath;
16902            // Drop the suffix right away
16903            if (suffix != null && subStr.endsWith(suffix)) {
16904                subStr = subStr.substring(0, subStr.length() - suffix.length());
16905            }
16906            // If oldCodePath already contains prefix find out the
16907            // ending index to either increment or decrement.
16908            int sidx = subStr.lastIndexOf(prefix);
16909            if (sidx != -1) {
16910                subStr = subStr.substring(sidx + prefix.length());
16911                if (subStr != null) {
16912                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16913                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16914                    }
16915                    try {
16916                        idx = Integer.parseInt(subStr);
16917                        if (idx <= 1) {
16918                            idx++;
16919                        } else {
16920                            idx--;
16921                        }
16922                    } catch(NumberFormatException e) {
16923                    }
16924                }
16925            }
16926        }
16927        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16928        return prefix + idxStr;
16929    }
16930
16931    private File getNextCodePath(File targetDir, String packageName) {
16932        File result;
16933        SecureRandom random = new SecureRandom();
16934        byte[] bytes = new byte[16];
16935        do {
16936            random.nextBytes(bytes);
16937            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16938            result = new File(targetDir, packageName + "-" + suffix);
16939        } while (result.exists());
16940        return result;
16941    }
16942
16943    // Utility method that returns the relative package path with respect
16944    // to the installation directory. Like say for /data/data/com.test-1.apk
16945    // string com.test-1 is returned.
16946    static String deriveCodePathName(String codePath) {
16947        if (codePath == null) {
16948            return null;
16949        }
16950        final File codeFile = new File(codePath);
16951        final String name = codeFile.getName();
16952        if (codeFile.isDirectory()) {
16953            return name;
16954        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16955            final int lastDot = name.lastIndexOf('.');
16956            return name.substring(0, lastDot);
16957        } else {
16958            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16959            return null;
16960        }
16961    }
16962
16963    static class PackageInstalledInfo {
16964        String name;
16965        int uid;
16966        // The set of users that originally had this package installed.
16967        int[] origUsers;
16968        // The set of users that now have this package installed.
16969        int[] newUsers;
16970        PackageParser.Package pkg;
16971        int returnCode;
16972        String returnMsg;
16973        PackageRemovedInfo removedInfo;
16974        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16975
16976        public void setError(int code, String msg) {
16977            setReturnCode(code);
16978            setReturnMessage(msg);
16979            Slog.w(TAG, msg);
16980        }
16981
16982        public void setError(String msg, PackageParserException e) {
16983            setReturnCode(e.error);
16984            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16985            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16986            for (int i = 0; i < childCount; i++) {
16987                addedChildPackages.valueAt(i).setError(msg, e);
16988            }
16989            Slog.w(TAG, msg, e);
16990        }
16991
16992        public void setError(String msg, PackageManagerException e) {
16993            returnCode = e.error;
16994            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16995            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16996            for (int i = 0; i < childCount; i++) {
16997                addedChildPackages.valueAt(i).setError(msg, e);
16998            }
16999            Slog.w(TAG, msg, e);
17000        }
17001
17002        public void setReturnCode(int returnCode) {
17003            this.returnCode = returnCode;
17004            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17005            for (int i = 0; i < childCount; i++) {
17006                addedChildPackages.valueAt(i).returnCode = returnCode;
17007            }
17008        }
17009
17010        private void setReturnMessage(String returnMsg) {
17011            this.returnMsg = returnMsg;
17012            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17013            for (int i = 0; i < childCount; i++) {
17014                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17015            }
17016        }
17017
17018        // In some error cases we want to convey more info back to the observer
17019        String origPackage;
17020        String origPermission;
17021    }
17022
17023    /*
17024     * Install a non-existing package.
17025     */
17026    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17027            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17028            PackageInstalledInfo res, int installReason) {
17029        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17030
17031        // Remember this for later, in case we need to rollback this install
17032        String pkgName = pkg.packageName;
17033
17034        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17035
17036        synchronized(mPackages) {
17037            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17038            if (renamedPackage != null) {
17039                // A package with the same name is already installed, though
17040                // it has been renamed to an older name.  The package we
17041                // are trying to install should be installed as an update to
17042                // the existing one, but that has not been requested, so bail.
17043                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17044                        + " without first uninstalling package running as "
17045                        + renamedPackage);
17046                return;
17047            }
17048            if (mPackages.containsKey(pkgName)) {
17049                // Don't allow installation over an existing package with the same name.
17050                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17051                        + " without first uninstalling.");
17052                return;
17053            }
17054        }
17055
17056        try {
17057            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17058                    System.currentTimeMillis(), user);
17059
17060            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17061
17062            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17063                prepareAppDataAfterInstallLIF(newPackage);
17064
17065            } else {
17066                // Remove package from internal structures, but keep around any
17067                // data that might have already existed
17068                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17069                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17070            }
17071        } catch (PackageManagerException e) {
17072            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17073        }
17074
17075        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17076    }
17077
17078    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17079        // Can't rotate keys during boot or if sharedUser.
17080        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17081                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17082            return false;
17083        }
17084        // app is using upgradeKeySets; make sure all are valid
17085        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17086        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17087        for (int i = 0; i < upgradeKeySets.length; i++) {
17088            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17089                Slog.wtf(TAG, "Package "
17090                         + (oldPs.name != null ? oldPs.name : "<null>")
17091                         + " contains upgrade-key-set reference to unknown key-set: "
17092                         + upgradeKeySets[i]
17093                         + " reverting to signatures check.");
17094                return false;
17095            }
17096        }
17097        return true;
17098    }
17099
17100    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17101        // Upgrade keysets are being used.  Determine if new package has a superset of the
17102        // required keys.
17103        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17104        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17105        for (int i = 0; i < upgradeKeySets.length; i++) {
17106            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17107            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17108                return true;
17109            }
17110        }
17111        return false;
17112    }
17113
17114    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17115        try (DigestInputStream digestStream =
17116                new DigestInputStream(new FileInputStream(file), digest)) {
17117            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17118        }
17119    }
17120
17121    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17122            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17123            int installReason) {
17124        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17125
17126        final PackageParser.Package oldPackage;
17127        final PackageSetting ps;
17128        final String pkgName = pkg.packageName;
17129        final int[] allUsers;
17130        final int[] installedUsers;
17131
17132        synchronized(mPackages) {
17133            oldPackage = mPackages.get(pkgName);
17134            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17135
17136            // don't allow upgrade to target a release SDK from a pre-release SDK
17137            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17138                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17139            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17140                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17141            if (oldTargetsPreRelease
17142                    && !newTargetsPreRelease
17143                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17144                Slog.w(TAG, "Can't install package targeting released sdk");
17145                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17146                return;
17147            }
17148
17149            ps = mSettings.mPackages.get(pkgName);
17150
17151            // verify signatures are valid
17152            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17153                if (!checkUpgradeKeySetLP(ps, pkg)) {
17154                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17155                            "New package not signed by keys specified by upgrade-keysets: "
17156                                    + pkgName);
17157                    return;
17158                }
17159            } else {
17160                // default to original signature matching
17161                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17162                        != PackageManager.SIGNATURE_MATCH) {
17163                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17164                            "New package has a different signature: " + pkgName);
17165                    return;
17166                }
17167            }
17168
17169            // don't allow a system upgrade unless the upgrade hash matches
17170            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17171                byte[] digestBytes = null;
17172                try {
17173                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17174                    updateDigest(digest, new File(pkg.baseCodePath));
17175                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17176                        for (String path : pkg.splitCodePaths) {
17177                            updateDigest(digest, new File(path));
17178                        }
17179                    }
17180                    digestBytes = digest.digest();
17181                } catch (NoSuchAlgorithmException | IOException e) {
17182                    res.setError(INSTALL_FAILED_INVALID_APK,
17183                            "Could not compute hash: " + pkgName);
17184                    return;
17185                }
17186                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17187                    res.setError(INSTALL_FAILED_INVALID_APK,
17188                            "New package fails restrict-update check: " + pkgName);
17189                    return;
17190                }
17191                // retain upgrade restriction
17192                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17193            }
17194
17195            // Check for shared user id changes
17196            String invalidPackageName =
17197                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17198            if (invalidPackageName != null) {
17199                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17200                        "Package " + invalidPackageName + " tried to change user "
17201                                + oldPackage.mSharedUserId);
17202                return;
17203            }
17204
17205            // In case of rollback, remember per-user/profile install state
17206            allUsers = sUserManager.getUserIds();
17207            installedUsers = ps.queryInstalledUsers(allUsers, true);
17208
17209            // don't allow an upgrade from full to ephemeral
17210            if (isInstantApp) {
17211                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17212                    for (int currentUser : allUsers) {
17213                        if (!ps.getInstantApp(currentUser)) {
17214                            // can't downgrade from full to instant
17215                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17216                                    + " for user: " + currentUser);
17217                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17218                            return;
17219                        }
17220                    }
17221                } else if (!ps.getInstantApp(user.getIdentifier())) {
17222                    // can't downgrade from full to instant
17223                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17224                            + " for user: " + user.getIdentifier());
17225                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17226                    return;
17227                }
17228            }
17229        }
17230
17231        // Update what is removed
17232        res.removedInfo = new PackageRemovedInfo(this);
17233        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17234        res.removedInfo.removedPackage = oldPackage.packageName;
17235        res.removedInfo.installerPackageName = ps.installerPackageName;
17236        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17237        res.removedInfo.isUpdate = true;
17238        res.removedInfo.origUsers = installedUsers;
17239        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17240        for (int i = 0; i < installedUsers.length; i++) {
17241            final int userId = installedUsers[i];
17242            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17243        }
17244
17245        final int childCount = (oldPackage.childPackages != null)
17246                ? oldPackage.childPackages.size() : 0;
17247        for (int i = 0; i < childCount; i++) {
17248            boolean childPackageUpdated = false;
17249            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17250            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17251            if (res.addedChildPackages != null) {
17252                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17253                if (childRes != null) {
17254                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17255                    childRes.removedInfo.removedPackage = childPkg.packageName;
17256                    if (childPs != null) {
17257                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17258                    }
17259                    childRes.removedInfo.isUpdate = true;
17260                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17261                    childPackageUpdated = true;
17262                }
17263            }
17264            if (!childPackageUpdated) {
17265                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17266                childRemovedRes.removedPackage = childPkg.packageName;
17267                if (childPs != null) {
17268                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17269                }
17270                childRemovedRes.isUpdate = false;
17271                childRemovedRes.dataRemoved = true;
17272                synchronized (mPackages) {
17273                    if (childPs != null) {
17274                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17275                    }
17276                }
17277                if (res.removedInfo.removedChildPackages == null) {
17278                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17279                }
17280                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17281            }
17282        }
17283
17284        boolean sysPkg = (isSystemApp(oldPackage));
17285        if (sysPkg) {
17286            // Set the system/privileged flags as needed
17287            final boolean privileged =
17288                    (oldPackage.applicationInfo.privateFlags
17289                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17290            final int systemPolicyFlags = policyFlags
17291                    | PackageParser.PARSE_IS_SYSTEM
17292                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17293
17294            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17295                    user, allUsers, installerPackageName, res, installReason);
17296        } else {
17297            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17298                    user, allUsers, installerPackageName, res, installReason);
17299        }
17300    }
17301
17302    @Override
17303    public List<String> getPreviousCodePaths(String packageName) {
17304        final int callingUid = Binder.getCallingUid();
17305        final List<String> result = new ArrayList<>();
17306        if (getInstantAppPackageName(callingUid) != null) {
17307            return result;
17308        }
17309        final PackageSetting ps = mSettings.mPackages.get(packageName);
17310        if (ps != null
17311                && ps.oldCodePaths != null
17312                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17313            result.addAll(ps.oldCodePaths);
17314        }
17315        return result;
17316    }
17317
17318    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17319            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17320            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17321            int installReason) {
17322        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17323                + deletedPackage);
17324
17325        String pkgName = deletedPackage.packageName;
17326        boolean deletedPkg = true;
17327        boolean addedPkg = false;
17328        boolean updatedSettings = false;
17329        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17330        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17331                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17332
17333        final long origUpdateTime = (pkg.mExtras != null)
17334                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17335
17336        // First delete the existing package while retaining the data directory
17337        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17338                res.removedInfo, true, pkg)) {
17339            // If the existing package wasn't successfully deleted
17340            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17341            deletedPkg = false;
17342        } else {
17343            // Successfully deleted the old package; proceed with replace.
17344
17345            // If deleted package lived in a container, give users a chance to
17346            // relinquish resources before killing.
17347            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17348                if (DEBUG_INSTALL) {
17349                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17350                }
17351                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17352                final ArrayList<String> pkgList = new ArrayList<String>(1);
17353                pkgList.add(deletedPackage.applicationInfo.packageName);
17354                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17355            }
17356
17357            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17358                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17359            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17360
17361            try {
17362                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17363                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17364                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17365                        installReason);
17366
17367                // Update the in-memory copy of the previous code paths.
17368                PackageSetting ps = mSettings.mPackages.get(pkgName);
17369                if (!killApp) {
17370                    if (ps.oldCodePaths == null) {
17371                        ps.oldCodePaths = new ArraySet<>();
17372                    }
17373                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17374                    if (deletedPackage.splitCodePaths != null) {
17375                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17376                    }
17377                } else {
17378                    ps.oldCodePaths = null;
17379                }
17380                if (ps.childPackageNames != null) {
17381                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17382                        final String childPkgName = ps.childPackageNames.get(i);
17383                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17384                        childPs.oldCodePaths = ps.oldCodePaths;
17385                    }
17386                }
17387                // set instant app status, but, only if it's explicitly specified
17388                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17389                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17390                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17391                prepareAppDataAfterInstallLIF(newPackage);
17392                addedPkg = true;
17393                mDexManager.notifyPackageUpdated(newPackage.packageName,
17394                        newPackage.baseCodePath, newPackage.splitCodePaths);
17395            } catch (PackageManagerException e) {
17396                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17397            }
17398        }
17399
17400        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17401            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17402
17403            // Revert all internal state mutations and added folders for the failed install
17404            if (addedPkg) {
17405                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17406                        res.removedInfo, true, null);
17407            }
17408
17409            // Restore the old package
17410            if (deletedPkg) {
17411                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17412                File restoreFile = new File(deletedPackage.codePath);
17413                // Parse old package
17414                boolean oldExternal = isExternal(deletedPackage);
17415                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17416                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17417                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17418                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17419                try {
17420                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17421                            null);
17422                } catch (PackageManagerException e) {
17423                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17424                            + e.getMessage());
17425                    return;
17426                }
17427
17428                synchronized (mPackages) {
17429                    // Ensure the installer package name up to date
17430                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17431
17432                    // Update permissions for restored package
17433                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17434
17435                    mSettings.writeLPr();
17436                }
17437
17438                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17439            }
17440        } else {
17441            synchronized (mPackages) {
17442                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17443                if (ps != null) {
17444                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17445                    if (res.removedInfo.removedChildPackages != null) {
17446                        final int childCount = res.removedInfo.removedChildPackages.size();
17447                        // Iterate in reverse as we may modify the collection
17448                        for (int i = childCount - 1; i >= 0; i--) {
17449                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17450                            if (res.addedChildPackages.containsKey(childPackageName)) {
17451                                res.removedInfo.removedChildPackages.removeAt(i);
17452                            } else {
17453                                PackageRemovedInfo childInfo = res.removedInfo
17454                                        .removedChildPackages.valueAt(i);
17455                                childInfo.removedForAllUsers = mPackages.get(
17456                                        childInfo.removedPackage) == null;
17457                            }
17458                        }
17459                    }
17460                }
17461            }
17462        }
17463    }
17464
17465    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17466            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17467            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17468            int installReason) {
17469        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17470                + ", old=" + deletedPackage);
17471
17472        final boolean disabledSystem;
17473
17474        // Remove existing system package
17475        removePackageLI(deletedPackage, true);
17476
17477        synchronized (mPackages) {
17478            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17479        }
17480        if (!disabledSystem) {
17481            // We didn't need to disable the .apk as a current system package,
17482            // which means we are replacing another update that is already
17483            // installed.  We need to make sure to delete the older one's .apk.
17484            res.removedInfo.args = createInstallArgsForExisting(0,
17485                    deletedPackage.applicationInfo.getCodePath(),
17486                    deletedPackage.applicationInfo.getResourcePath(),
17487                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17488        } else {
17489            res.removedInfo.args = null;
17490        }
17491
17492        // Successfully disabled the old package. Now proceed with re-installation
17493        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17494                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17495        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17496
17497        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17498        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17499                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17500
17501        PackageParser.Package newPackage = null;
17502        try {
17503            // Add the package to the internal data structures
17504            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17505
17506            // Set the update and install times
17507            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17508            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17509                    System.currentTimeMillis());
17510
17511            // Update the package dynamic state if succeeded
17512            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17513                // Now that the install succeeded make sure we remove data
17514                // directories for any child package the update removed.
17515                final int deletedChildCount = (deletedPackage.childPackages != null)
17516                        ? deletedPackage.childPackages.size() : 0;
17517                final int newChildCount = (newPackage.childPackages != null)
17518                        ? newPackage.childPackages.size() : 0;
17519                for (int i = 0; i < deletedChildCount; i++) {
17520                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17521                    boolean childPackageDeleted = true;
17522                    for (int j = 0; j < newChildCount; j++) {
17523                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17524                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17525                            childPackageDeleted = false;
17526                            break;
17527                        }
17528                    }
17529                    if (childPackageDeleted) {
17530                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17531                                deletedChildPkg.packageName);
17532                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17533                            PackageRemovedInfo removedChildRes = res.removedInfo
17534                                    .removedChildPackages.get(deletedChildPkg.packageName);
17535                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17536                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17537                        }
17538                    }
17539                }
17540
17541                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17542                        installReason);
17543                prepareAppDataAfterInstallLIF(newPackage);
17544
17545                mDexManager.notifyPackageUpdated(newPackage.packageName,
17546                            newPackage.baseCodePath, newPackage.splitCodePaths);
17547            }
17548        } catch (PackageManagerException e) {
17549            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17550            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17551        }
17552
17553        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17554            // Re installation failed. Restore old information
17555            // Remove new pkg information
17556            if (newPackage != null) {
17557                removeInstalledPackageLI(newPackage, true);
17558            }
17559            // Add back the old system package
17560            try {
17561                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17562            } catch (PackageManagerException e) {
17563                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17564            }
17565
17566            synchronized (mPackages) {
17567                if (disabledSystem) {
17568                    enableSystemPackageLPw(deletedPackage);
17569                }
17570
17571                // Ensure the installer package name up to date
17572                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17573
17574                // Update permissions for restored package
17575                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17576
17577                mSettings.writeLPr();
17578            }
17579
17580            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17581                    + " after failed upgrade");
17582        }
17583    }
17584
17585    /**
17586     * Checks whether the parent or any of the child packages have a change shared
17587     * user. For a package to be a valid update the shred users of the parent and
17588     * the children should match. We may later support changing child shared users.
17589     * @param oldPkg The updated package.
17590     * @param newPkg The update package.
17591     * @return The shared user that change between the versions.
17592     */
17593    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17594            PackageParser.Package newPkg) {
17595        // Check parent shared user
17596        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17597            return newPkg.packageName;
17598        }
17599        // Check child shared users
17600        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17601        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17602        for (int i = 0; i < newChildCount; i++) {
17603            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17604            // If this child was present, did it have the same shared user?
17605            for (int j = 0; j < oldChildCount; j++) {
17606                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17607                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17608                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17609                    return newChildPkg.packageName;
17610                }
17611            }
17612        }
17613        return null;
17614    }
17615
17616    private void removeNativeBinariesLI(PackageSetting ps) {
17617        // Remove the lib path for the parent package
17618        if (ps != null) {
17619            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17620            // Remove the lib path for the child packages
17621            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17622            for (int i = 0; i < childCount; i++) {
17623                PackageSetting childPs = null;
17624                synchronized (mPackages) {
17625                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17626                }
17627                if (childPs != null) {
17628                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17629                            .legacyNativeLibraryPathString);
17630                }
17631            }
17632        }
17633    }
17634
17635    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17636        // Enable the parent package
17637        mSettings.enableSystemPackageLPw(pkg.packageName);
17638        // Enable the child packages
17639        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17640        for (int i = 0; i < childCount; i++) {
17641            PackageParser.Package childPkg = pkg.childPackages.get(i);
17642            mSettings.enableSystemPackageLPw(childPkg.packageName);
17643        }
17644    }
17645
17646    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17647            PackageParser.Package newPkg) {
17648        // Disable the parent package (parent always replaced)
17649        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17650        // Disable the child packages
17651        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17652        for (int i = 0; i < childCount; i++) {
17653            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17654            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17655            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17656        }
17657        return disabled;
17658    }
17659
17660    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17661            String installerPackageName) {
17662        // Enable the parent package
17663        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17664        // Enable the child packages
17665        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17666        for (int i = 0; i < childCount; i++) {
17667            PackageParser.Package childPkg = pkg.childPackages.get(i);
17668            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17669        }
17670    }
17671
17672    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17673        // Collect all used permissions in the UID
17674        ArraySet<String> usedPermissions = new ArraySet<>();
17675        final int packageCount = su.packages.size();
17676        for (int i = 0; i < packageCount; i++) {
17677            PackageSetting ps = su.packages.valueAt(i);
17678            if (ps.pkg == null) {
17679                continue;
17680            }
17681            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17682            for (int j = 0; j < requestedPermCount; j++) {
17683                String permission = ps.pkg.requestedPermissions.get(j);
17684                BasePermission bp = mSettings.mPermissions.get(permission);
17685                if (bp != null) {
17686                    usedPermissions.add(permission);
17687                }
17688            }
17689        }
17690
17691        PermissionsState permissionsState = su.getPermissionsState();
17692        // Prune install permissions
17693        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17694        final int installPermCount = installPermStates.size();
17695        for (int i = installPermCount - 1; i >= 0;  i--) {
17696            PermissionState permissionState = installPermStates.get(i);
17697            if (!usedPermissions.contains(permissionState.getName())) {
17698                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17699                if (bp != null) {
17700                    permissionsState.revokeInstallPermission(bp);
17701                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17702                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17703                }
17704            }
17705        }
17706
17707        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17708
17709        // Prune runtime permissions
17710        for (int userId : allUserIds) {
17711            List<PermissionState> runtimePermStates = permissionsState
17712                    .getRuntimePermissionStates(userId);
17713            final int runtimePermCount = runtimePermStates.size();
17714            for (int i = runtimePermCount - 1; i >= 0; i--) {
17715                PermissionState permissionState = runtimePermStates.get(i);
17716                if (!usedPermissions.contains(permissionState.getName())) {
17717                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17718                    if (bp != null) {
17719                        permissionsState.revokeRuntimePermission(bp, userId);
17720                        permissionsState.updatePermissionFlags(bp, userId,
17721                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17722                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17723                                runtimePermissionChangedUserIds, userId);
17724                    }
17725                }
17726            }
17727        }
17728
17729        return runtimePermissionChangedUserIds;
17730    }
17731
17732    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17733            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17734        // Update the parent package setting
17735        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17736                res, user, installReason);
17737        // Update the child packages setting
17738        final int childCount = (newPackage.childPackages != null)
17739                ? newPackage.childPackages.size() : 0;
17740        for (int i = 0; i < childCount; i++) {
17741            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17742            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17743            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17744                    childRes.origUsers, childRes, user, installReason);
17745        }
17746    }
17747
17748    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17749            String installerPackageName, int[] allUsers, int[] installedForUsers,
17750            PackageInstalledInfo res, UserHandle user, int installReason) {
17751        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17752
17753        String pkgName = newPackage.packageName;
17754        synchronized (mPackages) {
17755            //write settings. the installStatus will be incomplete at this stage.
17756            //note that the new package setting would have already been
17757            //added to mPackages. It hasn't been persisted yet.
17758            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17759            // TODO: Remove this write? It's also written at the end of this method
17760            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17761            mSettings.writeLPr();
17762            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17763        }
17764
17765        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17766        synchronized (mPackages) {
17767            updatePermissionsLPw(newPackage.packageName, newPackage,
17768                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17769                            ? UPDATE_PERMISSIONS_ALL : 0));
17770            // For system-bundled packages, we assume that installing an upgraded version
17771            // of the package implies that the user actually wants to run that new code,
17772            // so we enable the package.
17773            PackageSetting ps = mSettings.mPackages.get(pkgName);
17774            final int userId = user.getIdentifier();
17775            if (ps != null) {
17776                if (isSystemApp(newPackage)) {
17777                    if (DEBUG_INSTALL) {
17778                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17779                    }
17780                    // Enable system package for requested users
17781                    if (res.origUsers != null) {
17782                        for (int origUserId : res.origUsers) {
17783                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17784                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17785                                        origUserId, installerPackageName);
17786                            }
17787                        }
17788                    }
17789                    // Also convey the prior install/uninstall state
17790                    if (allUsers != null && installedForUsers != null) {
17791                        for (int currentUserId : allUsers) {
17792                            final boolean installed = ArrayUtils.contains(
17793                                    installedForUsers, currentUserId);
17794                            if (DEBUG_INSTALL) {
17795                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17796                            }
17797                            ps.setInstalled(installed, currentUserId);
17798                        }
17799                        // these install state changes will be persisted in the
17800                        // upcoming call to mSettings.writeLPr().
17801                    }
17802                }
17803                // It's implied that when a user requests installation, they want the app to be
17804                // installed and enabled.
17805                if (userId != UserHandle.USER_ALL) {
17806                    ps.setInstalled(true, userId);
17807                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17808                }
17809
17810                // When replacing an existing package, preserve the original install reason for all
17811                // users that had the package installed before.
17812                final Set<Integer> previousUserIds = new ArraySet<>();
17813                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17814                    final int installReasonCount = res.removedInfo.installReasons.size();
17815                    for (int i = 0; i < installReasonCount; i++) {
17816                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17817                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17818                        ps.setInstallReason(previousInstallReason, previousUserId);
17819                        previousUserIds.add(previousUserId);
17820                    }
17821                }
17822
17823                // Set install reason for users that are having the package newly installed.
17824                if (userId == UserHandle.USER_ALL) {
17825                    for (int currentUserId : sUserManager.getUserIds()) {
17826                        if (!previousUserIds.contains(currentUserId)) {
17827                            ps.setInstallReason(installReason, currentUserId);
17828                        }
17829                    }
17830                } else if (!previousUserIds.contains(userId)) {
17831                    ps.setInstallReason(installReason, userId);
17832                }
17833                mSettings.writeKernelMappingLPr(ps);
17834            }
17835            res.name = pkgName;
17836            res.uid = newPackage.applicationInfo.uid;
17837            res.pkg = newPackage;
17838            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17839            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17840            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17841            //to update install status
17842            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17843            mSettings.writeLPr();
17844            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17845        }
17846
17847        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17848    }
17849
17850    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17851        try {
17852            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17853            installPackageLI(args, res);
17854        } finally {
17855            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17856        }
17857    }
17858
17859    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17860        final int installFlags = args.installFlags;
17861        final String installerPackageName = args.installerPackageName;
17862        final String volumeUuid = args.volumeUuid;
17863        final File tmpPackageFile = new File(args.getCodePath());
17864        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17865        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17866                || (args.volumeUuid != null));
17867        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17868        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17869        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17870        boolean replace = false;
17871        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17872        if (args.move != null) {
17873            // moving a complete application; perform an initial scan on the new install location
17874            scanFlags |= SCAN_INITIAL;
17875        }
17876        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17877            scanFlags |= SCAN_DONT_KILL_APP;
17878        }
17879        if (instantApp) {
17880            scanFlags |= SCAN_AS_INSTANT_APP;
17881        }
17882        if (fullApp) {
17883            scanFlags |= SCAN_AS_FULL_APP;
17884        }
17885
17886        // Result object to be returned
17887        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17888
17889        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17890
17891        // Sanity check
17892        if (instantApp && (forwardLocked || onExternal)) {
17893            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17894                    + " external=" + onExternal);
17895            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17896            return;
17897        }
17898
17899        // Retrieve PackageSettings and parse package
17900        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17901                | PackageParser.PARSE_ENFORCE_CODE
17902                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17903                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17904                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17905                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17906        PackageParser pp = new PackageParser();
17907        pp.setSeparateProcesses(mSeparateProcesses);
17908        pp.setDisplayMetrics(mMetrics);
17909        pp.setCallback(mPackageParserCallback);
17910
17911        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17912        final PackageParser.Package pkg;
17913        try {
17914            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17915        } catch (PackageParserException e) {
17916            res.setError("Failed parse during installPackageLI", e);
17917            return;
17918        } finally {
17919            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17920        }
17921
17922        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17923        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17924            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17925            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17926                    "Instant app package must target O");
17927            return;
17928        }
17929        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17930            Slog.w(TAG, "Instant app package " + pkg.packageName
17931                    + " does not target targetSandboxVersion 2");
17932            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17933                    "Instant app package must use targetSanboxVersion 2");
17934            return;
17935        }
17936
17937        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17938            // Static shared libraries have synthetic package names
17939            renameStaticSharedLibraryPackage(pkg);
17940
17941            // No static shared libs on external storage
17942            if (onExternal) {
17943                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17944                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17945                        "Packages declaring static-shared libs cannot be updated");
17946                return;
17947            }
17948        }
17949
17950        // If we are installing a clustered package add results for the children
17951        if (pkg.childPackages != null) {
17952            synchronized (mPackages) {
17953                final int childCount = pkg.childPackages.size();
17954                for (int i = 0; i < childCount; i++) {
17955                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17956                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17957                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17958                    childRes.pkg = childPkg;
17959                    childRes.name = childPkg.packageName;
17960                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17961                    if (childPs != null) {
17962                        childRes.origUsers = childPs.queryInstalledUsers(
17963                                sUserManager.getUserIds(), true);
17964                    }
17965                    if ((mPackages.containsKey(childPkg.packageName))) {
17966                        childRes.removedInfo = new PackageRemovedInfo(this);
17967                        childRes.removedInfo.removedPackage = childPkg.packageName;
17968                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17969                    }
17970                    if (res.addedChildPackages == null) {
17971                        res.addedChildPackages = new ArrayMap<>();
17972                    }
17973                    res.addedChildPackages.put(childPkg.packageName, childRes);
17974                }
17975            }
17976        }
17977
17978        // If package doesn't declare API override, mark that we have an install
17979        // time CPU ABI override.
17980        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17981            pkg.cpuAbiOverride = args.abiOverride;
17982        }
17983
17984        String pkgName = res.name = pkg.packageName;
17985        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17986            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17987                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17988                return;
17989            }
17990        }
17991
17992        try {
17993            // either use what we've been given or parse directly from the APK
17994            if (args.certificates != null) {
17995                try {
17996                    PackageParser.populateCertificates(pkg, args.certificates);
17997                } catch (PackageParserException e) {
17998                    // there was something wrong with the certificates we were given;
17999                    // try to pull them from the APK
18000                    PackageParser.collectCertificates(pkg, parseFlags);
18001                }
18002            } else {
18003                PackageParser.collectCertificates(pkg, parseFlags);
18004            }
18005        } catch (PackageParserException e) {
18006            res.setError("Failed collect during installPackageLI", e);
18007            return;
18008        }
18009
18010        // Get rid of all references to package scan path via parser.
18011        pp = null;
18012        String oldCodePath = null;
18013        boolean systemApp = false;
18014        synchronized (mPackages) {
18015            // Check if installing already existing package
18016            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18017                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18018                if (pkg.mOriginalPackages != null
18019                        && pkg.mOriginalPackages.contains(oldName)
18020                        && mPackages.containsKey(oldName)) {
18021                    // This package is derived from an original package,
18022                    // and this device has been updating from that original
18023                    // name.  We must continue using the original name, so
18024                    // rename the new package here.
18025                    pkg.setPackageName(oldName);
18026                    pkgName = pkg.packageName;
18027                    replace = true;
18028                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18029                            + oldName + " pkgName=" + pkgName);
18030                } else if (mPackages.containsKey(pkgName)) {
18031                    // This package, under its official name, already exists
18032                    // on the device; we should replace it.
18033                    replace = true;
18034                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18035                }
18036
18037                // Child packages are installed through the parent package
18038                if (pkg.parentPackage != null) {
18039                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18040                            "Package " + pkg.packageName + " is child of package "
18041                                    + pkg.parentPackage.parentPackage + ". Child packages "
18042                                    + "can be updated only through the parent package.");
18043                    return;
18044                }
18045
18046                if (replace) {
18047                    // Prevent apps opting out from runtime permissions
18048                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18049                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18050                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18051                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18052                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18053                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18054                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18055                                        + " doesn't support runtime permissions but the old"
18056                                        + " target SDK " + oldTargetSdk + " does.");
18057                        return;
18058                    }
18059                    // Prevent apps from downgrading their targetSandbox.
18060                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18061                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18062                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18063                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18064                                "Package " + pkg.packageName + " new target sandbox "
18065                                + newTargetSandbox + " is incompatible with the previous value of"
18066                                + oldTargetSandbox + ".");
18067                        return;
18068                    }
18069
18070                    // Prevent installing of child packages
18071                    if (oldPackage.parentPackage != null) {
18072                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18073                                "Package " + pkg.packageName + " is child of package "
18074                                        + oldPackage.parentPackage + ". Child packages "
18075                                        + "can be updated only through the parent package.");
18076                        return;
18077                    }
18078                }
18079            }
18080
18081            PackageSetting ps = mSettings.mPackages.get(pkgName);
18082            if (ps != null) {
18083                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18084
18085                // Static shared libs have same package with different versions where
18086                // we internally use a synthetic package name to allow multiple versions
18087                // of the same package, therefore we need to compare signatures against
18088                // the package setting for the latest library version.
18089                PackageSetting signatureCheckPs = ps;
18090                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18091                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18092                    if (libraryEntry != null) {
18093                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18094                    }
18095                }
18096
18097                // Quick sanity check that we're signed correctly if updating;
18098                // we'll check this again later when scanning, but we want to
18099                // bail early here before tripping over redefined permissions.
18100                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18101                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18102                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18103                                + pkg.packageName + " upgrade keys do not match the "
18104                                + "previously installed version");
18105                        return;
18106                    }
18107                } else {
18108                    try {
18109                        verifySignaturesLP(signatureCheckPs, pkg);
18110                    } catch (PackageManagerException e) {
18111                        res.setError(e.error, e.getMessage());
18112                        return;
18113                    }
18114                }
18115
18116                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18117                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18118                    systemApp = (ps.pkg.applicationInfo.flags &
18119                            ApplicationInfo.FLAG_SYSTEM) != 0;
18120                }
18121                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18122            }
18123
18124            int N = pkg.permissions.size();
18125            for (int i = N-1; i >= 0; i--) {
18126                PackageParser.Permission perm = pkg.permissions.get(i);
18127                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18128
18129                // Don't allow anyone but the system to define ephemeral permissions.
18130                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18131                        && !systemApp) {
18132                    Slog.w(TAG, "Non-System package " + pkg.packageName
18133                            + " attempting to delcare ephemeral permission "
18134                            + perm.info.name + "; Removing ephemeral.");
18135                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18136                }
18137                // Check whether the newly-scanned package wants to define an already-defined perm
18138                if (bp != null) {
18139                    // If the defining package is signed with our cert, it's okay.  This
18140                    // also includes the "updating the same package" case, of course.
18141                    // "updating same package" could also involve key-rotation.
18142                    final boolean sigsOk;
18143                    if (bp.sourcePackage.equals(pkg.packageName)
18144                            && (bp.packageSetting instanceof PackageSetting)
18145                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18146                                    scanFlags))) {
18147                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18148                    } else {
18149                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18150                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18151                    }
18152                    if (!sigsOk) {
18153                        // If the owning package is the system itself, we log but allow
18154                        // install to proceed; we fail the install on all other permission
18155                        // redefinitions.
18156                        if (!bp.sourcePackage.equals("android")) {
18157                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18158                                    + pkg.packageName + " attempting to redeclare permission "
18159                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18160                            res.origPermission = perm.info.name;
18161                            res.origPackage = bp.sourcePackage;
18162                            return;
18163                        } else {
18164                            Slog.w(TAG, "Package " + pkg.packageName
18165                                    + " attempting to redeclare system permission "
18166                                    + perm.info.name + "; ignoring new declaration");
18167                            pkg.permissions.remove(i);
18168                        }
18169                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18170                        // Prevent apps to change protection level to dangerous from any other
18171                        // type as this would allow a privilege escalation where an app adds a
18172                        // normal/signature permission in other app's group and later redefines
18173                        // it as dangerous leading to the group auto-grant.
18174                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18175                                == PermissionInfo.PROTECTION_DANGEROUS) {
18176                            if (bp != null && !bp.isRuntime()) {
18177                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18178                                        + "non-runtime permission " + perm.info.name
18179                                        + " to runtime; keeping old protection level");
18180                                perm.info.protectionLevel = bp.protectionLevel;
18181                            }
18182                        }
18183                    }
18184                }
18185            }
18186        }
18187
18188        if (systemApp) {
18189            if (onExternal) {
18190                // Abort update; system app can't be replaced with app on sdcard
18191                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18192                        "Cannot install updates to system apps on sdcard");
18193                return;
18194            } else if (instantApp) {
18195                // Abort update; system app can't be replaced with an instant app
18196                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18197                        "Cannot update a system app with an instant app");
18198                return;
18199            }
18200        }
18201
18202        if (args.move != null) {
18203            // We did an in-place move, so dex is ready to roll
18204            scanFlags |= SCAN_NO_DEX;
18205            scanFlags |= SCAN_MOVE;
18206
18207            synchronized (mPackages) {
18208                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18209                if (ps == null) {
18210                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18211                            "Missing settings for moved package " + pkgName);
18212                }
18213
18214                // We moved the entire application as-is, so bring over the
18215                // previously derived ABI information.
18216                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18217                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18218            }
18219
18220        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18221            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18222            scanFlags |= SCAN_NO_DEX;
18223
18224            try {
18225                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18226                    args.abiOverride : pkg.cpuAbiOverride);
18227                final boolean extractNativeLibs = !pkg.isLibrary();
18228                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18229                        extractNativeLibs, mAppLib32InstallDir);
18230            } catch (PackageManagerException pme) {
18231                Slog.e(TAG, "Error deriving application ABI", pme);
18232                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18233                return;
18234            }
18235
18236            // Shared libraries for the package need to be updated.
18237            synchronized (mPackages) {
18238                try {
18239                    updateSharedLibrariesLPr(pkg, null);
18240                } catch (PackageManagerException e) {
18241                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18242                }
18243            }
18244
18245            // dexopt can take some time to complete, so, for instant apps, we skip this
18246            // step during installation. Instead, we'll take extra time the first time the
18247            // instant app starts. It's preferred to do it this way to provide continuous
18248            // progress to the user instead of mysteriously blocking somewhere in the
18249            // middle of running an instant app. The default behaviour can be overridden
18250            // via gservices.
18251            if (!instantApp || Global.getInt(
18252                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18253                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18254                // Do not run PackageDexOptimizer through the local performDexOpt
18255                // method because `pkg` may not be in `mPackages` yet.
18256                //
18257                // Also, don't fail application installs if the dexopt step fails.
18258                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18259                        null /* instructionSets */, false /* checkProfiles */,
18260                        getCompilerFilterForReason(REASON_INSTALL),
18261                        getOrCreateCompilerPackageStats(pkg),
18262                        mDexManager.isUsedByOtherApps(pkg.packageName),
18263                        true /* bootComplete */,
18264                        false /* downgrade */);
18265                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18266            }
18267
18268            // Notify BackgroundDexOptService that the package has been changed.
18269            // If this is an update of a package which used to fail to compile,
18270            // BDOS will remove it from its blacklist.
18271            // TODO: Layering violation
18272            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18273        }
18274
18275        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18276            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18277            return;
18278        }
18279
18280        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18281
18282        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18283                "installPackageLI")) {
18284            if (replace) {
18285                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18286                    // Static libs have a synthetic package name containing the version
18287                    // and cannot be updated as an update would get a new package name,
18288                    // unless this is the exact same version code which is useful for
18289                    // development.
18290                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18291                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18292                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18293                                + "static-shared libs cannot be updated");
18294                        return;
18295                    }
18296                }
18297                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18298                        installerPackageName, res, args.installReason);
18299            } else {
18300                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18301                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18302            }
18303        }
18304
18305        synchronized (mPackages) {
18306            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18307            if (ps != null) {
18308                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18309                ps.setUpdateAvailable(false /*updateAvailable*/);
18310            }
18311
18312            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18313            for (int i = 0; i < childCount; i++) {
18314                PackageParser.Package childPkg = pkg.childPackages.get(i);
18315                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18316                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18317                if (childPs != null) {
18318                    childRes.newUsers = childPs.queryInstalledUsers(
18319                            sUserManager.getUserIds(), true);
18320                }
18321            }
18322
18323            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18324                updateSequenceNumberLP(ps, res.newUsers);
18325                updateInstantAppInstallerLocked(pkgName);
18326            }
18327        }
18328    }
18329
18330    private void startIntentFilterVerifications(int userId, boolean replacing,
18331            PackageParser.Package pkg) {
18332        if (mIntentFilterVerifierComponent == null) {
18333            Slog.w(TAG, "No IntentFilter verification will not be done as "
18334                    + "there is no IntentFilterVerifier available!");
18335            return;
18336        }
18337
18338        final int verifierUid = getPackageUid(
18339                mIntentFilterVerifierComponent.getPackageName(),
18340                MATCH_DEBUG_TRIAGED_MISSING,
18341                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18342
18343        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18344        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18345        mHandler.sendMessage(msg);
18346
18347        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18348        for (int i = 0; i < childCount; i++) {
18349            PackageParser.Package childPkg = pkg.childPackages.get(i);
18350            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18351            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18352            mHandler.sendMessage(msg);
18353        }
18354    }
18355
18356    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18357            PackageParser.Package pkg) {
18358        int size = pkg.activities.size();
18359        if (size == 0) {
18360            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18361                    "No activity, so no need to verify any IntentFilter!");
18362            return;
18363        }
18364
18365        final boolean hasDomainURLs = hasDomainURLs(pkg);
18366        if (!hasDomainURLs) {
18367            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18368                    "No domain URLs, so no need to verify any IntentFilter!");
18369            return;
18370        }
18371
18372        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18373                + " if any IntentFilter from the " + size
18374                + " Activities needs verification ...");
18375
18376        int count = 0;
18377        final String packageName = pkg.packageName;
18378
18379        synchronized (mPackages) {
18380            // If this is a new install and we see that we've already run verification for this
18381            // package, we have nothing to do: it means the state was restored from backup.
18382            if (!replacing) {
18383                IntentFilterVerificationInfo ivi =
18384                        mSettings.getIntentFilterVerificationLPr(packageName);
18385                if (ivi != null) {
18386                    if (DEBUG_DOMAIN_VERIFICATION) {
18387                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18388                                + ivi.getStatusString());
18389                    }
18390                    return;
18391                }
18392            }
18393
18394            // If any filters need to be verified, then all need to be.
18395            boolean needToVerify = false;
18396            for (PackageParser.Activity a : pkg.activities) {
18397                for (ActivityIntentInfo filter : a.intents) {
18398                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18399                        if (DEBUG_DOMAIN_VERIFICATION) {
18400                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18401                        }
18402                        needToVerify = true;
18403                        break;
18404                    }
18405                }
18406            }
18407
18408            if (needToVerify) {
18409                final int verificationId = mIntentFilterVerificationToken++;
18410                for (PackageParser.Activity a : pkg.activities) {
18411                    for (ActivityIntentInfo filter : a.intents) {
18412                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18413                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18414                                    "Verification needed for IntentFilter:" + filter.toString());
18415                            mIntentFilterVerifier.addOneIntentFilterVerification(
18416                                    verifierUid, userId, verificationId, filter, packageName);
18417                            count++;
18418                        }
18419                    }
18420                }
18421            }
18422        }
18423
18424        if (count > 0) {
18425            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18426                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18427                    +  " for userId:" + userId);
18428            mIntentFilterVerifier.startVerifications(userId);
18429        } else {
18430            if (DEBUG_DOMAIN_VERIFICATION) {
18431                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18432            }
18433        }
18434    }
18435
18436    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18437        final ComponentName cn  = filter.activity.getComponentName();
18438        final String packageName = cn.getPackageName();
18439
18440        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18441                packageName);
18442        if (ivi == null) {
18443            return true;
18444        }
18445        int status = ivi.getStatus();
18446        switch (status) {
18447            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18448            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18449                return true;
18450
18451            default:
18452                // Nothing to do
18453                return false;
18454        }
18455    }
18456
18457    private static boolean isMultiArch(ApplicationInfo info) {
18458        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18459    }
18460
18461    private static boolean isExternal(PackageParser.Package pkg) {
18462        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18463    }
18464
18465    private static boolean isExternal(PackageSetting ps) {
18466        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18467    }
18468
18469    private static boolean isSystemApp(PackageParser.Package pkg) {
18470        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18471    }
18472
18473    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18474        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18475    }
18476
18477    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18478        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18479    }
18480
18481    private static boolean isSystemApp(PackageSetting ps) {
18482        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18483    }
18484
18485    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18486        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18487    }
18488
18489    private int packageFlagsToInstallFlags(PackageSetting ps) {
18490        int installFlags = 0;
18491        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18492            // This existing package was an external ASEC install when we have
18493            // the external flag without a UUID
18494            installFlags |= PackageManager.INSTALL_EXTERNAL;
18495        }
18496        if (ps.isForwardLocked()) {
18497            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18498        }
18499        return installFlags;
18500    }
18501
18502    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18503        if (isExternal(pkg)) {
18504            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18505                return StorageManager.UUID_PRIMARY_PHYSICAL;
18506            } else {
18507                return pkg.volumeUuid;
18508            }
18509        } else {
18510            return StorageManager.UUID_PRIVATE_INTERNAL;
18511        }
18512    }
18513
18514    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18515        if (isExternal(pkg)) {
18516            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18517                return mSettings.getExternalVersion();
18518            } else {
18519                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18520            }
18521        } else {
18522            return mSettings.getInternalVersion();
18523        }
18524    }
18525
18526    private void deleteTempPackageFiles() {
18527        final FilenameFilter filter = new FilenameFilter() {
18528            public boolean accept(File dir, String name) {
18529                return name.startsWith("vmdl") && name.endsWith(".tmp");
18530            }
18531        };
18532        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18533            file.delete();
18534        }
18535    }
18536
18537    @Override
18538    public void deletePackageAsUser(String packageName, int versionCode,
18539            IPackageDeleteObserver observer, int userId, int flags) {
18540        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18541                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18542    }
18543
18544    @Override
18545    public void deletePackageVersioned(VersionedPackage versionedPackage,
18546            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18547        final int callingUid = Binder.getCallingUid();
18548        mContext.enforceCallingOrSelfPermission(
18549                android.Manifest.permission.DELETE_PACKAGES, null);
18550        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18551        Preconditions.checkNotNull(versionedPackage);
18552        Preconditions.checkNotNull(observer);
18553        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18554                PackageManager.VERSION_CODE_HIGHEST,
18555                Integer.MAX_VALUE, "versionCode must be >= -1");
18556
18557        final String packageName = versionedPackage.getPackageName();
18558        final int versionCode = versionedPackage.getVersionCode();
18559        final String internalPackageName;
18560        synchronized (mPackages) {
18561            // Normalize package name to handle renamed packages and static libs
18562            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18563                    versionedPackage.getVersionCode());
18564        }
18565
18566        final int uid = Binder.getCallingUid();
18567        if (!isOrphaned(internalPackageName)
18568                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18569            try {
18570                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18571                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18572                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18573                observer.onUserActionRequired(intent);
18574            } catch (RemoteException re) {
18575            }
18576            return;
18577        }
18578        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18579        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18580        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18581            mContext.enforceCallingOrSelfPermission(
18582                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18583                    "deletePackage for user " + userId);
18584        }
18585
18586        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18587            try {
18588                observer.onPackageDeleted(packageName,
18589                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18590            } catch (RemoteException re) {
18591            }
18592            return;
18593        }
18594
18595        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18596            try {
18597                observer.onPackageDeleted(packageName,
18598                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18599            } catch (RemoteException re) {
18600            }
18601            return;
18602        }
18603
18604        if (DEBUG_REMOVE) {
18605            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18606                    + " deleteAllUsers: " + deleteAllUsers + " version="
18607                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18608                    ? "VERSION_CODE_HIGHEST" : versionCode));
18609        }
18610        // Queue up an async operation since the package deletion may take a little while.
18611        mHandler.post(new Runnable() {
18612            public void run() {
18613                mHandler.removeCallbacks(this);
18614                int returnCode;
18615                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18616                boolean doDeletePackage = true;
18617                if (ps != null) {
18618                    final boolean targetIsInstantApp =
18619                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18620                    doDeletePackage = !targetIsInstantApp
18621                            || canViewInstantApps;
18622                }
18623                if (doDeletePackage) {
18624                    if (!deleteAllUsers) {
18625                        returnCode = deletePackageX(internalPackageName, versionCode,
18626                                userId, deleteFlags);
18627                    } else {
18628                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18629                                internalPackageName, users);
18630                        // If nobody is blocking uninstall, proceed with delete for all users
18631                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18632                            returnCode = deletePackageX(internalPackageName, versionCode,
18633                                    userId, deleteFlags);
18634                        } else {
18635                            // Otherwise uninstall individually for users with blockUninstalls=false
18636                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18637                            for (int userId : users) {
18638                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18639                                    returnCode = deletePackageX(internalPackageName, versionCode,
18640                                            userId, userFlags);
18641                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18642                                        Slog.w(TAG, "Package delete failed for user " + userId
18643                                                + ", returnCode " + returnCode);
18644                                    }
18645                                }
18646                            }
18647                            // The app has only been marked uninstalled for certain users.
18648                            // We still need to report that delete was blocked
18649                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18650                        }
18651                    }
18652                } else {
18653                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18654                }
18655                try {
18656                    observer.onPackageDeleted(packageName, returnCode, null);
18657                } catch (RemoteException e) {
18658                    Log.i(TAG, "Observer no longer exists.");
18659                } //end catch
18660            } //end run
18661        });
18662    }
18663
18664    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18665        if (pkg.staticSharedLibName != null) {
18666            return pkg.manifestPackageName;
18667        }
18668        return pkg.packageName;
18669    }
18670
18671    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18672        // Handle renamed packages
18673        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18674        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18675
18676        // Is this a static library?
18677        SparseArray<SharedLibraryEntry> versionedLib =
18678                mStaticLibsByDeclaringPackage.get(packageName);
18679        if (versionedLib == null || versionedLib.size() <= 0) {
18680            return packageName;
18681        }
18682
18683        // Figure out which lib versions the caller can see
18684        SparseIntArray versionsCallerCanSee = null;
18685        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18686        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18687                && callingAppId != Process.ROOT_UID) {
18688            versionsCallerCanSee = new SparseIntArray();
18689            String libName = versionedLib.valueAt(0).info.getName();
18690            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18691            if (uidPackages != null) {
18692                for (String uidPackage : uidPackages) {
18693                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18694                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18695                    if (libIdx >= 0) {
18696                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18697                        versionsCallerCanSee.append(libVersion, libVersion);
18698                    }
18699                }
18700            }
18701        }
18702
18703        // Caller can see nothing - done
18704        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18705            return packageName;
18706        }
18707
18708        // Find the version the caller can see and the app version code
18709        SharedLibraryEntry highestVersion = null;
18710        final int versionCount = versionedLib.size();
18711        for (int i = 0; i < versionCount; i++) {
18712            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18713            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18714                    libEntry.info.getVersion()) < 0) {
18715                continue;
18716            }
18717            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18718            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18719                if (libVersionCode == versionCode) {
18720                    return libEntry.apk;
18721                }
18722            } else if (highestVersion == null) {
18723                highestVersion = libEntry;
18724            } else if (libVersionCode  > highestVersion.info
18725                    .getDeclaringPackage().getVersionCode()) {
18726                highestVersion = libEntry;
18727            }
18728        }
18729
18730        if (highestVersion != null) {
18731            return highestVersion.apk;
18732        }
18733
18734        return packageName;
18735    }
18736
18737    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18738        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18739              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18740            return true;
18741        }
18742        final int callingUserId = UserHandle.getUserId(callingUid);
18743        // If the caller installed the pkgName, then allow it to silently uninstall.
18744        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18745            return true;
18746        }
18747
18748        // Allow package verifier to silently uninstall.
18749        if (mRequiredVerifierPackage != null &&
18750                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18751            return true;
18752        }
18753
18754        // Allow package uninstaller to silently uninstall.
18755        if (mRequiredUninstallerPackage != null &&
18756                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18757            return true;
18758        }
18759
18760        // Allow storage manager to silently uninstall.
18761        if (mStorageManagerPackage != null &&
18762                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18763            return true;
18764        }
18765
18766        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18767        // uninstall for device owner provisioning.
18768        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18769                == PERMISSION_GRANTED) {
18770            return true;
18771        }
18772
18773        return false;
18774    }
18775
18776    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18777        int[] result = EMPTY_INT_ARRAY;
18778        for (int userId : userIds) {
18779            if (getBlockUninstallForUser(packageName, userId)) {
18780                result = ArrayUtils.appendInt(result, userId);
18781            }
18782        }
18783        return result;
18784    }
18785
18786    @Override
18787    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18788        final int callingUid = Binder.getCallingUid();
18789        if (getInstantAppPackageName(callingUid) != null
18790                && !isCallerSameApp(packageName, callingUid)) {
18791            return false;
18792        }
18793        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18794    }
18795
18796    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18797        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18798                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18799        try {
18800            if (dpm != null) {
18801                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18802                        /* callingUserOnly =*/ false);
18803                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18804                        : deviceOwnerComponentName.getPackageName();
18805                // Does the package contains the device owner?
18806                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18807                // this check is probably not needed, since DO should be registered as a device
18808                // admin on some user too. (Original bug for this: b/17657954)
18809                if (packageName.equals(deviceOwnerPackageName)) {
18810                    return true;
18811                }
18812                // Does it contain a device admin for any user?
18813                int[] users;
18814                if (userId == UserHandle.USER_ALL) {
18815                    users = sUserManager.getUserIds();
18816                } else {
18817                    users = new int[]{userId};
18818                }
18819                for (int i = 0; i < users.length; ++i) {
18820                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18821                        return true;
18822                    }
18823                }
18824            }
18825        } catch (RemoteException e) {
18826        }
18827        return false;
18828    }
18829
18830    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18831        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18832    }
18833
18834    /**
18835     *  This method is an internal method that could be get invoked either
18836     *  to delete an installed package or to clean up a failed installation.
18837     *  After deleting an installed package, a broadcast is sent to notify any
18838     *  listeners that the package has been removed. For cleaning up a failed
18839     *  installation, the broadcast is not necessary since the package's
18840     *  installation wouldn't have sent the initial broadcast either
18841     *  The key steps in deleting a package are
18842     *  deleting the package information in internal structures like mPackages,
18843     *  deleting the packages base directories through installd
18844     *  updating mSettings to reflect current status
18845     *  persisting settings for later use
18846     *  sending a broadcast if necessary
18847     */
18848    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18849        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18850        final boolean res;
18851
18852        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18853                ? UserHandle.USER_ALL : userId;
18854
18855        if (isPackageDeviceAdmin(packageName, removeUser)) {
18856            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18857            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18858        }
18859
18860        PackageSetting uninstalledPs = null;
18861        PackageParser.Package pkg = null;
18862
18863        // for the uninstall-updates case and restricted profiles, remember the per-
18864        // user handle installed state
18865        int[] allUsers;
18866        synchronized (mPackages) {
18867            uninstalledPs = mSettings.mPackages.get(packageName);
18868            if (uninstalledPs == null) {
18869                Slog.w(TAG, "Not removing non-existent package " + packageName);
18870                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18871            }
18872
18873            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18874                    && uninstalledPs.versionCode != versionCode) {
18875                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18876                        + uninstalledPs.versionCode + " != " + versionCode);
18877                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18878            }
18879
18880            // Static shared libs can be declared by any package, so let us not
18881            // allow removing a package if it provides a lib others depend on.
18882            pkg = mPackages.get(packageName);
18883
18884            allUsers = sUserManager.getUserIds();
18885
18886            if (pkg != null && pkg.staticSharedLibName != null) {
18887                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18888                        pkg.staticSharedLibVersion);
18889                if (libEntry != null) {
18890                    for (int currUserId : allUsers) {
18891                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18892                            continue;
18893                        }
18894                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18895                                libEntry.info, 0, currUserId);
18896                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18897                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18898                                    + " hosting lib " + libEntry.info.getName() + " version "
18899                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18900                                    + " for user " + currUserId);
18901                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18902                        }
18903                    }
18904                }
18905            }
18906
18907            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18908        }
18909
18910        final int freezeUser;
18911        if (isUpdatedSystemApp(uninstalledPs)
18912                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18913            // We're downgrading a system app, which will apply to all users, so
18914            // freeze them all during the downgrade
18915            freezeUser = UserHandle.USER_ALL;
18916        } else {
18917            freezeUser = removeUser;
18918        }
18919
18920        synchronized (mInstallLock) {
18921            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18922            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18923                    deleteFlags, "deletePackageX")) {
18924                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18925                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18926            }
18927            synchronized (mPackages) {
18928                if (res) {
18929                    if (pkg != null) {
18930                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18931                    }
18932                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18933                    updateInstantAppInstallerLocked(packageName);
18934                }
18935            }
18936        }
18937
18938        if (res) {
18939            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18940            info.sendPackageRemovedBroadcasts(killApp);
18941            info.sendSystemPackageUpdatedBroadcasts();
18942            info.sendSystemPackageAppearedBroadcasts();
18943        }
18944        // Force a gc here.
18945        Runtime.getRuntime().gc();
18946        // Delete the resources here after sending the broadcast to let
18947        // other processes clean up before deleting resources.
18948        if (info.args != null) {
18949            synchronized (mInstallLock) {
18950                info.args.doPostDeleteLI(true);
18951            }
18952        }
18953
18954        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18955    }
18956
18957    static class PackageRemovedInfo {
18958        final PackageSender packageSender;
18959        String removedPackage;
18960        String installerPackageName;
18961        int uid = -1;
18962        int removedAppId = -1;
18963        int[] origUsers;
18964        int[] removedUsers = null;
18965        int[] broadcastUsers = null;
18966        SparseArray<Integer> installReasons;
18967        boolean isRemovedPackageSystemUpdate = false;
18968        boolean isUpdate;
18969        boolean dataRemoved;
18970        boolean removedForAllUsers;
18971        boolean isStaticSharedLib;
18972        // Clean up resources deleted packages.
18973        InstallArgs args = null;
18974        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18975        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18976
18977        PackageRemovedInfo(PackageSender packageSender) {
18978            this.packageSender = packageSender;
18979        }
18980
18981        void sendPackageRemovedBroadcasts(boolean killApp) {
18982            sendPackageRemovedBroadcastInternal(killApp);
18983            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18984            for (int i = 0; i < childCount; i++) {
18985                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18986                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18987            }
18988        }
18989
18990        void sendSystemPackageUpdatedBroadcasts() {
18991            if (isRemovedPackageSystemUpdate) {
18992                sendSystemPackageUpdatedBroadcastsInternal();
18993                final int childCount = (removedChildPackages != null)
18994                        ? removedChildPackages.size() : 0;
18995                for (int i = 0; i < childCount; i++) {
18996                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18997                    if (childInfo.isRemovedPackageSystemUpdate) {
18998                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18999                    }
19000                }
19001            }
19002        }
19003
19004        void sendSystemPackageAppearedBroadcasts() {
19005            final int packageCount = (appearedChildPackages != null)
19006                    ? appearedChildPackages.size() : 0;
19007            for (int i = 0; i < packageCount; i++) {
19008                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19009                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19010                    true, UserHandle.getAppId(installedInfo.uid),
19011                    installedInfo.newUsers);
19012            }
19013        }
19014
19015        private void sendSystemPackageUpdatedBroadcastsInternal() {
19016            Bundle extras = new Bundle(2);
19017            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19018            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19019            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19020                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19021            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19022                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19023            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19024                null, null, 0, removedPackage, null, null);
19025            if (installerPackageName != null) {
19026                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19027                        removedPackage, extras, 0 /*flags*/,
19028                        installerPackageName, null, null);
19029                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19030                        removedPackage, extras, 0 /*flags*/,
19031                        installerPackageName, null, null);
19032            }
19033        }
19034
19035        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19036            // Don't send static shared library removal broadcasts as these
19037            // libs are visible only the the apps that depend on them an one
19038            // cannot remove the library if it has a dependency.
19039            if (isStaticSharedLib) {
19040                return;
19041            }
19042            Bundle extras = new Bundle(2);
19043            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19044            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19045            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19046            if (isUpdate || isRemovedPackageSystemUpdate) {
19047                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19048            }
19049            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19050            if (removedPackage != null) {
19051                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19052                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19053                if (installerPackageName != null) {
19054                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19055                            removedPackage, extras, 0 /*flags*/,
19056                            installerPackageName, null, broadcastUsers);
19057                }
19058                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19059                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19060                        removedPackage, extras,
19061                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19062                        null, null, broadcastUsers);
19063                }
19064            }
19065            if (removedAppId >= 0) {
19066                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19067                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19068                    null, null, broadcastUsers);
19069            }
19070        }
19071
19072        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19073            removedUsers = userIds;
19074            if (removedUsers == null) {
19075                broadcastUsers = null;
19076                return;
19077            }
19078
19079            broadcastUsers = EMPTY_INT_ARRAY;
19080            for (int i = userIds.length - 1; i >= 0; --i) {
19081                final int userId = userIds[i];
19082                if (deletedPackageSetting.getInstantApp(userId)) {
19083                    continue;
19084                }
19085                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19086            }
19087        }
19088    }
19089
19090    /*
19091     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19092     * flag is not set, the data directory is removed as well.
19093     * make sure this flag is set for partially installed apps. If not its meaningless to
19094     * delete a partially installed application.
19095     */
19096    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19097            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19098        String packageName = ps.name;
19099        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19100        // Retrieve object to delete permissions for shared user later on
19101        final PackageParser.Package deletedPkg;
19102        final PackageSetting deletedPs;
19103        // reader
19104        synchronized (mPackages) {
19105            deletedPkg = mPackages.get(packageName);
19106            deletedPs = mSettings.mPackages.get(packageName);
19107            if (outInfo != null) {
19108                outInfo.removedPackage = packageName;
19109                outInfo.installerPackageName = ps.installerPackageName;
19110                outInfo.isStaticSharedLib = deletedPkg != null
19111                        && deletedPkg.staticSharedLibName != null;
19112                outInfo.populateUsers(deletedPs == null ? null
19113                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19114            }
19115        }
19116
19117        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19118
19119        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19120            final PackageParser.Package resolvedPkg;
19121            if (deletedPkg != null) {
19122                resolvedPkg = deletedPkg;
19123            } else {
19124                // We don't have a parsed package when it lives on an ejected
19125                // adopted storage device, so fake something together
19126                resolvedPkg = new PackageParser.Package(ps.name);
19127                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19128            }
19129            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19130                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19131            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19132            if (outInfo != null) {
19133                outInfo.dataRemoved = true;
19134            }
19135            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19136        }
19137
19138        int removedAppId = -1;
19139
19140        // writer
19141        synchronized (mPackages) {
19142            boolean installedStateChanged = false;
19143            if (deletedPs != null) {
19144                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19145                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19146                    clearDefaultBrowserIfNeeded(packageName);
19147                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19148                    removedAppId = mSettings.removePackageLPw(packageName);
19149                    if (outInfo != null) {
19150                        outInfo.removedAppId = removedAppId;
19151                    }
19152                    updatePermissionsLPw(deletedPs.name, null, 0);
19153                    if (deletedPs.sharedUser != null) {
19154                        // Remove permissions associated with package. Since runtime
19155                        // permissions are per user we have to kill the removed package
19156                        // or packages running under the shared user of the removed
19157                        // package if revoking the permissions requested only by the removed
19158                        // package is successful and this causes a change in gids.
19159                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19160                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19161                                    userId);
19162                            if (userIdToKill == UserHandle.USER_ALL
19163                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19164                                // If gids changed for this user, kill all affected packages.
19165                                mHandler.post(new Runnable() {
19166                                    @Override
19167                                    public void run() {
19168                                        // This has to happen with no lock held.
19169                                        killApplication(deletedPs.name, deletedPs.appId,
19170                                                KILL_APP_REASON_GIDS_CHANGED);
19171                                    }
19172                                });
19173                                break;
19174                            }
19175                        }
19176                    }
19177                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19178                }
19179                // make sure to preserve per-user disabled state if this removal was just
19180                // a downgrade of a system app to the factory package
19181                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19182                    if (DEBUG_REMOVE) {
19183                        Slog.d(TAG, "Propagating install state across downgrade");
19184                    }
19185                    for (int userId : allUserHandles) {
19186                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19187                        if (DEBUG_REMOVE) {
19188                            Slog.d(TAG, "    user " + userId + " => " + installed);
19189                        }
19190                        if (installed != ps.getInstalled(userId)) {
19191                            installedStateChanged = true;
19192                        }
19193                        ps.setInstalled(installed, userId);
19194                    }
19195                }
19196            }
19197            // can downgrade to reader
19198            if (writeSettings) {
19199                // Save settings now
19200                mSettings.writeLPr();
19201            }
19202            if (installedStateChanged) {
19203                mSettings.writeKernelMappingLPr(ps);
19204            }
19205        }
19206        if (removedAppId != -1) {
19207            // A user ID was deleted here. Go through all users and remove it
19208            // from KeyStore.
19209            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19210        }
19211    }
19212
19213    static boolean locationIsPrivileged(File path) {
19214        try {
19215            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19216                    .getCanonicalPath();
19217            return path.getCanonicalPath().startsWith(privilegedAppDir);
19218        } catch (IOException e) {
19219            Slog.e(TAG, "Unable to access code path " + path);
19220        }
19221        return false;
19222    }
19223
19224    /*
19225     * Tries to delete system package.
19226     */
19227    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19228            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19229            boolean writeSettings) {
19230        if (deletedPs.parentPackageName != null) {
19231            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19232            return false;
19233        }
19234
19235        final boolean applyUserRestrictions
19236                = (allUserHandles != null) && (outInfo.origUsers != null);
19237        final PackageSetting disabledPs;
19238        // Confirm if the system package has been updated
19239        // An updated system app can be deleted. This will also have to restore
19240        // the system pkg from system partition
19241        // reader
19242        synchronized (mPackages) {
19243            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19244        }
19245
19246        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19247                + " disabledPs=" + disabledPs);
19248
19249        if (disabledPs == null) {
19250            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19251            return false;
19252        } else if (DEBUG_REMOVE) {
19253            Slog.d(TAG, "Deleting system pkg from data partition");
19254        }
19255
19256        if (DEBUG_REMOVE) {
19257            if (applyUserRestrictions) {
19258                Slog.d(TAG, "Remembering install states:");
19259                for (int userId : allUserHandles) {
19260                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19261                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19262                }
19263            }
19264        }
19265
19266        // Delete the updated package
19267        outInfo.isRemovedPackageSystemUpdate = true;
19268        if (outInfo.removedChildPackages != null) {
19269            final int childCount = (deletedPs.childPackageNames != null)
19270                    ? deletedPs.childPackageNames.size() : 0;
19271            for (int i = 0; i < childCount; i++) {
19272                String childPackageName = deletedPs.childPackageNames.get(i);
19273                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19274                        .contains(childPackageName)) {
19275                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19276                            childPackageName);
19277                    if (childInfo != null) {
19278                        childInfo.isRemovedPackageSystemUpdate = true;
19279                    }
19280                }
19281            }
19282        }
19283
19284        if (disabledPs.versionCode < deletedPs.versionCode) {
19285            // Delete data for downgrades
19286            flags &= ~PackageManager.DELETE_KEEP_DATA;
19287        } else {
19288            // Preserve data by setting flag
19289            flags |= PackageManager.DELETE_KEEP_DATA;
19290        }
19291
19292        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19293                outInfo, writeSettings, disabledPs.pkg);
19294        if (!ret) {
19295            return false;
19296        }
19297
19298        // writer
19299        synchronized (mPackages) {
19300            // Reinstate the old system package
19301            enableSystemPackageLPw(disabledPs.pkg);
19302            // Remove any native libraries from the upgraded package.
19303            removeNativeBinariesLI(deletedPs);
19304        }
19305
19306        // Install the system package
19307        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19308        int parseFlags = mDefParseFlags
19309                | PackageParser.PARSE_MUST_BE_APK
19310                | PackageParser.PARSE_IS_SYSTEM
19311                | PackageParser.PARSE_IS_SYSTEM_DIR;
19312        if (locationIsPrivileged(disabledPs.codePath)) {
19313            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19314        }
19315
19316        final PackageParser.Package newPkg;
19317        try {
19318            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19319                0 /* currentTime */, null);
19320        } catch (PackageManagerException e) {
19321            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19322                    + e.getMessage());
19323            return false;
19324        }
19325
19326        try {
19327            // update shared libraries for the newly re-installed system package
19328            updateSharedLibrariesLPr(newPkg, null);
19329        } catch (PackageManagerException e) {
19330            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19331        }
19332
19333        prepareAppDataAfterInstallLIF(newPkg);
19334
19335        // writer
19336        synchronized (mPackages) {
19337            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19338
19339            // Propagate the permissions state as we do not want to drop on the floor
19340            // runtime permissions. The update permissions method below will take
19341            // care of removing obsolete permissions and grant install permissions.
19342            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19343            updatePermissionsLPw(newPkg.packageName, newPkg,
19344                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19345
19346            if (applyUserRestrictions) {
19347                boolean installedStateChanged = false;
19348                if (DEBUG_REMOVE) {
19349                    Slog.d(TAG, "Propagating install state across reinstall");
19350                }
19351                for (int userId : allUserHandles) {
19352                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19353                    if (DEBUG_REMOVE) {
19354                        Slog.d(TAG, "    user " + userId + " => " + installed);
19355                    }
19356                    if (installed != ps.getInstalled(userId)) {
19357                        installedStateChanged = true;
19358                    }
19359                    ps.setInstalled(installed, userId);
19360
19361                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19362                }
19363                // Regardless of writeSettings we need to ensure that this restriction
19364                // state propagation is persisted
19365                mSettings.writeAllUsersPackageRestrictionsLPr();
19366                if (installedStateChanged) {
19367                    mSettings.writeKernelMappingLPr(ps);
19368                }
19369            }
19370            // can downgrade to reader here
19371            if (writeSettings) {
19372                mSettings.writeLPr();
19373            }
19374        }
19375        return true;
19376    }
19377
19378    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19379            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19380            PackageRemovedInfo outInfo, boolean writeSettings,
19381            PackageParser.Package replacingPackage) {
19382        synchronized (mPackages) {
19383            if (outInfo != null) {
19384                outInfo.uid = ps.appId;
19385            }
19386
19387            if (outInfo != null && outInfo.removedChildPackages != null) {
19388                final int childCount = (ps.childPackageNames != null)
19389                        ? ps.childPackageNames.size() : 0;
19390                for (int i = 0; i < childCount; i++) {
19391                    String childPackageName = ps.childPackageNames.get(i);
19392                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19393                    if (childPs == null) {
19394                        return false;
19395                    }
19396                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19397                            childPackageName);
19398                    if (childInfo != null) {
19399                        childInfo.uid = childPs.appId;
19400                    }
19401                }
19402            }
19403        }
19404
19405        // Delete package data from internal structures and also remove data if flag is set
19406        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19407
19408        // Delete the child packages data
19409        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19410        for (int i = 0; i < childCount; i++) {
19411            PackageSetting childPs;
19412            synchronized (mPackages) {
19413                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19414            }
19415            if (childPs != null) {
19416                PackageRemovedInfo childOutInfo = (outInfo != null
19417                        && outInfo.removedChildPackages != null)
19418                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19419                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19420                        && (replacingPackage != null
19421                        && !replacingPackage.hasChildPackage(childPs.name))
19422                        ? flags & ~DELETE_KEEP_DATA : flags;
19423                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19424                        deleteFlags, writeSettings);
19425            }
19426        }
19427
19428        // Delete application code and resources only for parent packages
19429        if (ps.parentPackageName == null) {
19430            if (deleteCodeAndResources && (outInfo != null)) {
19431                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19432                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19433                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19434            }
19435        }
19436
19437        return true;
19438    }
19439
19440    @Override
19441    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19442            int userId) {
19443        mContext.enforceCallingOrSelfPermission(
19444                android.Manifest.permission.DELETE_PACKAGES, null);
19445        synchronized (mPackages) {
19446            // Cannot block uninstall of static shared libs as they are
19447            // considered a part of the using app (emulating static linking).
19448            // Also static libs are installed always on internal storage.
19449            PackageParser.Package pkg = mPackages.get(packageName);
19450            if (pkg != null && pkg.staticSharedLibName != null) {
19451                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19452                        + " providing static shared library: " + pkg.staticSharedLibName);
19453                return false;
19454            }
19455            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19456            mSettings.writePackageRestrictionsLPr(userId);
19457        }
19458        return true;
19459    }
19460
19461    @Override
19462    public boolean getBlockUninstallForUser(String packageName, int userId) {
19463        synchronized (mPackages) {
19464            final PackageSetting ps = mSettings.mPackages.get(packageName);
19465            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19466                return false;
19467            }
19468            return mSettings.getBlockUninstallLPr(userId, packageName);
19469        }
19470    }
19471
19472    @Override
19473    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19474        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19475        synchronized (mPackages) {
19476            PackageSetting ps = mSettings.mPackages.get(packageName);
19477            if (ps == null) {
19478                Log.w(TAG, "Package doesn't exist: " + packageName);
19479                return false;
19480            }
19481            if (systemUserApp) {
19482                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19483            } else {
19484                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19485            }
19486            mSettings.writeLPr();
19487        }
19488        return true;
19489    }
19490
19491    /*
19492     * This method handles package deletion in general
19493     */
19494    private boolean deletePackageLIF(String packageName, UserHandle user,
19495            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19496            PackageRemovedInfo outInfo, boolean writeSettings,
19497            PackageParser.Package replacingPackage) {
19498        if (packageName == null) {
19499            Slog.w(TAG, "Attempt to delete null packageName.");
19500            return false;
19501        }
19502
19503        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19504
19505        PackageSetting ps;
19506        synchronized (mPackages) {
19507            ps = mSettings.mPackages.get(packageName);
19508            if (ps == null) {
19509                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19510                return false;
19511            }
19512
19513            if (ps.parentPackageName != null && (!isSystemApp(ps)
19514                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19515                if (DEBUG_REMOVE) {
19516                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19517                            + ((user == null) ? UserHandle.USER_ALL : user));
19518                }
19519                final int removedUserId = (user != null) ? user.getIdentifier()
19520                        : UserHandle.USER_ALL;
19521                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19522                    return false;
19523                }
19524                markPackageUninstalledForUserLPw(ps, user);
19525                scheduleWritePackageRestrictionsLocked(user);
19526                return true;
19527            }
19528        }
19529
19530        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19531                && user.getIdentifier() != UserHandle.USER_ALL)) {
19532            // The caller is asking that the package only be deleted for a single
19533            // user.  To do this, we just mark its uninstalled state and delete
19534            // its data. If this is a system app, we only allow this to happen if
19535            // they have set the special DELETE_SYSTEM_APP which requests different
19536            // semantics than normal for uninstalling system apps.
19537            markPackageUninstalledForUserLPw(ps, user);
19538
19539            if (!isSystemApp(ps)) {
19540                // Do not uninstall the APK if an app should be cached
19541                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19542                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19543                    // Other user still have this package installed, so all
19544                    // we need to do is clear this user's data and save that
19545                    // it is uninstalled.
19546                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19547                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19548                        return false;
19549                    }
19550                    scheduleWritePackageRestrictionsLocked(user);
19551                    return true;
19552                } else {
19553                    // We need to set it back to 'installed' so the uninstall
19554                    // broadcasts will be sent correctly.
19555                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19556                    ps.setInstalled(true, user.getIdentifier());
19557                    mSettings.writeKernelMappingLPr(ps);
19558                }
19559            } else {
19560                // This is a system app, so we assume that the
19561                // other users still have this package installed, so all
19562                // we need to do is clear this user's data and save that
19563                // it is uninstalled.
19564                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19565                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19566                    return false;
19567                }
19568                scheduleWritePackageRestrictionsLocked(user);
19569                return true;
19570            }
19571        }
19572
19573        // If we are deleting a composite package for all users, keep track
19574        // of result for each child.
19575        if (ps.childPackageNames != null && outInfo != null) {
19576            synchronized (mPackages) {
19577                final int childCount = ps.childPackageNames.size();
19578                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19579                for (int i = 0; i < childCount; i++) {
19580                    String childPackageName = ps.childPackageNames.get(i);
19581                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19582                    childInfo.removedPackage = childPackageName;
19583                    childInfo.installerPackageName = ps.installerPackageName;
19584                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19585                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19586                    if (childPs != null) {
19587                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19588                    }
19589                }
19590            }
19591        }
19592
19593        boolean ret = false;
19594        if (isSystemApp(ps)) {
19595            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19596            // When an updated system application is deleted we delete the existing resources
19597            // as well and fall back to existing code in system partition
19598            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19599        } else {
19600            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19601            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19602                    outInfo, writeSettings, replacingPackage);
19603        }
19604
19605        // Take a note whether we deleted the package for all users
19606        if (outInfo != null) {
19607            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19608            if (outInfo.removedChildPackages != null) {
19609                synchronized (mPackages) {
19610                    final int childCount = outInfo.removedChildPackages.size();
19611                    for (int i = 0; i < childCount; i++) {
19612                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19613                        if (childInfo != null) {
19614                            childInfo.removedForAllUsers = mPackages.get(
19615                                    childInfo.removedPackage) == null;
19616                        }
19617                    }
19618                }
19619            }
19620            // If we uninstalled an update to a system app there may be some
19621            // child packages that appeared as they are declared in the system
19622            // app but were not declared in the update.
19623            if (isSystemApp(ps)) {
19624                synchronized (mPackages) {
19625                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19626                    final int childCount = (updatedPs.childPackageNames != null)
19627                            ? updatedPs.childPackageNames.size() : 0;
19628                    for (int i = 0; i < childCount; i++) {
19629                        String childPackageName = updatedPs.childPackageNames.get(i);
19630                        if (outInfo.removedChildPackages == null
19631                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19632                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19633                            if (childPs == null) {
19634                                continue;
19635                            }
19636                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19637                            installRes.name = childPackageName;
19638                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19639                            installRes.pkg = mPackages.get(childPackageName);
19640                            installRes.uid = childPs.pkg.applicationInfo.uid;
19641                            if (outInfo.appearedChildPackages == null) {
19642                                outInfo.appearedChildPackages = new ArrayMap<>();
19643                            }
19644                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19645                        }
19646                    }
19647                }
19648            }
19649        }
19650
19651        return ret;
19652    }
19653
19654    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19655        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19656                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19657        for (int nextUserId : userIds) {
19658            if (DEBUG_REMOVE) {
19659                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19660            }
19661            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19662                    false /*installed*/,
19663                    true /*stopped*/,
19664                    true /*notLaunched*/,
19665                    false /*hidden*/,
19666                    false /*suspended*/,
19667                    false /*instantApp*/,
19668                    null /*lastDisableAppCaller*/,
19669                    null /*enabledComponents*/,
19670                    null /*disabledComponents*/,
19671                    ps.readUserState(nextUserId).domainVerificationStatus,
19672                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19673        }
19674        mSettings.writeKernelMappingLPr(ps);
19675    }
19676
19677    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19678            PackageRemovedInfo outInfo) {
19679        final PackageParser.Package pkg;
19680        synchronized (mPackages) {
19681            pkg = mPackages.get(ps.name);
19682        }
19683
19684        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19685                : new int[] {userId};
19686        for (int nextUserId : userIds) {
19687            if (DEBUG_REMOVE) {
19688                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19689                        + nextUserId);
19690            }
19691
19692            destroyAppDataLIF(pkg, userId,
19693                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19694            destroyAppProfilesLIF(pkg, userId);
19695            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19696            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19697            schedulePackageCleaning(ps.name, nextUserId, false);
19698            synchronized (mPackages) {
19699                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19700                    scheduleWritePackageRestrictionsLocked(nextUserId);
19701                }
19702                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19703            }
19704        }
19705
19706        if (outInfo != null) {
19707            outInfo.removedPackage = ps.name;
19708            outInfo.installerPackageName = ps.installerPackageName;
19709            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19710            outInfo.removedAppId = ps.appId;
19711            outInfo.removedUsers = userIds;
19712            outInfo.broadcastUsers = userIds;
19713        }
19714
19715        return true;
19716    }
19717
19718    private final class ClearStorageConnection implements ServiceConnection {
19719        IMediaContainerService mContainerService;
19720
19721        @Override
19722        public void onServiceConnected(ComponentName name, IBinder service) {
19723            synchronized (this) {
19724                mContainerService = IMediaContainerService.Stub
19725                        .asInterface(Binder.allowBlocking(service));
19726                notifyAll();
19727            }
19728        }
19729
19730        @Override
19731        public void onServiceDisconnected(ComponentName name) {
19732        }
19733    }
19734
19735    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19736        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19737
19738        final boolean mounted;
19739        if (Environment.isExternalStorageEmulated()) {
19740            mounted = true;
19741        } else {
19742            final String status = Environment.getExternalStorageState();
19743
19744            mounted = status.equals(Environment.MEDIA_MOUNTED)
19745                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19746        }
19747
19748        if (!mounted) {
19749            return;
19750        }
19751
19752        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19753        int[] users;
19754        if (userId == UserHandle.USER_ALL) {
19755            users = sUserManager.getUserIds();
19756        } else {
19757            users = new int[] { userId };
19758        }
19759        final ClearStorageConnection conn = new ClearStorageConnection();
19760        if (mContext.bindServiceAsUser(
19761                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19762            try {
19763                for (int curUser : users) {
19764                    long timeout = SystemClock.uptimeMillis() + 5000;
19765                    synchronized (conn) {
19766                        long now;
19767                        while (conn.mContainerService == null &&
19768                                (now = SystemClock.uptimeMillis()) < timeout) {
19769                            try {
19770                                conn.wait(timeout - now);
19771                            } catch (InterruptedException e) {
19772                            }
19773                        }
19774                    }
19775                    if (conn.mContainerService == null) {
19776                        return;
19777                    }
19778
19779                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19780                    clearDirectory(conn.mContainerService,
19781                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19782                    if (allData) {
19783                        clearDirectory(conn.mContainerService,
19784                                userEnv.buildExternalStorageAppDataDirs(packageName));
19785                        clearDirectory(conn.mContainerService,
19786                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19787                    }
19788                }
19789            } finally {
19790                mContext.unbindService(conn);
19791            }
19792        }
19793    }
19794
19795    @Override
19796    public void clearApplicationProfileData(String packageName) {
19797        enforceSystemOrRoot("Only the system can clear all profile data");
19798
19799        final PackageParser.Package pkg;
19800        synchronized (mPackages) {
19801            pkg = mPackages.get(packageName);
19802        }
19803
19804        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19805            synchronized (mInstallLock) {
19806                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19807            }
19808        }
19809    }
19810
19811    @Override
19812    public void clearApplicationUserData(final String packageName,
19813            final IPackageDataObserver observer, final int userId) {
19814        mContext.enforceCallingOrSelfPermission(
19815                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19816
19817        final int callingUid = Binder.getCallingUid();
19818        enforceCrossUserPermission(callingUid, userId,
19819                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19820
19821        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19822        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19823            return;
19824        }
19825        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19826            throw new SecurityException("Cannot clear data for a protected package: "
19827                    + packageName);
19828        }
19829        // Queue up an async operation since the package deletion may take a little while.
19830        mHandler.post(new Runnable() {
19831            public void run() {
19832                mHandler.removeCallbacks(this);
19833                final boolean succeeded;
19834                try (PackageFreezer freezer = freezePackage(packageName,
19835                        "clearApplicationUserData")) {
19836                    synchronized (mInstallLock) {
19837                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19838                    }
19839                    clearExternalStorageDataSync(packageName, userId, true);
19840                    synchronized (mPackages) {
19841                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19842                                packageName, userId);
19843                    }
19844                }
19845                if (succeeded) {
19846                    // invoke DeviceStorageMonitor's update method to clear any notifications
19847                    DeviceStorageMonitorInternal dsm = LocalServices
19848                            .getService(DeviceStorageMonitorInternal.class);
19849                    if (dsm != null) {
19850                        dsm.checkMemory();
19851                    }
19852                }
19853                if(observer != null) {
19854                    try {
19855                        observer.onRemoveCompleted(packageName, succeeded);
19856                    } catch (RemoteException e) {
19857                        Log.i(TAG, "Observer no longer exists.");
19858                    }
19859                } //end if observer
19860            } //end run
19861        });
19862    }
19863
19864    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19865        if (packageName == null) {
19866            Slog.w(TAG, "Attempt to delete null packageName.");
19867            return false;
19868        }
19869
19870        // Try finding details about the requested package
19871        PackageParser.Package pkg;
19872        synchronized (mPackages) {
19873            pkg = mPackages.get(packageName);
19874            if (pkg == null) {
19875                final PackageSetting ps = mSettings.mPackages.get(packageName);
19876                if (ps != null) {
19877                    pkg = ps.pkg;
19878                }
19879            }
19880
19881            if (pkg == null) {
19882                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19883                return false;
19884            }
19885
19886            PackageSetting ps = (PackageSetting) pkg.mExtras;
19887            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19888        }
19889
19890        clearAppDataLIF(pkg, userId,
19891                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19892
19893        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19894        removeKeystoreDataIfNeeded(userId, appId);
19895
19896        UserManagerInternal umInternal = getUserManagerInternal();
19897        final int flags;
19898        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19899            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19900        } else if (umInternal.isUserRunning(userId)) {
19901            flags = StorageManager.FLAG_STORAGE_DE;
19902        } else {
19903            flags = 0;
19904        }
19905        prepareAppDataContentsLIF(pkg, userId, flags);
19906
19907        return true;
19908    }
19909
19910    /**
19911     * Reverts user permission state changes (permissions and flags) in
19912     * all packages for a given user.
19913     *
19914     * @param userId The device user for which to do a reset.
19915     */
19916    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19917        final int packageCount = mPackages.size();
19918        for (int i = 0; i < packageCount; i++) {
19919            PackageParser.Package pkg = mPackages.valueAt(i);
19920            PackageSetting ps = (PackageSetting) pkg.mExtras;
19921            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19922        }
19923    }
19924
19925    private void resetNetworkPolicies(int userId) {
19926        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19927    }
19928
19929    /**
19930     * Reverts user permission state changes (permissions and flags).
19931     *
19932     * @param ps The package for which to reset.
19933     * @param userId The device user for which to do a reset.
19934     */
19935    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19936            final PackageSetting ps, final int userId) {
19937        if (ps.pkg == null) {
19938            return;
19939        }
19940
19941        // These are flags that can change base on user actions.
19942        final int userSettableMask = FLAG_PERMISSION_USER_SET
19943                | FLAG_PERMISSION_USER_FIXED
19944                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19945                | FLAG_PERMISSION_REVIEW_REQUIRED;
19946
19947        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19948                | FLAG_PERMISSION_POLICY_FIXED;
19949
19950        boolean writeInstallPermissions = false;
19951        boolean writeRuntimePermissions = false;
19952
19953        final int permissionCount = ps.pkg.requestedPermissions.size();
19954        for (int i = 0; i < permissionCount; i++) {
19955            String permission = ps.pkg.requestedPermissions.get(i);
19956
19957            BasePermission bp = mSettings.mPermissions.get(permission);
19958            if (bp == null) {
19959                continue;
19960            }
19961
19962            // If shared user we just reset the state to which only this app contributed.
19963            if (ps.sharedUser != null) {
19964                boolean used = false;
19965                final int packageCount = ps.sharedUser.packages.size();
19966                for (int j = 0; j < packageCount; j++) {
19967                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19968                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19969                            && pkg.pkg.requestedPermissions.contains(permission)) {
19970                        used = true;
19971                        break;
19972                    }
19973                }
19974                if (used) {
19975                    continue;
19976                }
19977            }
19978
19979            PermissionsState permissionsState = ps.getPermissionsState();
19980
19981            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19982
19983            // Always clear the user settable flags.
19984            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19985                    bp.name) != null;
19986            // If permission review is enabled and this is a legacy app, mark the
19987            // permission as requiring a review as this is the initial state.
19988            int flags = 0;
19989            if (mPermissionReviewRequired
19990                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19991                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19992            }
19993            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19994                if (hasInstallState) {
19995                    writeInstallPermissions = true;
19996                } else {
19997                    writeRuntimePermissions = true;
19998                }
19999            }
20000
20001            // Below is only runtime permission handling.
20002            if (!bp.isRuntime()) {
20003                continue;
20004            }
20005
20006            // Never clobber system or policy.
20007            if ((oldFlags & policyOrSystemFlags) != 0) {
20008                continue;
20009            }
20010
20011            // If this permission was granted by default, make sure it is.
20012            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20013                if (permissionsState.grantRuntimePermission(bp, userId)
20014                        != PERMISSION_OPERATION_FAILURE) {
20015                    writeRuntimePermissions = true;
20016                }
20017            // If permission review is enabled the permissions for a legacy apps
20018            // are represented as constantly granted runtime ones, so don't revoke.
20019            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20020                // Otherwise, reset the permission.
20021                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20022                switch (revokeResult) {
20023                    case PERMISSION_OPERATION_SUCCESS:
20024                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20025                        writeRuntimePermissions = true;
20026                        final int appId = ps.appId;
20027                        mHandler.post(new Runnable() {
20028                            @Override
20029                            public void run() {
20030                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20031                            }
20032                        });
20033                    } break;
20034                }
20035            }
20036        }
20037
20038        // Synchronously write as we are taking permissions away.
20039        if (writeRuntimePermissions) {
20040            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20041        }
20042
20043        // Synchronously write as we are taking permissions away.
20044        if (writeInstallPermissions) {
20045            mSettings.writeLPr();
20046        }
20047    }
20048
20049    /**
20050     * Remove entries from the keystore daemon. Will only remove it if the
20051     * {@code appId} is valid.
20052     */
20053    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20054        if (appId < 0) {
20055            return;
20056        }
20057
20058        final KeyStore keyStore = KeyStore.getInstance();
20059        if (keyStore != null) {
20060            if (userId == UserHandle.USER_ALL) {
20061                for (final int individual : sUserManager.getUserIds()) {
20062                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20063                }
20064            } else {
20065                keyStore.clearUid(UserHandle.getUid(userId, appId));
20066            }
20067        } else {
20068            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20069        }
20070    }
20071
20072    @Override
20073    public void deleteApplicationCacheFiles(final String packageName,
20074            final IPackageDataObserver observer) {
20075        final int userId = UserHandle.getCallingUserId();
20076        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20077    }
20078
20079    @Override
20080    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20081            final IPackageDataObserver observer) {
20082        final int callingUid = Binder.getCallingUid();
20083        mContext.enforceCallingOrSelfPermission(
20084                android.Manifest.permission.DELETE_CACHE_FILES, null);
20085        enforceCrossUserPermission(callingUid, userId,
20086                /* requireFullPermission= */ true, /* checkShell= */ false,
20087                "delete application cache files");
20088        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20089                android.Manifest.permission.ACCESS_INSTANT_APPS);
20090
20091        final PackageParser.Package pkg;
20092        synchronized (mPackages) {
20093            pkg = mPackages.get(packageName);
20094        }
20095
20096        // Queue up an async operation since the package deletion may take a little while.
20097        mHandler.post(new Runnable() {
20098            public void run() {
20099                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20100                boolean doClearData = true;
20101                if (ps != null) {
20102                    final boolean targetIsInstantApp =
20103                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20104                    doClearData = !targetIsInstantApp
20105                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20106                }
20107                if (doClearData) {
20108                    synchronized (mInstallLock) {
20109                        final int flags = StorageManager.FLAG_STORAGE_DE
20110                                | StorageManager.FLAG_STORAGE_CE;
20111                        // We're only clearing cache files, so we don't care if the
20112                        // app is unfrozen and still able to run
20113                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20114                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20115                    }
20116                    clearExternalStorageDataSync(packageName, userId, false);
20117                }
20118                if (observer != null) {
20119                    try {
20120                        observer.onRemoveCompleted(packageName, true);
20121                    } catch (RemoteException e) {
20122                        Log.i(TAG, "Observer no longer exists.");
20123                    }
20124                }
20125            }
20126        });
20127    }
20128
20129    @Override
20130    public void getPackageSizeInfo(final String packageName, int userHandle,
20131            final IPackageStatsObserver observer) {
20132        throw new UnsupportedOperationException(
20133                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20134    }
20135
20136    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20137        final PackageSetting ps;
20138        synchronized (mPackages) {
20139            ps = mSettings.mPackages.get(packageName);
20140            if (ps == null) {
20141                Slog.w(TAG, "Failed to find settings for " + packageName);
20142                return false;
20143            }
20144        }
20145
20146        final String[] packageNames = { packageName };
20147        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20148        final String[] codePaths = { ps.codePathString };
20149
20150        try {
20151            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20152                    ps.appId, ceDataInodes, codePaths, stats);
20153
20154            // For now, ignore code size of packages on system partition
20155            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20156                stats.codeSize = 0;
20157            }
20158
20159            // External clients expect these to be tracked separately
20160            stats.dataSize -= stats.cacheSize;
20161
20162        } catch (InstallerException e) {
20163            Slog.w(TAG, String.valueOf(e));
20164            return false;
20165        }
20166
20167        return true;
20168    }
20169
20170    private int getUidTargetSdkVersionLockedLPr(int uid) {
20171        Object obj = mSettings.getUserIdLPr(uid);
20172        if (obj instanceof SharedUserSetting) {
20173            final SharedUserSetting sus = (SharedUserSetting) obj;
20174            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20175            final Iterator<PackageSetting> it = sus.packages.iterator();
20176            while (it.hasNext()) {
20177                final PackageSetting ps = it.next();
20178                if (ps.pkg != null) {
20179                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20180                    if (v < vers) vers = v;
20181                }
20182            }
20183            return vers;
20184        } else if (obj instanceof PackageSetting) {
20185            final PackageSetting ps = (PackageSetting) obj;
20186            if (ps.pkg != null) {
20187                return ps.pkg.applicationInfo.targetSdkVersion;
20188            }
20189        }
20190        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20191    }
20192
20193    @Override
20194    public void addPreferredActivity(IntentFilter filter, int match,
20195            ComponentName[] set, ComponentName activity, int userId) {
20196        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20197                "Adding preferred");
20198    }
20199
20200    private void addPreferredActivityInternal(IntentFilter filter, int match,
20201            ComponentName[] set, ComponentName activity, boolean always, int userId,
20202            String opname) {
20203        // writer
20204        int callingUid = Binder.getCallingUid();
20205        enforceCrossUserPermission(callingUid, userId,
20206                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20207        if (filter.countActions() == 0) {
20208            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20209            return;
20210        }
20211        synchronized (mPackages) {
20212            if (mContext.checkCallingOrSelfPermission(
20213                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20214                    != PackageManager.PERMISSION_GRANTED) {
20215                if (getUidTargetSdkVersionLockedLPr(callingUid)
20216                        < Build.VERSION_CODES.FROYO) {
20217                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20218                            + callingUid);
20219                    return;
20220                }
20221                mContext.enforceCallingOrSelfPermission(
20222                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20223            }
20224
20225            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20226            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20227                    + userId + ":");
20228            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20229            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20230            scheduleWritePackageRestrictionsLocked(userId);
20231            postPreferredActivityChangedBroadcast(userId);
20232        }
20233    }
20234
20235    private void postPreferredActivityChangedBroadcast(int userId) {
20236        mHandler.post(() -> {
20237            final IActivityManager am = ActivityManager.getService();
20238            if (am == null) {
20239                return;
20240            }
20241
20242            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20243            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20244            try {
20245                am.broadcastIntent(null, intent, null, null,
20246                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20247                        null, false, false, userId);
20248            } catch (RemoteException e) {
20249            }
20250        });
20251    }
20252
20253    @Override
20254    public void replacePreferredActivity(IntentFilter filter, int match,
20255            ComponentName[] set, ComponentName activity, int userId) {
20256        if (filter.countActions() != 1) {
20257            throw new IllegalArgumentException(
20258                    "replacePreferredActivity expects filter to have only 1 action.");
20259        }
20260        if (filter.countDataAuthorities() != 0
20261                || filter.countDataPaths() != 0
20262                || filter.countDataSchemes() > 1
20263                || filter.countDataTypes() != 0) {
20264            throw new IllegalArgumentException(
20265                    "replacePreferredActivity expects filter to have no data authorities, " +
20266                    "paths, or types; and at most one scheme.");
20267        }
20268
20269        final int callingUid = Binder.getCallingUid();
20270        enforceCrossUserPermission(callingUid, userId,
20271                true /* requireFullPermission */, false /* checkShell */,
20272                "replace preferred activity");
20273        synchronized (mPackages) {
20274            if (mContext.checkCallingOrSelfPermission(
20275                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20276                    != PackageManager.PERMISSION_GRANTED) {
20277                if (getUidTargetSdkVersionLockedLPr(callingUid)
20278                        < Build.VERSION_CODES.FROYO) {
20279                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20280                            + Binder.getCallingUid());
20281                    return;
20282                }
20283                mContext.enforceCallingOrSelfPermission(
20284                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20285            }
20286
20287            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20288            if (pir != null) {
20289                // Get all of the existing entries that exactly match this filter.
20290                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20291                if (existing != null && existing.size() == 1) {
20292                    PreferredActivity cur = existing.get(0);
20293                    if (DEBUG_PREFERRED) {
20294                        Slog.i(TAG, "Checking replace of preferred:");
20295                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20296                        if (!cur.mPref.mAlways) {
20297                            Slog.i(TAG, "  -- CUR; not mAlways!");
20298                        } else {
20299                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20300                            Slog.i(TAG, "  -- CUR: mSet="
20301                                    + Arrays.toString(cur.mPref.mSetComponents));
20302                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20303                            Slog.i(TAG, "  -- NEW: mMatch="
20304                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20305                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20306                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20307                        }
20308                    }
20309                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20310                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20311                            && cur.mPref.sameSet(set)) {
20312                        // Setting the preferred activity to what it happens to be already
20313                        if (DEBUG_PREFERRED) {
20314                            Slog.i(TAG, "Replacing with same preferred activity "
20315                                    + cur.mPref.mShortComponent + " for user "
20316                                    + userId + ":");
20317                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20318                        }
20319                        return;
20320                    }
20321                }
20322
20323                if (existing != null) {
20324                    if (DEBUG_PREFERRED) {
20325                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20326                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20327                    }
20328                    for (int i = 0; i < existing.size(); i++) {
20329                        PreferredActivity pa = existing.get(i);
20330                        if (DEBUG_PREFERRED) {
20331                            Slog.i(TAG, "Removing existing preferred activity "
20332                                    + pa.mPref.mComponent + ":");
20333                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20334                        }
20335                        pir.removeFilter(pa);
20336                    }
20337                }
20338            }
20339            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20340                    "Replacing preferred");
20341        }
20342    }
20343
20344    @Override
20345    public void clearPackagePreferredActivities(String packageName) {
20346        final int callingUid = Binder.getCallingUid();
20347        if (getInstantAppPackageName(callingUid) != null) {
20348            return;
20349        }
20350        // writer
20351        synchronized (mPackages) {
20352            PackageParser.Package pkg = mPackages.get(packageName);
20353            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20354                if (mContext.checkCallingOrSelfPermission(
20355                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20356                        != PackageManager.PERMISSION_GRANTED) {
20357                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20358                            < Build.VERSION_CODES.FROYO) {
20359                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20360                                + callingUid);
20361                        return;
20362                    }
20363                    mContext.enforceCallingOrSelfPermission(
20364                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20365                }
20366            }
20367            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20368            if (ps != null
20369                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20370                return;
20371            }
20372            int user = UserHandle.getCallingUserId();
20373            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20374                scheduleWritePackageRestrictionsLocked(user);
20375            }
20376        }
20377    }
20378
20379    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20380    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20381        ArrayList<PreferredActivity> removed = null;
20382        boolean changed = false;
20383        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20384            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20385            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20386            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20387                continue;
20388            }
20389            Iterator<PreferredActivity> it = pir.filterIterator();
20390            while (it.hasNext()) {
20391                PreferredActivity pa = it.next();
20392                // Mark entry for removal only if it matches the package name
20393                // and the entry is of type "always".
20394                if (packageName == null ||
20395                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20396                                && pa.mPref.mAlways)) {
20397                    if (removed == null) {
20398                        removed = new ArrayList<PreferredActivity>();
20399                    }
20400                    removed.add(pa);
20401                }
20402            }
20403            if (removed != null) {
20404                for (int j=0; j<removed.size(); j++) {
20405                    PreferredActivity pa = removed.get(j);
20406                    pir.removeFilter(pa);
20407                }
20408                changed = true;
20409            }
20410        }
20411        if (changed) {
20412            postPreferredActivityChangedBroadcast(userId);
20413        }
20414        return changed;
20415    }
20416
20417    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20418    private void clearIntentFilterVerificationsLPw(int userId) {
20419        final int packageCount = mPackages.size();
20420        for (int i = 0; i < packageCount; i++) {
20421            PackageParser.Package pkg = mPackages.valueAt(i);
20422            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20423        }
20424    }
20425
20426    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20427    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20428        if (userId == UserHandle.USER_ALL) {
20429            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20430                    sUserManager.getUserIds())) {
20431                for (int oneUserId : sUserManager.getUserIds()) {
20432                    scheduleWritePackageRestrictionsLocked(oneUserId);
20433                }
20434            }
20435        } else {
20436            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20437                scheduleWritePackageRestrictionsLocked(userId);
20438            }
20439        }
20440    }
20441
20442    /** Clears state for all users, and touches intent filter verification policy */
20443    void clearDefaultBrowserIfNeeded(String packageName) {
20444        for (int oneUserId : sUserManager.getUserIds()) {
20445            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20446        }
20447    }
20448
20449    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20450        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20451        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20452            if (packageName.equals(defaultBrowserPackageName)) {
20453                setDefaultBrowserPackageName(null, userId);
20454            }
20455        }
20456    }
20457
20458    @Override
20459    public void resetApplicationPreferences(int userId) {
20460        mContext.enforceCallingOrSelfPermission(
20461                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20462        final long identity = Binder.clearCallingIdentity();
20463        // writer
20464        try {
20465            synchronized (mPackages) {
20466                clearPackagePreferredActivitiesLPw(null, userId);
20467                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20468                // TODO: We have to reset the default SMS and Phone. This requires
20469                // significant refactoring to keep all default apps in the package
20470                // manager (cleaner but more work) or have the services provide
20471                // callbacks to the package manager to request a default app reset.
20472                applyFactoryDefaultBrowserLPw(userId);
20473                clearIntentFilterVerificationsLPw(userId);
20474                primeDomainVerificationsLPw(userId);
20475                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20476                scheduleWritePackageRestrictionsLocked(userId);
20477            }
20478            resetNetworkPolicies(userId);
20479        } finally {
20480            Binder.restoreCallingIdentity(identity);
20481        }
20482    }
20483
20484    @Override
20485    public int getPreferredActivities(List<IntentFilter> outFilters,
20486            List<ComponentName> outActivities, String packageName) {
20487        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20488            return 0;
20489        }
20490        int num = 0;
20491        final int userId = UserHandle.getCallingUserId();
20492        // reader
20493        synchronized (mPackages) {
20494            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20495            if (pir != null) {
20496                final Iterator<PreferredActivity> it = pir.filterIterator();
20497                while (it.hasNext()) {
20498                    final PreferredActivity pa = it.next();
20499                    if (packageName == null
20500                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20501                                    && pa.mPref.mAlways)) {
20502                        if (outFilters != null) {
20503                            outFilters.add(new IntentFilter(pa));
20504                        }
20505                        if (outActivities != null) {
20506                            outActivities.add(pa.mPref.mComponent);
20507                        }
20508                    }
20509                }
20510            }
20511        }
20512
20513        return num;
20514    }
20515
20516    @Override
20517    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20518            int userId) {
20519        int callingUid = Binder.getCallingUid();
20520        if (callingUid != Process.SYSTEM_UID) {
20521            throw new SecurityException(
20522                    "addPersistentPreferredActivity can only be run by the system");
20523        }
20524        if (filter.countActions() == 0) {
20525            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20526            return;
20527        }
20528        synchronized (mPackages) {
20529            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20530                    ":");
20531            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20532            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20533                    new PersistentPreferredActivity(filter, activity));
20534            scheduleWritePackageRestrictionsLocked(userId);
20535            postPreferredActivityChangedBroadcast(userId);
20536        }
20537    }
20538
20539    @Override
20540    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20541        int callingUid = Binder.getCallingUid();
20542        if (callingUid != Process.SYSTEM_UID) {
20543            throw new SecurityException(
20544                    "clearPackagePersistentPreferredActivities can only be run by the system");
20545        }
20546        ArrayList<PersistentPreferredActivity> removed = null;
20547        boolean changed = false;
20548        synchronized (mPackages) {
20549            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20550                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20551                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20552                        .valueAt(i);
20553                if (userId != thisUserId) {
20554                    continue;
20555                }
20556                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20557                while (it.hasNext()) {
20558                    PersistentPreferredActivity ppa = it.next();
20559                    // Mark entry for removal only if it matches the package name.
20560                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20561                        if (removed == null) {
20562                            removed = new ArrayList<PersistentPreferredActivity>();
20563                        }
20564                        removed.add(ppa);
20565                    }
20566                }
20567                if (removed != null) {
20568                    for (int j=0; j<removed.size(); j++) {
20569                        PersistentPreferredActivity ppa = removed.get(j);
20570                        ppir.removeFilter(ppa);
20571                    }
20572                    changed = true;
20573                }
20574            }
20575
20576            if (changed) {
20577                scheduleWritePackageRestrictionsLocked(userId);
20578                postPreferredActivityChangedBroadcast(userId);
20579            }
20580        }
20581    }
20582
20583    /**
20584     * Common machinery for picking apart a restored XML blob and passing
20585     * it to a caller-supplied functor to be applied to the running system.
20586     */
20587    private void restoreFromXml(XmlPullParser parser, int userId,
20588            String expectedStartTag, BlobXmlRestorer functor)
20589            throws IOException, XmlPullParserException {
20590        int type;
20591        while ((type = parser.next()) != XmlPullParser.START_TAG
20592                && type != XmlPullParser.END_DOCUMENT) {
20593        }
20594        if (type != XmlPullParser.START_TAG) {
20595            // oops didn't find a start tag?!
20596            if (DEBUG_BACKUP) {
20597                Slog.e(TAG, "Didn't find start tag during restore");
20598            }
20599            return;
20600        }
20601Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20602        // this is supposed to be TAG_PREFERRED_BACKUP
20603        if (!expectedStartTag.equals(parser.getName())) {
20604            if (DEBUG_BACKUP) {
20605                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20606            }
20607            return;
20608        }
20609
20610        // skip interfering stuff, then we're aligned with the backing implementation
20611        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20612Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20613        functor.apply(parser, userId);
20614    }
20615
20616    private interface BlobXmlRestorer {
20617        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20618    }
20619
20620    /**
20621     * Non-Binder method, support for the backup/restore mechanism: write the
20622     * full set of preferred activities in its canonical XML format.  Returns the
20623     * XML output as a byte array, or null if there is none.
20624     */
20625    @Override
20626    public byte[] getPreferredActivityBackup(int userId) {
20627        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20628            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20629        }
20630
20631        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20632        try {
20633            final XmlSerializer serializer = new FastXmlSerializer();
20634            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20635            serializer.startDocument(null, true);
20636            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20637
20638            synchronized (mPackages) {
20639                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20640            }
20641
20642            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20643            serializer.endDocument();
20644            serializer.flush();
20645        } catch (Exception e) {
20646            if (DEBUG_BACKUP) {
20647                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20648            }
20649            return null;
20650        }
20651
20652        return dataStream.toByteArray();
20653    }
20654
20655    @Override
20656    public void restorePreferredActivities(byte[] backup, int userId) {
20657        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20658            throw new SecurityException("Only the system may call restorePreferredActivities()");
20659        }
20660
20661        try {
20662            final XmlPullParser parser = Xml.newPullParser();
20663            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20664            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20665                    new BlobXmlRestorer() {
20666                        @Override
20667                        public void apply(XmlPullParser parser, int userId)
20668                                throws XmlPullParserException, IOException {
20669                            synchronized (mPackages) {
20670                                mSettings.readPreferredActivitiesLPw(parser, userId);
20671                            }
20672                        }
20673                    } );
20674        } catch (Exception e) {
20675            if (DEBUG_BACKUP) {
20676                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20677            }
20678        }
20679    }
20680
20681    /**
20682     * Non-Binder method, support for the backup/restore mechanism: write the
20683     * default browser (etc) settings in its canonical XML format.  Returns the default
20684     * browser XML representation as a byte array, or null if there is none.
20685     */
20686    @Override
20687    public byte[] getDefaultAppsBackup(int userId) {
20688        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20689            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20690        }
20691
20692        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20693        try {
20694            final XmlSerializer serializer = new FastXmlSerializer();
20695            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20696            serializer.startDocument(null, true);
20697            serializer.startTag(null, TAG_DEFAULT_APPS);
20698
20699            synchronized (mPackages) {
20700                mSettings.writeDefaultAppsLPr(serializer, userId);
20701            }
20702
20703            serializer.endTag(null, TAG_DEFAULT_APPS);
20704            serializer.endDocument();
20705            serializer.flush();
20706        } catch (Exception e) {
20707            if (DEBUG_BACKUP) {
20708                Slog.e(TAG, "Unable to write default apps for backup", e);
20709            }
20710            return null;
20711        }
20712
20713        return dataStream.toByteArray();
20714    }
20715
20716    @Override
20717    public void restoreDefaultApps(byte[] backup, int userId) {
20718        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20719            throw new SecurityException("Only the system may call restoreDefaultApps()");
20720        }
20721
20722        try {
20723            final XmlPullParser parser = Xml.newPullParser();
20724            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20725            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20726                    new BlobXmlRestorer() {
20727                        @Override
20728                        public void apply(XmlPullParser parser, int userId)
20729                                throws XmlPullParserException, IOException {
20730                            synchronized (mPackages) {
20731                                mSettings.readDefaultAppsLPw(parser, userId);
20732                            }
20733                        }
20734                    } );
20735        } catch (Exception e) {
20736            if (DEBUG_BACKUP) {
20737                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20738            }
20739        }
20740    }
20741
20742    @Override
20743    public byte[] getIntentFilterVerificationBackup(int userId) {
20744        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20745            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20746        }
20747
20748        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20749        try {
20750            final XmlSerializer serializer = new FastXmlSerializer();
20751            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20752            serializer.startDocument(null, true);
20753            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20754
20755            synchronized (mPackages) {
20756                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20757            }
20758
20759            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20760            serializer.endDocument();
20761            serializer.flush();
20762        } catch (Exception e) {
20763            if (DEBUG_BACKUP) {
20764                Slog.e(TAG, "Unable to write default apps for backup", e);
20765            }
20766            return null;
20767        }
20768
20769        return dataStream.toByteArray();
20770    }
20771
20772    @Override
20773    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20774        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20775            throw new SecurityException("Only the system may call restorePreferredActivities()");
20776        }
20777
20778        try {
20779            final XmlPullParser parser = Xml.newPullParser();
20780            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20781            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20782                    new BlobXmlRestorer() {
20783                        @Override
20784                        public void apply(XmlPullParser parser, int userId)
20785                                throws XmlPullParserException, IOException {
20786                            synchronized (mPackages) {
20787                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20788                                mSettings.writeLPr();
20789                            }
20790                        }
20791                    } );
20792        } catch (Exception e) {
20793            if (DEBUG_BACKUP) {
20794                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20795            }
20796        }
20797    }
20798
20799    @Override
20800    public byte[] getPermissionGrantBackup(int userId) {
20801        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20802            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20803        }
20804
20805        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20806        try {
20807            final XmlSerializer serializer = new FastXmlSerializer();
20808            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20809            serializer.startDocument(null, true);
20810            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20811
20812            synchronized (mPackages) {
20813                serializeRuntimePermissionGrantsLPr(serializer, userId);
20814            }
20815
20816            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20817            serializer.endDocument();
20818            serializer.flush();
20819        } catch (Exception e) {
20820            if (DEBUG_BACKUP) {
20821                Slog.e(TAG, "Unable to write default apps for backup", e);
20822            }
20823            return null;
20824        }
20825
20826        return dataStream.toByteArray();
20827    }
20828
20829    @Override
20830    public void restorePermissionGrants(byte[] backup, int userId) {
20831        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20832            throw new SecurityException("Only the system may call restorePermissionGrants()");
20833        }
20834
20835        try {
20836            final XmlPullParser parser = Xml.newPullParser();
20837            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20838            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20839                    new BlobXmlRestorer() {
20840                        @Override
20841                        public void apply(XmlPullParser parser, int userId)
20842                                throws XmlPullParserException, IOException {
20843                            synchronized (mPackages) {
20844                                processRestoredPermissionGrantsLPr(parser, userId);
20845                            }
20846                        }
20847                    } );
20848        } catch (Exception e) {
20849            if (DEBUG_BACKUP) {
20850                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20851            }
20852        }
20853    }
20854
20855    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20856            throws IOException {
20857        serializer.startTag(null, TAG_ALL_GRANTS);
20858
20859        final int N = mSettings.mPackages.size();
20860        for (int i = 0; i < N; i++) {
20861            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20862            boolean pkgGrantsKnown = false;
20863
20864            PermissionsState packagePerms = ps.getPermissionsState();
20865
20866            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20867                final int grantFlags = state.getFlags();
20868                // only look at grants that are not system/policy fixed
20869                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20870                    final boolean isGranted = state.isGranted();
20871                    // And only back up the user-twiddled state bits
20872                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20873                        final String packageName = mSettings.mPackages.keyAt(i);
20874                        if (!pkgGrantsKnown) {
20875                            serializer.startTag(null, TAG_GRANT);
20876                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20877                            pkgGrantsKnown = true;
20878                        }
20879
20880                        final boolean userSet =
20881                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20882                        final boolean userFixed =
20883                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20884                        final boolean revoke =
20885                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20886
20887                        serializer.startTag(null, TAG_PERMISSION);
20888                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20889                        if (isGranted) {
20890                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20891                        }
20892                        if (userSet) {
20893                            serializer.attribute(null, ATTR_USER_SET, "true");
20894                        }
20895                        if (userFixed) {
20896                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20897                        }
20898                        if (revoke) {
20899                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20900                        }
20901                        serializer.endTag(null, TAG_PERMISSION);
20902                    }
20903                }
20904            }
20905
20906            if (pkgGrantsKnown) {
20907                serializer.endTag(null, TAG_GRANT);
20908            }
20909        }
20910
20911        serializer.endTag(null, TAG_ALL_GRANTS);
20912    }
20913
20914    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20915            throws XmlPullParserException, IOException {
20916        String pkgName = null;
20917        int outerDepth = parser.getDepth();
20918        int type;
20919        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20920                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20921            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20922                continue;
20923            }
20924
20925            final String tagName = parser.getName();
20926            if (tagName.equals(TAG_GRANT)) {
20927                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20928                if (DEBUG_BACKUP) {
20929                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20930                }
20931            } else if (tagName.equals(TAG_PERMISSION)) {
20932
20933                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20934                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20935
20936                int newFlagSet = 0;
20937                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20938                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20939                }
20940                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20941                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20942                }
20943                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20944                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20945                }
20946                if (DEBUG_BACKUP) {
20947                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20948                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20949                }
20950                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20951                if (ps != null) {
20952                    // Already installed so we apply the grant immediately
20953                    if (DEBUG_BACKUP) {
20954                        Slog.v(TAG, "        + already installed; applying");
20955                    }
20956                    PermissionsState perms = ps.getPermissionsState();
20957                    BasePermission bp = mSettings.mPermissions.get(permName);
20958                    if (bp != null) {
20959                        if (isGranted) {
20960                            perms.grantRuntimePermission(bp, userId);
20961                        }
20962                        if (newFlagSet != 0) {
20963                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20964                        }
20965                    }
20966                } else {
20967                    // Need to wait for post-restore install to apply the grant
20968                    if (DEBUG_BACKUP) {
20969                        Slog.v(TAG, "        - not yet installed; saving for later");
20970                    }
20971                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20972                            isGranted, newFlagSet, userId);
20973                }
20974            } else {
20975                PackageManagerService.reportSettingsProblem(Log.WARN,
20976                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20977                XmlUtils.skipCurrentTag(parser);
20978            }
20979        }
20980
20981        scheduleWriteSettingsLocked();
20982        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20983    }
20984
20985    @Override
20986    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20987            int sourceUserId, int targetUserId, int flags) {
20988        mContext.enforceCallingOrSelfPermission(
20989                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20990        int callingUid = Binder.getCallingUid();
20991        enforceOwnerRights(ownerPackage, callingUid);
20992        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20993        if (intentFilter.countActions() == 0) {
20994            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20995            return;
20996        }
20997        synchronized (mPackages) {
20998            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20999                    ownerPackage, targetUserId, flags);
21000            CrossProfileIntentResolver resolver =
21001                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21002            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21003            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21004            if (existing != null) {
21005                int size = existing.size();
21006                for (int i = 0; i < size; i++) {
21007                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21008                        return;
21009                    }
21010                }
21011            }
21012            resolver.addFilter(newFilter);
21013            scheduleWritePackageRestrictionsLocked(sourceUserId);
21014        }
21015    }
21016
21017    @Override
21018    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21019        mContext.enforceCallingOrSelfPermission(
21020                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21021        final int callingUid = Binder.getCallingUid();
21022        enforceOwnerRights(ownerPackage, callingUid);
21023        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21024        synchronized (mPackages) {
21025            CrossProfileIntentResolver resolver =
21026                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21027            ArraySet<CrossProfileIntentFilter> set =
21028                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21029            for (CrossProfileIntentFilter filter : set) {
21030                if (filter.getOwnerPackage().equals(ownerPackage)) {
21031                    resolver.removeFilter(filter);
21032                }
21033            }
21034            scheduleWritePackageRestrictionsLocked(sourceUserId);
21035        }
21036    }
21037
21038    // Enforcing that callingUid is owning pkg on userId
21039    private void enforceOwnerRights(String pkg, int callingUid) {
21040        // The system owns everything.
21041        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21042            return;
21043        }
21044        final int callingUserId = UserHandle.getUserId(callingUid);
21045        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21046        if (pi == null) {
21047            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21048                    + callingUserId);
21049        }
21050        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21051            throw new SecurityException("Calling uid " + callingUid
21052                    + " does not own package " + pkg);
21053        }
21054    }
21055
21056    @Override
21057    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21058        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21059            return null;
21060        }
21061        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21062    }
21063
21064    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21065        UserManagerService ums = UserManagerService.getInstance();
21066        if (ums != null) {
21067            final UserInfo parent = ums.getProfileParent(userId);
21068            final int launcherUid = (parent != null) ? parent.id : userId;
21069            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21070            if (launcherComponent != null) {
21071                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21072                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21073                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21074                        .setPackage(launcherComponent.getPackageName());
21075                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21076            }
21077        }
21078    }
21079
21080    /**
21081     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21082     * then reports the most likely home activity or null if there are more than one.
21083     */
21084    private ComponentName getDefaultHomeActivity(int userId) {
21085        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21086        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21087        if (cn != null) {
21088            return cn;
21089        }
21090
21091        // Find the launcher with the highest priority and return that component if there are no
21092        // other home activity with the same priority.
21093        int lastPriority = Integer.MIN_VALUE;
21094        ComponentName lastComponent = null;
21095        final int size = allHomeCandidates.size();
21096        for (int i = 0; i < size; i++) {
21097            final ResolveInfo ri = allHomeCandidates.get(i);
21098            if (ri.priority > lastPriority) {
21099                lastComponent = ri.activityInfo.getComponentName();
21100                lastPriority = ri.priority;
21101            } else if (ri.priority == lastPriority) {
21102                // Two components found with same priority.
21103                lastComponent = null;
21104            }
21105        }
21106        return lastComponent;
21107    }
21108
21109    private Intent getHomeIntent() {
21110        Intent intent = new Intent(Intent.ACTION_MAIN);
21111        intent.addCategory(Intent.CATEGORY_HOME);
21112        intent.addCategory(Intent.CATEGORY_DEFAULT);
21113        return intent;
21114    }
21115
21116    private IntentFilter getHomeFilter() {
21117        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21118        filter.addCategory(Intent.CATEGORY_HOME);
21119        filter.addCategory(Intent.CATEGORY_DEFAULT);
21120        return filter;
21121    }
21122
21123    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21124            int userId) {
21125        Intent intent  = getHomeIntent();
21126        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21127                PackageManager.GET_META_DATA, userId);
21128        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21129                true, false, false, userId);
21130
21131        allHomeCandidates.clear();
21132        if (list != null) {
21133            for (ResolveInfo ri : list) {
21134                allHomeCandidates.add(ri);
21135            }
21136        }
21137        return (preferred == null || preferred.activityInfo == null)
21138                ? null
21139                : new ComponentName(preferred.activityInfo.packageName,
21140                        preferred.activityInfo.name);
21141    }
21142
21143    @Override
21144    public void setHomeActivity(ComponentName comp, int userId) {
21145        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21146            return;
21147        }
21148        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21149        getHomeActivitiesAsUser(homeActivities, userId);
21150
21151        boolean found = false;
21152
21153        final int size = homeActivities.size();
21154        final ComponentName[] set = new ComponentName[size];
21155        for (int i = 0; i < size; i++) {
21156            final ResolveInfo candidate = homeActivities.get(i);
21157            final ActivityInfo info = candidate.activityInfo;
21158            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21159            set[i] = activityName;
21160            if (!found && activityName.equals(comp)) {
21161                found = true;
21162            }
21163        }
21164        if (!found) {
21165            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21166                    + userId);
21167        }
21168        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21169                set, comp, userId);
21170    }
21171
21172    private @Nullable String getSetupWizardPackageName() {
21173        final Intent intent = new Intent(Intent.ACTION_MAIN);
21174        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21175
21176        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21177                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21178                        | MATCH_DISABLED_COMPONENTS,
21179                UserHandle.myUserId());
21180        if (matches.size() == 1) {
21181            return matches.get(0).getComponentInfo().packageName;
21182        } else {
21183            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21184                    + ": matches=" + matches);
21185            return null;
21186        }
21187    }
21188
21189    private @Nullable String getStorageManagerPackageName() {
21190        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21191
21192        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21193                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21194                        | MATCH_DISABLED_COMPONENTS,
21195                UserHandle.myUserId());
21196        if (matches.size() == 1) {
21197            return matches.get(0).getComponentInfo().packageName;
21198        } else {
21199            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21200                    + matches.size() + ": matches=" + matches);
21201            return null;
21202        }
21203    }
21204
21205    @Override
21206    public void setApplicationEnabledSetting(String appPackageName,
21207            int newState, int flags, int userId, String callingPackage) {
21208        if (!sUserManager.exists(userId)) return;
21209        if (callingPackage == null) {
21210            callingPackage = Integer.toString(Binder.getCallingUid());
21211        }
21212        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21213    }
21214
21215    @Override
21216    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21217        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21218        synchronized (mPackages) {
21219            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21220            if (pkgSetting != null) {
21221                pkgSetting.setUpdateAvailable(updateAvailable);
21222            }
21223        }
21224    }
21225
21226    @Override
21227    public void setComponentEnabledSetting(ComponentName componentName,
21228            int newState, int flags, int userId) {
21229        if (!sUserManager.exists(userId)) return;
21230        setEnabledSetting(componentName.getPackageName(),
21231                componentName.getClassName(), newState, flags, userId, null);
21232    }
21233
21234    private void setEnabledSetting(final String packageName, String className, int newState,
21235            final int flags, int userId, String callingPackage) {
21236        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21237              || newState == COMPONENT_ENABLED_STATE_ENABLED
21238              || newState == COMPONENT_ENABLED_STATE_DISABLED
21239              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21240              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21241            throw new IllegalArgumentException("Invalid new component state: "
21242                    + newState);
21243        }
21244        PackageSetting pkgSetting;
21245        final int callingUid = Binder.getCallingUid();
21246        final int permission;
21247        if (callingUid == Process.SYSTEM_UID) {
21248            permission = PackageManager.PERMISSION_GRANTED;
21249        } else {
21250            permission = mContext.checkCallingOrSelfPermission(
21251                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21252        }
21253        enforceCrossUserPermission(callingUid, userId,
21254                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21255        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21256        boolean sendNow = false;
21257        boolean isApp = (className == null);
21258        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21259        String componentName = isApp ? packageName : className;
21260        int packageUid = -1;
21261        ArrayList<String> components;
21262
21263        // reader
21264        synchronized (mPackages) {
21265            pkgSetting = mSettings.mPackages.get(packageName);
21266            if (pkgSetting == null) {
21267                if (!isCallerInstantApp) {
21268                    if (className == null) {
21269                        throw new IllegalArgumentException("Unknown package: " + packageName);
21270                    }
21271                    throw new IllegalArgumentException(
21272                            "Unknown component: " + packageName + "/" + className);
21273                } else {
21274                    // throw SecurityException to prevent leaking package information
21275                    throw new SecurityException(
21276                            "Attempt to change component state; "
21277                            + "pid=" + Binder.getCallingPid()
21278                            + ", uid=" + callingUid
21279                            + (className == null
21280                                    ? ", package=" + packageName
21281                                    : ", component=" + packageName + "/" + className));
21282                }
21283            }
21284        }
21285
21286        // Limit who can change which apps
21287        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21288            // Don't allow apps that don't have permission to modify other apps
21289            if (!allowedByPermission
21290                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21291                throw new SecurityException(
21292                        "Attempt to change component state; "
21293                        + "pid=" + Binder.getCallingPid()
21294                        + ", uid=" + callingUid
21295                        + (className == null
21296                                ? ", package=" + packageName
21297                                : ", component=" + packageName + "/" + className));
21298            }
21299            // Don't allow changing protected packages.
21300            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21301                throw new SecurityException("Cannot disable a protected package: " + packageName);
21302            }
21303        }
21304
21305        synchronized (mPackages) {
21306            if (callingUid == Process.SHELL_UID
21307                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21308                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21309                // unless it is a test package.
21310                int oldState = pkgSetting.getEnabled(userId);
21311                if (className == null
21312                    &&
21313                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21314                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21315                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21316                    &&
21317                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21318                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21319                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21320                    // ok
21321                } else {
21322                    throw new SecurityException(
21323                            "Shell cannot change component state for " + packageName + "/"
21324                            + className + " to " + newState);
21325                }
21326            }
21327            if (className == null) {
21328                // We're dealing with an application/package level state change
21329                if (pkgSetting.getEnabled(userId) == newState) {
21330                    // Nothing to do
21331                    return;
21332                }
21333                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21334                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21335                    // Don't care about who enables an app.
21336                    callingPackage = null;
21337                }
21338                pkgSetting.setEnabled(newState, userId, callingPackage);
21339                // pkgSetting.pkg.mSetEnabled = newState;
21340            } else {
21341                // We're dealing with a component level state change
21342                // First, verify that this is a valid class name.
21343                PackageParser.Package pkg = pkgSetting.pkg;
21344                if (pkg == null || !pkg.hasComponentClassName(className)) {
21345                    if (pkg != null &&
21346                            pkg.applicationInfo.targetSdkVersion >=
21347                                    Build.VERSION_CODES.JELLY_BEAN) {
21348                        throw new IllegalArgumentException("Component class " + className
21349                                + " does not exist in " + packageName);
21350                    } else {
21351                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21352                                + className + " does not exist in " + packageName);
21353                    }
21354                }
21355                switch (newState) {
21356                case COMPONENT_ENABLED_STATE_ENABLED:
21357                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21358                        return;
21359                    }
21360                    break;
21361                case COMPONENT_ENABLED_STATE_DISABLED:
21362                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21363                        return;
21364                    }
21365                    break;
21366                case COMPONENT_ENABLED_STATE_DEFAULT:
21367                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21368                        return;
21369                    }
21370                    break;
21371                default:
21372                    Slog.e(TAG, "Invalid new component state: " + newState);
21373                    return;
21374                }
21375            }
21376            scheduleWritePackageRestrictionsLocked(userId);
21377            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21378            final long callingId = Binder.clearCallingIdentity();
21379            try {
21380                updateInstantAppInstallerLocked(packageName);
21381            } finally {
21382                Binder.restoreCallingIdentity(callingId);
21383            }
21384            components = mPendingBroadcasts.get(userId, packageName);
21385            final boolean newPackage = components == null;
21386            if (newPackage) {
21387                components = new ArrayList<String>();
21388            }
21389            if (!components.contains(componentName)) {
21390                components.add(componentName);
21391            }
21392            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21393                sendNow = true;
21394                // Purge entry from pending broadcast list if another one exists already
21395                // since we are sending one right away.
21396                mPendingBroadcasts.remove(userId, packageName);
21397            } else {
21398                if (newPackage) {
21399                    mPendingBroadcasts.put(userId, packageName, components);
21400                }
21401                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21402                    // Schedule a message
21403                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21404                }
21405            }
21406        }
21407
21408        long callingId = Binder.clearCallingIdentity();
21409        try {
21410            if (sendNow) {
21411                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21412                sendPackageChangedBroadcast(packageName,
21413                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21414            }
21415        } finally {
21416            Binder.restoreCallingIdentity(callingId);
21417        }
21418    }
21419
21420    @Override
21421    public void flushPackageRestrictionsAsUser(int userId) {
21422        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21423            return;
21424        }
21425        if (!sUserManager.exists(userId)) {
21426            return;
21427        }
21428        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21429                false /* checkShell */, "flushPackageRestrictions");
21430        synchronized (mPackages) {
21431            mSettings.writePackageRestrictionsLPr(userId);
21432            mDirtyUsers.remove(userId);
21433            if (mDirtyUsers.isEmpty()) {
21434                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21435            }
21436        }
21437    }
21438
21439    private void sendPackageChangedBroadcast(String packageName,
21440            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21441        if (DEBUG_INSTALL)
21442            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21443                    + componentNames);
21444        Bundle extras = new Bundle(4);
21445        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21446        String nameList[] = new String[componentNames.size()];
21447        componentNames.toArray(nameList);
21448        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21449        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21450        extras.putInt(Intent.EXTRA_UID, packageUid);
21451        // If this is not reporting a change of the overall package, then only send it
21452        // to registered receivers.  We don't want to launch a swath of apps for every
21453        // little component state change.
21454        final int flags = !componentNames.contains(packageName)
21455                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21456        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21457                new int[] {UserHandle.getUserId(packageUid)});
21458    }
21459
21460    @Override
21461    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21462        if (!sUserManager.exists(userId)) return;
21463        final int callingUid = Binder.getCallingUid();
21464        if (getInstantAppPackageName(callingUid) != null) {
21465            return;
21466        }
21467        final int permission = mContext.checkCallingOrSelfPermission(
21468                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21469        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21470        enforceCrossUserPermission(callingUid, userId,
21471                true /* requireFullPermission */, true /* checkShell */, "stop package");
21472        // writer
21473        synchronized (mPackages) {
21474            final PackageSetting ps = mSettings.mPackages.get(packageName);
21475            if (!filterAppAccessLPr(ps, callingUid, userId)
21476                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21477                            allowedByPermission, callingUid, userId)) {
21478                scheduleWritePackageRestrictionsLocked(userId);
21479            }
21480        }
21481    }
21482
21483    @Override
21484    public String getInstallerPackageName(String packageName) {
21485        final int callingUid = Binder.getCallingUid();
21486        if (getInstantAppPackageName(callingUid) != null) {
21487            return null;
21488        }
21489        // reader
21490        synchronized (mPackages) {
21491            final PackageSetting ps = mSettings.mPackages.get(packageName);
21492            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21493                return null;
21494            }
21495            return mSettings.getInstallerPackageNameLPr(packageName);
21496        }
21497    }
21498
21499    public boolean isOrphaned(String packageName) {
21500        // reader
21501        synchronized (mPackages) {
21502            return mSettings.isOrphaned(packageName);
21503        }
21504    }
21505
21506    @Override
21507    public int getApplicationEnabledSetting(String packageName, int userId) {
21508        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21509        int callingUid = Binder.getCallingUid();
21510        enforceCrossUserPermission(callingUid, userId,
21511                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21512        // reader
21513        synchronized (mPackages) {
21514            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21515                return COMPONENT_ENABLED_STATE_DISABLED;
21516            }
21517            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21518        }
21519    }
21520
21521    @Override
21522    public int getComponentEnabledSetting(ComponentName component, int userId) {
21523        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21524        int callingUid = Binder.getCallingUid();
21525        enforceCrossUserPermission(callingUid, userId,
21526                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21527        synchronized (mPackages) {
21528            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21529                    component, TYPE_UNKNOWN, userId)) {
21530                return COMPONENT_ENABLED_STATE_DISABLED;
21531            }
21532            return mSettings.getComponentEnabledSettingLPr(component, userId);
21533        }
21534    }
21535
21536    @Override
21537    public void enterSafeMode() {
21538        enforceSystemOrRoot("Only the system can request entering safe mode");
21539
21540        if (!mSystemReady) {
21541            mSafeMode = true;
21542        }
21543    }
21544
21545    @Override
21546    public void systemReady() {
21547        enforceSystemOrRoot("Only the system can claim the system is ready");
21548
21549        mSystemReady = true;
21550        final ContentResolver resolver = mContext.getContentResolver();
21551        ContentObserver co = new ContentObserver(mHandler) {
21552            @Override
21553            public void onChange(boolean selfChange) {
21554                mEphemeralAppsDisabled =
21555                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21556                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21557            }
21558        };
21559        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21560                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21561                false, co, UserHandle.USER_SYSTEM);
21562        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21563                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21564        co.onChange(true);
21565
21566        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21567        // disabled after already being started.
21568        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21569                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21570
21571        // Read the compatibilty setting when the system is ready.
21572        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21573                mContext.getContentResolver(),
21574                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21575        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21576        if (DEBUG_SETTINGS) {
21577            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21578        }
21579
21580        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21581
21582        synchronized (mPackages) {
21583            // Verify that all of the preferred activity components actually
21584            // exist.  It is possible for applications to be updated and at
21585            // that point remove a previously declared activity component that
21586            // had been set as a preferred activity.  We try to clean this up
21587            // the next time we encounter that preferred activity, but it is
21588            // possible for the user flow to never be able to return to that
21589            // situation so here we do a sanity check to make sure we haven't
21590            // left any junk around.
21591            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21592            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21593                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21594                removed.clear();
21595                for (PreferredActivity pa : pir.filterSet()) {
21596                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21597                        removed.add(pa);
21598                    }
21599                }
21600                if (removed.size() > 0) {
21601                    for (int r=0; r<removed.size(); r++) {
21602                        PreferredActivity pa = removed.get(r);
21603                        Slog.w(TAG, "Removing dangling preferred activity: "
21604                                + pa.mPref.mComponent);
21605                        pir.removeFilter(pa);
21606                    }
21607                    mSettings.writePackageRestrictionsLPr(
21608                            mSettings.mPreferredActivities.keyAt(i));
21609                }
21610            }
21611
21612            for (int userId : UserManagerService.getInstance().getUserIds()) {
21613                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21614                    grantPermissionsUserIds = ArrayUtils.appendInt(
21615                            grantPermissionsUserIds, userId);
21616                }
21617            }
21618        }
21619        sUserManager.systemReady();
21620
21621        // If we upgraded grant all default permissions before kicking off.
21622        for (int userId : grantPermissionsUserIds) {
21623            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21624        }
21625
21626        // If we did not grant default permissions, we preload from this the
21627        // default permission exceptions lazily to ensure we don't hit the
21628        // disk on a new user creation.
21629        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21630            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21631        }
21632
21633        // Kick off any messages waiting for system ready
21634        if (mPostSystemReadyMessages != null) {
21635            for (Message msg : mPostSystemReadyMessages) {
21636                msg.sendToTarget();
21637            }
21638            mPostSystemReadyMessages = null;
21639        }
21640
21641        // Watch for external volumes that come and go over time
21642        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21643        storage.registerListener(mStorageListener);
21644
21645        mInstallerService.systemReady();
21646        mPackageDexOptimizer.systemReady();
21647
21648        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21649                StorageManagerInternal.class);
21650        StorageManagerInternal.addExternalStoragePolicy(
21651                new StorageManagerInternal.ExternalStorageMountPolicy() {
21652            @Override
21653            public int getMountMode(int uid, String packageName) {
21654                if (Process.isIsolated(uid)) {
21655                    return Zygote.MOUNT_EXTERNAL_NONE;
21656                }
21657                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21658                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21659                }
21660                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21661                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21662                }
21663                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21664                    return Zygote.MOUNT_EXTERNAL_READ;
21665                }
21666                return Zygote.MOUNT_EXTERNAL_WRITE;
21667            }
21668
21669            @Override
21670            public boolean hasExternalStorage(int uid, String packageName) {
21671                return true;
21672            }
21673        });
21674
21675        // Now that we're mostly running, clean up stale users and apps
21676        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21677        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21678
21679        if (mPrivappPermissionsViolations != null) {
21680            Slog.wtf(TAG,"Signature|privileged permissions not in "
21681                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21682            mPrivappPermissionsViolations = null;
21683        }
21684    }
21685
21686    public void waitForAppDataPrepared() {
21687        if (mPrepareAppDataFuture == null) {
21688            return;
21689        }
21690        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21691        mPrepareAppDataFuture = null;
21692    }
21693
21694    @Override
21695    public boolean isSafeMode() {
21696        // allow instant applications
21697        return mSafeMode;
21698    }
21699
21700    @Override
21701    public boolean hasSystemUidErrors() {
21702        // allow instant applications
21703        return mHasSystemUidErrors;
21704    }
21705
21706    static String arrayToString(int[] array) {
21707        StringBuffer buf = new StringBuffer(128);
21708        buf.append('[');
21709        if (array != null) {
21710            for (int i=0; i<array.length; i++) {
21711                if (i > 0) buf.append(", ");
21712                buf.append(array[i]);
21713            }
21714        }
21715        buf.append(']');
21716        return buf.toString();
21717    }
21718
21719    static class DumpState {
21720        public static final int DUMP_LIBS = 1 << 0;
21721        public static final int DUMP_FEATURES = 1 << 1;
21722        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21723        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21724        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21725        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21726        public static final int DUMP_PERMISSIONS = 1 << 6;
21727        public static final int DUMP_PACKAGES = 1 << 7;
21728        public static final int DUMP_SHARED_USERS = 1 << 8;
21729        public static final int DUMP_MESSAGES = 1 << 9;
21730        public static final int DUMP_PROVIDERS = 1 << 10;
21731        public static final int DUMP_VERIFIERS = 1 << 11;
21732        public static final int DUMP_PREFERRED = 1 << 12;
21733        public static final int DUMP_PREFERRED_XML = 1 << 13;
21734        public static final int DUMP_KEYSETS = 1 << 14;
21735        public static final int DUMP_VERSION = 1 << 15;
21736        public static final int DUMP_INSTALLS = 1 << 16;
21737        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21738        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21739        public static final int DUMP_FROZEN = 1 << 19;
21740        public static final int DUMP_DEXOPT = 1 << 20;
21741        public static final int DUMP_COMPILER_STATS = 1 << 21;
21742        public static final int DUMP_CHANGES = 1 << 22;
21743        public static final int DUMP_VOLUMES = 1 << 23;
21744
21745        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21746
21747        private int mTypes;
21748
21749        private int mOptions;
21750
21751        private boolean mTitlePrinted;
21752
21753        private SharedUserSetting mSharedUser;
21754
21755        public boolean isDumping(int type) {
21756            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21757                return true;
21758            }
21759
21760            return (mTypes & type) != 0;
21761        }
21762
21763        public void setDump(int type) {
21764            mTypes |= type;
21765        }
21766
21767        public boolean isOptionEnabled(int option) {
21768            return (mOptions & option) != 0;
21769        }
21770
21771        public void setOptionEnabled(int option) {
21772            mOptions |= option;
21773        }
21774
21775        public boolean onTitlePrinted() {
21776            final boolean printed = mTitlePrinted;
21777            mTitlePrinted = true;
21778            return printed;
21779        }
21780
21781        public boolean getTitlePrinted() {
21782            return mTitlePrinted;
21783        }
21784
21785        public void setTitlePrinted(boolean enabled) {
21786            mTitlePrinted = enabled;
21787        }
21788
21789        public SharedUserSetting getSharedUser() {
21790            return mSharedUser;
21791        }
21792
21793        public void setSharedUser(SharedUserSetting user) {
21794            mSharedUser = user;
21795        }
21796    }
21797
21798    @Override
21799    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21800            FileDescriptor err, String[] args, ShellCallback callback,
21801            ResultReceiver resultReceiver) {
21802        (new PackageManagerShellCommand(this)).exec(
21803                this, in, out, err, args, callback, resultReceiver);
21804    }
21805
21806    @Override
21807    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21808        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21809
21810        DumpState dumpState = new DumpState();
21811        boolean fullPreferred = false;
21812        boolean checkin = false;
21813
21814        String packageName = null;
21815        ArraySet<String> permissionNames = null;
21816
21817        int opti = 0;
21818        while (opti < args.length) {
21819            String opt = args[opti];
21820            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21821                break;
21822            }
21823            opti++;
21824
21825            if ("-a".equals(opt)) {
21826                // Right now we only know how to print all.
21827            } else if ("-h".equals(opt)) {
21828                pw.println("Package manager dump options:");
21829                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21830                pw.println("    --checkin: dump for a checkin");
21831                pw.println("    -f: print details of intent filters");
21832                pw.println("    -h: print this help");
21833                pw.println("  cmd may be one of:");
21834                pw.println("    l[ibraries]: list known shared libraries");
21835                pw.println("    f[eatures]: list device features");
21836                pw.println("    k[eysets]: print known keysets");
21837                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21838                pw.println("    perm[issions]: dump permissions");
21839                pw.println("    permission [name ...]: dump declaration and use of given permission");
21840                pw.println("    pref[erred]: print preferred package settings");
21841                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21842                pw.println("    prov[iders]: dump content providers");
21843                pw.println("    p[ackages]: dump installed packages");
21844                pw.println("    s[hared-users]: dump shared user IDs");
21845                pw.println("    m[essages]: print collected runtime messages");
21846                pw.println("    v[erifiers]: print package verifier info");
21847                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21848                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21849                pw.println("    version: print database version info");
21850                pw.println("    write: write current settings now");
21851                pw.println("    installs: details about install sessions");
21852                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21853                pw.println("    dexopt: dump dexopt state");
21854                pw.println("    compiler-stats: dump compiler statistics");
21855                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21856                pw.println("    <package.name>: info about given package");
21857                return;
21858            } else if ("--checkin".equals(opt)) {
21859                checkin = true;
21860            } else if ("-f".equals(opt)) {
21861                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21862            } else if ("--proto".equals(opt)) {
21863                dumpProto(fd);
21864                return;
21865            } else {
21866                pw.println("Unknown argument: " + opt + "; use -h for help");
21867            }
21868        }
21869
21870        // Is the caller requesting to dump a particular piece of data?
21871        if (opti < args.length) {
21872            String cmd = args[opti];
21873            opti++;
21874            // Is this a package name?
21875            if ("android".equals(cmd) || cmd.contains(".")) {
21876                packageName = cmd;
21877                // When dumping a single package, we always dump all of its
21878                // filter information since the amount of data will be reasonable.
21879                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21880            } else if ("check-permission".equals(cmd)) {
21881                if (opti >= args.length) {
21882                    pw.println("Error: check-permission missing permission argument");
21883                    return;
21884                }
21885                String perm = args[opti];
21886                opti++;
21887                if (opti >= args.length) {
21888                    pw.println("Error: check-permission missing package argument");
21889                    return;
21890                }
21891
21892                String pkg = args[opti];
21893                opti++;
21894                int user = UserHandle.getUserId(Binder.getCallingUid());
21895                if (opti < args.length) {
21896                    try {
21897                        user = Integer.parseInt(args[opti]);
21898                    } catch (NumberFormatException e) {
21899                        pw.println("Error: check-permission user argument is not a number: "
21900                                + args[opti]);
21901                        return;
21902                    }
21903                }
21904
21905                // Normalize package name to handle renamed packages and static libs
21906                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21907
21908                pw.println(checkPermission(perm, pkg, user));
21909                return;
21910            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21911                dumpState.setDump(DumpState.DUMP_LIBS);
21912            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21913                dumpState.setDump(DumpState.DUMP_FEATURES);
21914            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21915                if (opti >= args.length) {
21916                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21917                            | DumpState.DUMP_SERVICE_RESOLVERS
21918                            | DumpState.DUMP_RECEIVER_RESOLVERS
21919                            | DumpState.DUMP_CONTENT_RESOLVERS);
21920                } else {
21921                    while (opti < args.length) {
21922                        String name = args[opti];
21923                        if ("a".equals(name) || "activity".equals(name)) {
21924                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21925                        } else if ("s".equals(name) || "service".equals(name)) {
21926                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21927                        } else if ("r".equals(name) || "receiver".equals(name)) {
21928                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21929                        } else if ("c".equals(name) || "content".equals(name)) {
21930                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21931                        } else {
21932                            pw.println("Error: unknown resolver table type: " + name);
21933                            return;
21934                        }
21935                        opti++;
21936                    }
21937                }
21938            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21939                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21940            } else if ("permission".equals(cmd)) {
21941                if (opti >= args.length) {
21942                    pw.println("Error: permission requires permission name");
21943                    return;
21944                }
21945                permissionNames = new ArraySet<>();
21946                while (opti < args.length) {
21947                    permissionNames.add(args[opti]);
21948                    opti++;
21949                }
21950                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21951                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21952            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21953                dumpState.setDump(DumpState.DUMP_PREFERRED);
21954            } else if ("preferred-xml".equals(cmd)) {
21955                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21956                if (opti < args.length && "--full".equals(args[opti])) {
21957                    fullPreferred = true;
21958                    opti++;
21959                }
21960            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21961                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21962            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21963                dumpState.setDump(DumpState.DUMP_PACKAGES);
21964            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21965                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21966            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21967                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21968            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21969                dumpState.setDump(DumpState.DUMP_MESSAGES);
21970            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21971                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21972            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21973                    || "intent-filter-verifiers".equals(cmd)) {
21974                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21975            } else if ("version".equals(cmd)) {
21976                dumpState.setDump(DumpState.DUMP_VERSION);
21977            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21978                dumpState.setDump(DumpState.DUMP_KEYSETS);
21979            } else if ("installs".equals(cmd)) {
21980                dumpState.setDump(DumpState.DUMP_INSTALLS);
21981            } else if ("frozen".equals(cmd)) {
21982                dumpState.setDump(DumpState.DUMP_FROZEN);
21983            } else if ("volumes".equals(cmd)) {
21984                dumpState.setDump(DumpState.DUMP_VOLUMES);
21985            } else if ("dexopt".equals(cmd)) {
21986                dumpState.setDump(DumpState.DUMP_DEXOPT);
21987            } else if ("compiler-stats".equals(cmd)) {
21988                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21989            } else if ("changes".equals(cmd)) {
21990                dumpState.setDump(DumpState.DUMP_CHANGES);
21991            } else if ("write".equals(cmd)) {
21992                synchronized (mPackages) {
21993                    mSettings.writeLPr();
21994                    pw.println("Settings written.");
21995                    return;
21996                }
21997            }
21998        }
21999
22000        if (checkin) {
22001            pw.println("vers,1");
22002        }
22003
22004        // reader
22005        synchronized (mPackages) {
22006            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22007                if (!checkin) {
22008                    if (dumpState.onTitlePrinted())
22009                        pw.println();
22010                    pw.println("Database versions:");
22011                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22012                }
22013            }
22014
22015            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22016                if (!checkin) {
22017                    if (dumpState.onTitlePrinted())
22018                        pw.println();
22019                    pw.println("Verifiers:");
22020                    pw.print("  Required: ");
22021                    pw.print(mRequiredVerifierPackage);
22022                    pw.print(" (uid=");
22023                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22024                            UserHandle.USER_SYSTEM));
22025                    pw.println(")");
22026                } else if (mRequiredVerifierPackage != null) {
22027                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22028                    pw.print(",");
22029                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22030                            UserHandle.USER_SYSTEM));
22031                }
22032            }
22033
22034            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22035                    packageName == null) {
22036                if (mIntentFilterVerifierComponent != null) {
22037                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22038                    if (!checkin) {
22039                        if (dumpState.onTitlePrinted())
22040                            pw.println();
22041                        pw.println("Intent Filter Verifier:");
22042                        pw.print("  Using: ");
22043                        pw.print(verifierPackageName);
22044                        pw.print(" (uid=");
22045                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22046                                UserHandle.USER_SYSTEM));
22047                        pw.println(")");
22048                    } else if (verifierPackageName != null) {
22049                        pw.print("ifv,"); pw.print(verifierPackageName);
22050                        pw.print(",");
22051                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22052                                UserHandle.USER_SYSTEM));
22053                    }
22054                } else {
22055                    pw.println();
22056                    pw.println("No Intent Filter Verifier available!");
22057                }
22058            }
22059
22060            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22061                boolean printedHeader = false;
22062                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22063                while (it.hasNext()) {
22064                    String libName = it.next();
22065                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22066                    if (versionedLib == null) {
22067                        continue;
22068                    }
22069                    final int versionCount = versionedLib.size();
22070                    for (int i = 0; i < versionCount; i++) {
22071                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22072                        if (!checkin) {
22073                            if (!printedHeader) {
22074                                if (dumpState.onTitlePrinted())
22075                                    pw.println();
22076                                pw.println("Libraries:");
22077                                printedHeader = true;
22078                            }
22079                            pw.print("  ");
22080                        } else {
22081                            pw.print("lib,");
22082                        }
22083                        pw.print(libEntry.info.getName());
22084                        if (libEntry.info.isStatic()) {
22085                            pw.print(" version=" + libEntry.info.getVersion());
22086                        }
22087                        if (!checkin) {
22088                            pw.print(" -> ");
22089                        }
22090                        if (libEntry.path != null) {
22091                            pw.print(" (jar) ");
22092                            pw.print(libEntry.path);
22093                        } else {
22094                            pw.print(" (apk) ");
22095                            pw.print(libEntry.apk);
22096                        }
22097                        pw.println();
22098                    }
22099                }
22100            }
22101
22102            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22103                if (dumpState.onTitlePrinted())
22104                    pw.println();
22105                if (!checkin) {
22106                    pw.println("Features:");
22107                }
22108
22109                synchronized (mAvailableFeatures) {
22110                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22111                        if (checkin) {
22112                            pw.print("feat,");
22113                            pw.print(feat.name);
22114                            pw.print(",");
22115                            pw.println(feat.version);
22116                        } else {
22117                            pw.print("  ");
22118                            pw.print(feat.name);
22119                            if (feat.version > 0) {
22120                                pw.print(" version=");
22121                                pw.print(feat.version);
22122                            }
22123                            pw.println();
22124                        }
22125                    }
22126                }
22127            }
22128
22129            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22130                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22131                        : "Activity Resolver Table:", "  ", packageName,
22132                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22133                    dumpState.setTitlePrinted(true);
22134                }
22135            }
22136            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22137                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22138                        : "Receiver Resolver Table:", "  ", packageName,
22139                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22140                    dumpState.setTitlePrinted(true);
22141                }
22142            }
22143            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22144                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22145                        : "Service Resolver Table:", "  ", packageName,
22146                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22147                    dumpState.setTitlePrinted(true);
22148                }
22149            }
22150            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22151                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22152                        : "Provider Resolver Table:", "  ", packageName,
22153                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22154                    dumpState.setTitlePrinted(true);
22155                }
22156            }
22157
22158            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22159                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22160                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22161                    int user = mSettings.mPreferredActivities.keyAt(i);
22162                    if (pir.dump(pw,
22163                            dumpState.getTitlePrinted()
22164                                ? "\nPreferred Activities User " + user + ":"
22165                                : "Preferred Activities User " + user + ":", "  ",
22166                            packageName, true, false)) {
22167                        dumpState.setTitlePrinted(true);
22168                    }
22169                }
22170            }
22171
22172            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22173                pw.flush();
22174                FileOutputStream fout = new FileOutputStream(fd);
22175                BufferedOutputStream str = new BufferedOutputStream(fout);
22176                XmlSerializer serializer = new FastXmlSerializer();
22177                try {
22178                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22179                    serializer.startDocument(null, true);
22180                    serializer.setFeature(
22181                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22182                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22183                    serializer.endDocument();
22184                    serializer.flush();
22185                } catch (IllegalArgumentException e) {
22186                    pw.println("Failed writing: " + e);
22187                } catch (IllegalStateException e) {
22188                    pw.println("Failed writing: " + e);
22189                } catch (IOException e) {
22190                    pw.println("Failed writing: " + e);
22191                }
22192            }
22193
22194            if (!checkin
22195                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22196                    && packageName == null) {
22197                pw.println();
22198                int count = mSettings.mPackages.size();
22199                if (count == 0) {
22200                    pw.println("No applications!");
22201                    pw.println();
22202                } else {
22203                    final String prefix = "  ";
22204                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22205                    if (allPackageSettings.size() == 0) {
22206                        pw.println("No domain preferred apps!");
22207                        pw.println();
22208                    } else {
22209                        pw.println("App verification status:");
22210                        pw.println();
22211                        count = 0;
22212                        for (PackageSetting ps : allPackageSettings) {
22213                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22214                            if (ivi == null || ivi.getPackageName() == null) continue;
22215                            pw.println(prefix + "Package: " + ivi.getPackageName());
22216                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22217                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22218                            pw.println();
22219                            count++;
22220                        }
22221                        if (count == 0) {
22222                            pw.println(prefix + "No app verification established.");
22223                            pw.println();
22224                        }
22225                        for (int userId : sUserManager.getUserIds()) {
22226                            pw.println("App linkages for user " + userId + ":");
22227                            pw.println();
22228                            count = 0;
22229                            for (PackageSetting ps : allPackageSettings) {
22230                                final long status = ps.getDomainVerificationStatusForUser(userId);
22231                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22232                                        && !DEBUG_DOMAIN_VERIFICATION) {
22233                                    continue;
22234                                }
22235                                pw.println(prefix + "Package: " + ps.name);
22236                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22237                                String statusStr = IntentFilterVerificationInfo.
22238                                        getStatusStringFromValue(status);
22239                                pw.println(prefix + "Status:  " + statusStr);
22240                                pw.println();
22241                                count++;
22242                            }
22243                            if (count == 0) {
22244                                pw.println(prefix + "No configured app linkages.");
22245                                pw.println();
22246                            }
22247                        }
22248                    }
22249                }
22250            }
22251
22252            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22253                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22254                if (packageName == null && permissionNames == null) {
22255                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22256                        if (iperm == 0) {
22257                            if (dumpState.onTitlePrinted())
22258                                pw.println();
22259                            pw.println("AppOp Permissions:");
22260                        }
22261                        pw.print("  AppOp Permission ");
22262                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22263                        pw.println(":");
22264                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22265                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22266                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22267                        }
22268                    }
22269                }
22270            }
22271
22272            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22273                boolean printedSomething = false;
22274                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22275                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22276                        continue;
22277                    }
22278                    if (!printedSomething) {
22279                        if (dumpState.onTitlePrinted())
22280                            pw.println();
22281                        pw.println("Registered ContentProviders:");
22282                        printedSomething = true;
22283                    }
22284                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22285                    pw.print("    "); pw.println(p.toString());
22286                }
22287                printedSomething = false;
22288                for (Map.Entry<String, PackageParser.Provider> entry :
22289                        mProvidersByAuthority.entrySet()) {
22290                    PackageParser.Provider p = entry.getValue();
22291                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22292                        continue;
22293                    }
22294                    if (!printedSomething) {
22295                        if (dumpState.onTitlePrinted())
22296                            pw.println();
22297                        pw.println("ContentProvider Authorities:");
22298                        printedSomething = true;
22299                    }
22300                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22301                    pw.print("    "); pw.println(p.toString());
22302                    if (p.info != null && p.info.applicationInfo != null) {
22303                        final String appInfo = p.info.applicationInfo.toString();
22304                        pw.print("      applicationInfo="); pw.println(appInfo);
22305                    }
22306                }
22307            }
22308
22309            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22310                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22311            }
22312
22313            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22314                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22315            }
22316
22317            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22318                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22319            }
22320
22321            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22322                if (dumpState.onTitlePrinted()) pw.println();
22323                pw.println("Package Changes:");
22324                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22325                final int K = mChangedPackages.size();
22326                for (int i = 0; i < K; i++) {
22327                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22328                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22329                    final int N = changes.size();
22330                    if (N == 0) {
22331                        pw.print("    "); pw.println("No packages changed");
22332                    } else {
22333                        for (int j = 0; j < N; j++) {
22334                            final String pkgName = changes.valueAt(j);
22335                            final int sequenceNumber = changes.keyAt(j);
22336                            pw.print("    ");
22337                            pw.print("seq=");
22338                            pw.print(sequenceNumber);
22339                            pw.print(", package=");
22340                            pw.println(pkgName);
22341                        }
22342                    }
22343                }
22344            }
22345
22346            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22347                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22348            }
22349
22350            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22351                // XXX should handle packageName != null by dumping only install data that
22352                // the given package is involved with.
22353                if (dumpState.onTitlePrinted()) pw.println();
22354
22355                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22356                ipw.println();
22357                ipw.println("Frozen packages:");
22358                ipw.increaseIndent();
22359                if (mFrozenPackages.size() == 0) {
22360                    ipw.println("(none)");
22361                } else {
22362                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22363                        ipw.println(mFrozenPackages.valueAt(i));
22364                    }
22365                }
22366                ipw.decreaseIndent();
22367            }
22368
22369            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22370                if (dumpState.onTitlePrinted()) pw.println();
22371
22372                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22373                ipw.println();
22374                ipw.println("Loaded volumes:");
22375                ipw.increaseIndent();
22376                if (mLoadedVolumes.size() == 0) {
22377                    ipw.println("(none)");
22378                } else {
22379                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22380                        ipw.println(mLoadedVolumes.valueAt(i));
22381                    }
22382                }
22383                ipw.decreaseIndent();
22384            }
22385
22386            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22387                if (dumpState.onTitlePrinted()) pw.println();
22388                dumpDexoptStateLPr(pw, packageName);
22389            }
22390
22391            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22392                if (dumpState.onTitlePrinted()) pw.println();
22393                dumpCompilerStatsLPr(pw, packageName);
22394            }
22395
22396            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22397                if (dumpState.onTitlePrinted()) pw.println();
22398                mSettings.dumpReadMessagesLPr(pw, dumpState);
22399
22400                pw.println();
22401                pw.println("Package warning messages:");
22402                BufferedReader in = null;
22403                String line = null;
22404                try {
22405                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22406                    while ((line = in.readLine()) != null) {
22407                        if (line.contains("ignored: updated version")) continue;
22408                        pw.println(line);
22409                    }
22410                } catch (IOException ignored) {
22411                } finally {
22412                    IoUtils.closeQuietly(in);
22413                }
22414            }
22415
22416            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22417                BufferedReader in = null;
22418                String line = null;
22419                try {
22420                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22421                    while ((line = in.readLine()) != null) {
22422                        if (line.contains("ignored: updated version")) continue;
22423                        pw.print("msg,");
22424                        pw.println(line);
22425                    }
22426                } catch (IOException ignored) {
22427                } finally {
22428                    IoUtils.closeQuietly(in);
22429                }
22430            }
22431        }
22432
22433        // PackageInstaller should be called outside of mPackages lock
22434        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22435            // XXX should handle packageName != null by dumping only install data that
22436            // the given package is involved with.
22437            if (dumpState.onTitlePrinted()) pw.println();
22438            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22439        }
22440    }
22441
22442    private void dumpProto(FileDescriptor fd) {
22443        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22444
22445        synchronized (mPackages) {
22446            final long requiredVerifierPackageToken =
22447                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22448            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22449            proto.write(
22450                    PackageServiceDumpProto.PackageShortProto.UID,
22451                    getPackageUid(
22452                            mRequiredVerifierPackage,
22453                            MATCH_DEBUG_TRIAGED_MISSING,
22454                            UserHandle.USER_SYSTEM));
22455            proto.end(requiredVerifierPackageToken);
22456
22457            if (mIntentFilterVerifierComponent != null) {
22458                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22459                final long verifierPackageToken =
22460                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22461                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22462                proto.write(
22463                        PackageServiceDumpProto.PackageShortProto.UID,
22464                        getPackageUid(
22465                                verifierPackageName,
22466                                MATCH_DEBUG_TRIAGED_MISSING,
22467                                UserHandle.USER_SYSTEM));
22468                proto.end(verifierPackageToken);
22469            }
22470
22471            dumpSharedLibrariesProto(proto);
22472            dumpFeaturesProto(proto);
22473            mSettings.dumpPackagesProto(proto);
22474            mSettings.dumpSharedUsersProto(proto);
22475            dumpMessagesProto(proto);
22476        }
22477        proto.flush();
22478    }
22479
22480    private void dumpMessagesProto(ProtoOutputStream proto) {
22481        BufferedReader in = null;
22482        String line = null;
22483        try {
22484            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22485            while ((line = in.readLine()) != null) {
22486                if (line.contains("ignored: updated version")) continue;
22487                proto.write(PackageServiceDumpProto.MESSAGES, line);
22488            }
22489        } catch (IOException ignored) {
22490        } finally {
22491            IoUtils.closeQuietly(in);
22492        }
22493    }
22494
22495    private void dumpFeaturesProto(ProtoOutputStream proto) {
22496        synchronized (mAvailableFeatures) {
22497            final int count = mAvailableFeatures.size();
22498            for (int i = 0; i < count; i++) {
22499                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22500                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22501                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22502                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22503                proto.end(featureToken);
22504            }
22505        }
22506    }
22507
22508    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22509        final int count = mSharedLibraries.size();
22510        for (int i = 0; i < count; i++) {
22511            final String libName = mSharedLibraries.keyAt(i);
22512            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22513            if (versionedLib == null) {
22514                continue;
22515            }
22516            final int versionCount = versionedLib.size();
22517            for (int j = 0; j < versionCount; j++) {
22518                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22519                final long sharedLibraryToken =
22520                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22521                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22522                final boolean isJar = (libEntry.path != null);
22523                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22524                if (isJar) {
22525                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22526                } else {
22527                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22528                }
22529                proto.end(sharedLibraryToken);
22530            }
22531        }
22532    }
22533
22534    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22535        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22536        ipw.println();
22537        ipw.println("Dexopt state:");
22538        ipw.increaseIndent();
22539        Collection<PackageParser.Package> packages = null;
22540        if (packageName != null) {
22541            PackageParser.Package targetPackage = mPackages.get(packageName);
22542            if (targetPackage != null) {
22543                packages = Collections.singletonList(targetPackage);
22544            } else {
22545                ipw.println("Unable to find package: " + packageName);
22546                return;
22547            }
22548        } else {
22549            packages = mPackages.values();
22550        }
22551
22552        for (PackageParser.Package pkg : packages) {
22553            ipw.println("[" + pkg.packageName + "]");
22554            ipw.increaseIndent();
22555            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22556            ipw.decreaseIndent();
22557        }
22558    }
22559
22560    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22561        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22562        ipw.println();
22563        ipw.println("Compiler stats:");
22564        ipw.increaseIndent();
22565        Collection<PackageParser.Package> packages = null;
22566        if (packageName != null) {
22567            PackageParser.Package targetPackage = mPackages.get(packageName);
22568            if (targetPackage != null) {
22569                packages = Collections.singletonList(targetPackage);
22570            } else {
22571                ipw.println("Unable to find package: " + packageName);
22572                return;
22573            }
22574        } else {
22575            packages = mPackages.values();
22576        }
22577
22578        for (PackageParser.Package pkg : packages) {
22579            ipw.println("[" + pkg.packageName + "]");
22580            ipw.increaseIndent();
22581
22582            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22583            if (stats == null) {
22584                ipw.println("(No recorded stats)");
22585            } else {
22586                stats.dump(ipw);
22587            }
22588            ipw.decreaseIndent();
22589        }
22590    }
22591
22592    private String dumpDomainString(String packageName) {
22593        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22594                .getList();
22595        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22596
22597        ArraySet<String> result = new ArraySet<>();
22598        if (iviList.size() > 0) {
22599            for (IntentFilterVerificationInfo ivi : iviList) {
22600                for (String host : ivi.getDomains()) {
22601                    result.add(host);
22602                }
22603            }
22604        }
22605        if (filters != null && filters.size() > 0) {
22606            for (IntentFilter filter : filters) {
22607                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22608                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22609                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22610                    result.addAll(filter.getHostsList());
22611                }
22612            }
22613        }
22614
22615        StringBuilder sb = new StringBuilder(result.size() * 16);
22616        for (String domain : result) {
22617            if (sb.length() > 0) sb.append(" ");
22618            sb.append(domain);
22619        }
22620        return sb.toString();
22621    }
22622
22623    // ------- apps on sdcard specific code -------
22624    static final boolean DEBUG_SD_INSTALL = false;
22625
22626    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22627
22628    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22629
22630    private boolean mMediaMounted = false;
22631
22632    static String getEncryptKey() {
22633        try {
22634            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22635                    SD_ENCRYPTION_KEYSTORE_NAME);
22636            if (sdEncKey == null) {
22637                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22638                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22639                if (sdEncKey == null) {
22640                    Slog.e(TAG, "Failed to create encryption keys");
22641                    return null;
22642                }
22643            }
22644            return sdEncKey;
22645        } catch (NoSuchAlgorithmException nsae) {
22646            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22647            return null;
22648        } catch (IOException ioe) {
22649            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22650            return null;
22651        }
22652    }
22653
22654    /*
22655     * Update media status on PackageManager.
22656     */
22657    @Override
22658    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22659        enforceSystemOrRoot("Media status can only be updated by the system");
22660        // reader; this apparently protects mMediaMounted, but should probably
22661        // be a different lock in that case.
22662        synchronized (mPackages) {
22663            Log.i(TAG, "Updating external media status from "
22664                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22665                    + (mediaStatus ? "mounted" : "unmounted"));
22666            if (DEBUG_SD_INSTALL)
22667                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22668                        + ", mMediaMounted=" + mMediaMounted);
22669            if (mediaStatus == mMediaMounted) {
22670                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22671                        : 0, -1);
22672                mHandler.sendMessage(msg);
22673                return;
22674            }
22675            mMediaMounted = mediaStatus;
22676        }
22677        // Queue up an async operation since the package installation may take a
22678        // little while.
22679        mHandler.post(new Runnable() {
22680            public void run() {
22681                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22682            }
22683        });
22684    }
22685
22686    /**
22687     * Called by StorageManagerService when the initial ASECs to scan are available.
22688     * Should block until all the ASEC containers are finished being scanned.
22689     */
22690    public void scanAvailableAsecs() {
22691        updateExternalMediaStatusInner(true, false, false);
22692    }
22693
22694    /*
22695     * Collect information of applications on external media, map them against
22696     * existing containers and update information based on current mount status.
22697     * Please note that we always have to report status if reportStatus has been
22698     * set to true especially when unloading packages.
22699     */
22700    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22701            boolean externalStorage) {
22702        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22703        int[] uidArr = EmptyArray.INT;
22704
22705        final String[] list = PackageHelper.getSecureContainerList();
22706        if (ArrayUtils.isEmpty(list)) {
22707            Log.i(TAG, "No secure containers found");
22708        } else {
22709            // Process list of secure containers and categorize them
22710            // as active or stale based on their package internal state.
22711
22712            // reader
22713            synchronized (mPackages) {
22714                for (String cid : list) {
22715                    // Leave stages untouched for now; installer service owns them
22716                    if (PackageInstallerService.isStageName(cid)) continue;
22717
22718                    if (DEBUG_SD_INSTALL)
22719                        Log.i(TAG, "Processing container " + cid);
22720                    String pkgName = getAsecPackageName(cid);
22721                    if (pkgName == null) {
22722                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22723                        continue;
22724                    }
22725                    if (DEBUG_SD_INSTALL)
22726                        Log.i(TAG, "Looking for pkg : " + pkgName);
22727
22728                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22729                    if (ps == null) {
22730                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22731                        continue;
22732                    }
22733
22734                    /*
22735                     * Skip packages that are not external if we're unmounting
22736                     * external storage.
22737                     */
22738                    if (externalStorage && !isMounted && !isExternal(ps)) {
22739                        continue;
22740                    }
22741
22742                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22743                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22744                    // The package status is changed only if the code path
22745                    // matches between settings and the container id.
22746                    if (ps.codePathString != null
22747                            && ps.codePathString.startsWith(args.getCodePath())) {
22748                        if (DEBUG_SD_INSTALL) {
22749                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22750                                    + " at code path: " + ps.codePathString);
22751                        }
22752
22753                        // We do have a valid package installed on sdcard
22754                        processCids.put(args, ps.codePathString);
22755                        final int uid = ps.appId;
22756                        if (uid != -1) {
22757                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22758                        }
22759                    } else {
22760                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22761                                + ps.codePathString);
22762                    }
22763                }
22764            }
22765
22766            Arrays.sort(uidArr);
22767        }
22768
22769        // Process packages with valid entries.
22770        if (isMounted) {
22771            if (DEBUG_SD_INSTALL)
22772                Log.i(TAG, "Loading packages");
22773            loadMediaPackages(processCids, uidArr, externalStorage);
22774            startCleaningPackages();
22775            mInstallerService.onSecureContainersAvailable();
22776        } else {
22777            if (DEBUG_SD_INSTALL)
22778                Log.i(TAG, "Unloading packages");
22779            unloadMediaPackages(processCids, uidArr, reportStatus);
22780        }
22781    }
22782
22783    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22784            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22785        final int size = infos.size();
22786        final String[] packageNames = new String[size];
22787        final int[] packageUids = new int[size];
22788        for (int i = 0; i < size; i++) {
22789            final ApplicationInfo info = infos.get(i);
22790            packageNames[i] = info.packageName;
22791            packageUids[i] = info.uid;
22792        }
22793        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22794                finishedReceiver);
22795    }
22796
22797    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22798            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22799        sendResourcesChangedBroadcast(mediaStatus, replacing,
22800                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22801    }
22802
22803    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22804            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22805        int size = pkgList.length;
22806        if (size > 0) {
22807            // Send broadcasts here
22808            Bundle extras = new Bundle();
22809            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22810            if (uidArr != null) {
22811                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22812            }
22813            if (replacing) {
22814                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22815            }
22816            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22817                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22818            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22819        }
22820    }
22821
22822   /*
22823     * Look at potentially valid container ids from processCids If package
22824     * information doesn't match the one on record or package scanning fails,
22825     * the cid is added to list of removeCids. We currently don't delete stale
22826     * containers.
22827     */
22828    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22829            boolean externalStorage) {
22830        ArrayList<String> pkgList = new ArrayList<String>();
22831        Set<AsecInstallArgs> keys = processCids.keySet();
22832
22833        for (AsecInstallArgs args : keys) {
22834            String codePath = processCids.get(args);
22835            if (DEBUG_SD_INSTALL)
22836                Log.i(TAG, "Loading container : " + args.cid);
22837            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22838            try {
22839                // Make sure there are no container errors first.
22840                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22841                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22842                            + " when installing from sdcard");
22843                    continue;
22844                }
22845                // Check code path here.
22846                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22847                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22848                            + " does not match one in settings " + codePath);
22849                    continue;
22850                }
22851                // Parse package
22852                int parseFlags = mDefParseFlags;
22853                if (args.isExternalAsec()) {
22854                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22855                }
22856                if (args.isFwdLocked()) {
22857                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22858                }
22859
22860                synchronized (mInstallLock) {
22861                    PackageParser.Package pkg = null;
22862                    try {
22863                        // Sadly we don't know the package name yet to freeze it
22864                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22865                                SCAN_IGNORE_FROZEN, 0, null);
22866                    } catch (PackageManagerException e) {
22867                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22868                    }
22869                    // Scan the package
22870                    if (pkg != null) {
22871                        /*
22872                         * TODO why is the lock being held? doPostInstall is
22873                         * called in other places without the lock. This needs
22874                         * to be straightened out.
22875                         */
22876                        // writer
22877                        synchronized (mPackages) {
22878                            retCode = PackageManager.INSTALL_SUCCEEDED;
22879                            pkgList.add(pkg.packageName);
22880                            // Post process args
22881                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22882                                    pkg.applicationInfo.uid);
22883                        }
22884                    } else {
22885                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22886                    }
22887                }
22888
22889            } finally {
22890                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22891                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22892                }
22893            }
22894        }
22895        // writer
22896        synchronized (mPackages) {
22897            // If the platform SDK has changed since the last time we booted,
22898            // we need to re-grant app permission to catch any new ones that
22899            // appear. This is really a hack, and means that apps can in some
22900            // cases get permissions that the user didn't initially explicitly
22901            // allow... it would be nice to have some better way to handle
22902            // this situation.
22903            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22904                    : mSettings.getInternalVersion();
22905            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22906                    : StorageManager.UUID_PRIVATE_INTERNAL;
22907
22908            int updateFlags = UPDATE_PERMISSIONS_ALL;
22909            if (ver.sdkVersion != mSdkVersion) {
22910                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22911                        + mSdkVersion + "; regranting permissions for external");
22912                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22913            }
22914            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22915
22916            // Yay, everything is now upgraded
22917            ver.forceCurrent();
22918
22919            // can downgrade to reader
22920            // Persist settings
22921            mSettings.writeLPr();
22922        }
22923        // Send a broadcast to let everyone know we are done processing
22924        if (pkgList.size() > 0) {
22925            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22926        }
22927    }
22928
22929   /*
22930     * Utility method to unload a list of specified containers
22931     */
22932    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22933        // Just unmount all valid containers.
22934        for (AsecInstallArgs arg : cidArgs) {
22935            synchronized (mInstallLock) {
22936                arg.doPostDeleteLI(false);
22937           }
22938       }
22939   }
22940
22941    /*
22942     * Unload packages mounted on external media. This involves deleting package
22943     * data from internal structures, sending broadcasts about disabled packages,
22944     * gc'ing to free up references, unmounting all secure containers
22945     * corresponding to packages on external media, and posting a
22946     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22947     * that we always have to post this message if status has been requested no
22948     * matter what.
22949     */
22950    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22951            final boolean reportStatus) {
22952        if (DEBUG_SD_INSTALL)
22953            Log.i(TAG, "unloading media packages");
22954        ArrayList<String> pkgList = new ArrayList<String>();
22955        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22956        final Set<AsecInstallArgs> keys = processCids.keySet();
22957        for (AsecInstallArgs args : keys) {
22958            String pkgName = args.getPackageName();
22959            if (DEBUG_SD_INSTALL)
22960                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22961            // Delete package internally
22962            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22963            synchronized (mInstallLock) {
22964                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22965                final boolean res;
22966                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22967                        "unloadMediaPackages")) {
22968                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22969                            null);
22970                }
22971                if (res) {
22972                    pkgList.add(pkgName);
22973                } else {
22974                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22975                    failedList.add(args);
22976                }
22977            }
22978        }
22979
22980        // reader
22981        synchronized (mPackages) {
22982            // We didn't update the settings after removing each package;
22983            // write them now for all packages.
22984            mSettings.writeLPr();
22985        }
22986
22987        // We have to absolutely send UPDATED_MEDIA_STATUS only
22988        // after confirming that all the receivers processed the ordered
22989        // broadcast when packages get disabled, force a gc to clean things up.
22990        // and unload all the containers.
22991        if (pkgList.size() > 0) {
22992            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22993                    new IIntentReceiver.Stub() {
22994                public void performReceive(Intent intent, int resultCode, String data,
22995                        Bundle extras, boolean ordered, boolean sticky,
22996                        int sendingUser) throws RemoteException {
22997                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22998                            reportStatus ? 1 : 0, 1, keys);
22999                    mHandler.sendMessage(msg);
23000                }
23001            });
23002        } else {
23003            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23004                    keys);
23005            mHandler.sendMessage(msg);
23006        }
23007    }
23008
23009    private void loadPrivatePackages(final VolumeInfo vol) {
23010        mHandler.post(new Runnable() {
23011            @Override
23012            public void run() {
23013                loadPrivatePackagesInner(vol);
23014            }
23015        });
23016    }
23017
23018    private void loadPrivatePackagesInner(VolumeInfo vol) {
23019        final String volumeUuid = vol.fsUuid;
23020        if (TextUtils.isEmpty(volumeUuid)) {
23021            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23022            return;
23023        }
23024
23025        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23026        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23027        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23028
23029        final VersionInfo ver;
23030        final List<PackageSetting> packages;
23031        synchronized (mPackages) {
23032            ver = mSettings.findOrCreateVersion(volumeUuid);
23033            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23034        }
23035
23036        for (PackageSetting ps : packages) {
23037            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23038            synchronized (mInstallLock) {
23039                final PackageParser.Package pkg;
23040                try {
23041                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23042                    loaded.add(pkg.applicationInfo);
23043
23044                } catch (PackageManagerException e) {
23045                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23046                }
23047
23048                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23049                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23050                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23051                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23052                }
23053            }
23054        }
23055
23056        // Reconcile app data for all started/unlocked users
23057        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23058        final UserManager um = mContext.getSystemService(UserManager.class);
23059        UserManagerInternal umInternal = getUserManagerInternal();
23060        for (UserInfo user : um.getUsers()) {
23061            final int flags;
23062            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23063                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23064            } else if (umInternal.isUserRunning(user.id)) {
23065                flags = StorageManager.FLAG_STORAGE_DE;
23066            } else {
23067                continue;
23068            }
23069
23070            try {
23071                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23072                synchronized (mInstallLock) {
23073                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23074                }
23075            } catch (IllegalStateException e) {
23076                // Device was probably ejected, and we'll process that event momentarily
23077                Slog.w(TAG, "Failed to prepare storage: " + e);
23078            }
23079        }
23080
23081        synchronized (mPackages) {
23082            int updateFlags = UPDATE_PERMISSIONS_ALL;
23083            if (ver.sdkVersion != mSdkVersion) {
23084                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23085                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23086                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23087            }
23088            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23089
23090            // Yay, everything is now upgraded
23091            ver.forceCurrent();
23092
23093            mSettings.writeLPr();
23094        }
23095
23096        for (PackageFreezer freezer : freezers) {
23097            freezer.close();
23098        }
23099
23100        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23101        sendResourcesChangedBroadcast(true, false, loaded, null);
23102        mLoadedVolumes.add(vol.getId());
23103    }
23104
23105    private void unloadPrivatePackages(final VolumeInfo vol) {
23106        mHandler.post(new Runnable() {
23107            @Override
23108            public void run() {
23109                unloadPrivatePackagesInner(vol);
23110            }
23111        });
23112    }
23113
23114    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23115        final String volumeUuid = vol.fsUuid;
23116        if (TextUtils.isEmpty(volumeUuid)) {
23117            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23118            return;
23119        }
23120
23121        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23122        synchronized (mInstallLock) {
23123        synchronized (mPackages) {
23124            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23125            for (PackageSetting ps : packages) {
23126                if (ps.pkg == null) continue;
23127
23128                final ApplicationInfo info = ps.pkg.applicationInfo;
23129                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23130                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23131
23132                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23133                        "unloadPrivatePackagesInner")) {
23134                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23135                            false, null)) {
23136                        unloaded.add(info);
23137                    } else {
23138                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23139                    }
23140                }
23141
23142                // Try very hard to release any references to this package
23143                // so we don't risk the system server being killed due to
23144                // open FDs
23145                AttributeCache.instance().removePackage(ps.name);
23146            }
23147
23148            mSettings.writeLPr();
23149        }
23150        }
23151
23152        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23153        sendResourcesChangedBroadcast(false, false, unloaded, null);
23154        mLoadedVolumes.remove(vol.getId());
23155
23156        // Try very hard to release any references to this path so we don't risk
23157        // the system server being killed due to open FDs
23158        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23159
23160        for (int i = 0; i < 3; i++) {
23161            System.gc();
23162            System.runFinalization();
23163        }
23164    }
23165
23166    private void assertPackageKnown(String volumeUuid, String packageName)
23167            throws PackageManagerException {
23168        synchronized (mPackages) {
23169            // Normalize package name to handle renamed packages
23170            packageName = normalizePackageNameLPr(packageName);
23171
23172            final PackageSetting ps = mSettings.mPackages.get(packageName);
23173            if (ps == null) {
23174                throw new PackageManagerException("Package " + packageName + " is unknown");
23175            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23176                throw new PackageManagerException(
23177                        "Package " + packageName + " found on unknown volume " + volumeUuid
23178                                + "; expected volume " + ps.volumeUuid);
23179            }
23180        }
23181    }
23182
23183    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23184            throws PackageManagerException {
23185        synchronized (mPackages) {
23186            // Normalize package name to handle renamed packages
23187            packageName = normalizePackageNameLPr(packageName);
23188
23189            final PackageSetting ps = mSettings.mPackages.get(packageName);
23190            if (ps == null) {
23191                throw new PackageManagerException("Package " + packageName + " is unknown");
23192            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23193                throw new PackageManagerException(
23194                        "Package " + packageName + " found on unknown volume " + volumeUuid
23195                                + "; expected volume " + ps.volumeUuid);
23196            } else if (!ps.getInstalled(userId)) {
23197                throw new PackageManagerException(
23198                        "Package " + packageName + " not installed for user " + userId);
23199            }
23200        }
23201    }
23202
23203    private List<String> collectAbsoluteCodePaths() {
23204        synchronized (mPackages) {
23205            List<String> codePaths = new ArrayList<>();
23206            final int packageCount = mSettings.mPackages.size();
23207            for (int i = 0; i < packageCount; i++) {
23208                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23209                codePaths.add(ps.codePath.getAbsolutePath());
23210            }
23211            return codePaths;
23212        }
23213    }
23214
23215    /**
23216     * Examine all apps present on given mounted volume, and destroy apps that
23217     * aren't expected, either due to uninstallation or reinstallation on
23218     * another volume.
23219     */
23220    private void reconcileApps(String volumeUuid) {
23221        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23222        List<File> filesToDelete = null;
23223
23224        final File[] files = FileUtils.listFilesOrEmpty(
23225                Environment.getDataAppDirectory(volumeUuid));
23226        for (File file : files) {
23227            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23228                    && !PackageInstallerService.isStageName(file.getName());
23229            if (!isPackage) {
23230                // Ignore entries which are not packages
23231                continue;
23232            }
23233
23234            String absolutePath = file.getAbsolutePath();
23235
23236            boolean pathValid = false;
23237            final int absoluteCodePathCount = absoluteCodePaths.size();
23238            for (int i = 0; i < absoluteCodePathCount; i++) {
23239                String absoluteCodePath = absoluteCodePaths.get(i);
23240                if (absolutePath.startsWith(absoluteCodePath)) {
23241                    pathValid = true;
23242                    break;
23243                }
23244            }
23245
23246            if (!pathValid) {
23247                if (filesToDelete == null) {
23248                    filesToDelete = new ArrayList<>();
23249                }
23250                filesToDelete.add(file);
23251            }
23252        }
23253
23254        if (filesToDelete != null) {
23255            final int fileToDeleteCount = filesToDelete.size();
23256            for (int i = 0; i < fileToDeleteCount; i++) {
23257                File fileToDelete = filesToDelete.get(i);
23258                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23259                synchronized (mInstallLock) {
23260                    removeCodePathLI(fileToDelete);
23261                }
23262            }
23263        }
23264    }
23265
23266    /**
23267     * Reconcile all app data for the given user.
23268     * <p>
23269     * Verifies that directories exist and that ownership and labeling is
23270     * correct for all installed apps on all mounted volumes.
23271     */
23272    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23273        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23274        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23275            final String volumeUuid = vol.getFsUuid();
23276            synchronized (mInstallLock) {
23277                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23278            }
23279        }
23280    }
23281
23282    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23283            boolean migrateAppData) {
23284        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23285    }
23286
23287    /**
23288     * Reconcile all app data on given mounted volume.
23289     * <p>
23290     * Destroys app data that isn't expected, either due to uninstallation or
23291     * reinstallation on another volume.
23292     * <p>
23293     * Verifies that directories exist and that ownership and labeling is
23294     * correct for all installed apps.
23295     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23296     */
23297    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23298            boolean migrateAppData, boolean onlyCoreApps) {
23299        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23300                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23301        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23302
23303        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23304        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23305
23306        // First look for stale data that doesn't belong, and check if things
23307        // have changed since we did our last restorecon
23308        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23309            if (StorageManager.isFileEncryptedNativeOrEmulated()
23310                    && !StorageManager.isUserKeyUnlocked(userId)) {
23311                throw new RuntimeException(
23312                        "Yikes, someone asked us to reconcile CE storage while " + userId
23313                                + " was still locked; this would have caused massive data loss!");
23314            }
23315
23316            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23317            for (File file : files) {
23318                final String packageName = file.getName();
23319                try {
23320                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23321                } catch (PackageManagerException e) {
23322                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23323                    try {
23324                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23325                                StorageManager.FLAG_STORAGE_CE, 0);
23326                    } catch (InstallerException e2) {
23327                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23328                    }
23329                }
23330            }
23331        }
23332        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23333            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23334            for (File file : files) {
23335                final String packageName = file.getName();
23336                try {
23337                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23338                } catch (PackageManagerException e) {
23339                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23340                    try {
23341                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23342                                StorageManager.FLAG_STORAGE_DE, 0);
23343                    } catch (InstallerException e2) {
23344                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23345                    }
23346                }
23347            }
23348        }
23349
23350        // Ensure that data directories are ready to roll for all packages
23351        // installed for this volume and user
23352        final List<PackageSetting> packages;
23353        synchronized (mPackages) {
23354            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23355        }
23356        int preparedCount = 0;
23357        for (PackageSetting ps : packages) {
23358            final String packageName = ps.name;
23359            if (ps.pkg == null) {
23360                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23361                // TODO: might be due to legacy ASEC apps; we should circle back
23362                // and reconcile again once they're scanned
23363                continue;
23364            }
23365            // Skip non-core apps if requested
23366            if (onlyCoreApps && !ps.pkg.coreApp) {
23367                result.add(packageName);
23368                continue;
23369            }
23370
23371            if (ps.getInstalled(userId)) {
23372                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23373                preparedCount++;
23374            }
23375        }
23376
23377        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23378        return result;
23379    }
23380
23381    /**
23382     * Prepare app data for the given app just after it was installed or
23383     * upgraded. This method carefully only touches users that it's installed
23384     * for, and it forces a restorecon to handle any seinfo changes.
23385     * <p>
23386     * Verifies that directories exist and that ownership and labeling is
23387     * correct for all installed apps. If there is an ownership mismatch, it
23388     * will try recovering system apps by wiping data; third-party app data is
23389     * left intact.
23390     * <p>
23391     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23392     */
23393    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23394        final PackageSetting ps;
23395        synchronized (mPackages) {
23396            ps = mSettings.mPackages.get(pkg.packageName);
23397            mSettings.writeKernelMappingLPr(ps);
23398        }
23399
23400        final UserManager um = mContext.getSystemService(UserManager.class);
23401        UserManagerInternal umInternal = getUserManagerInternal();
23402        for (UserInfo user : um.getUsers()) {
23403            final int flags;
23404            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23405                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23406            } else if (umInternal.isUserRunning(user.id)) {
23407                flags = StorageManager.FLAG_STORAGE_DE;
23408            } else {
23409                continue;
23410            }
23411
23412            if (ps.getInstalled(user.id)) {
23413                // TODO: when user data is locked, mark that we're still dirty
23414                prepareAppDataLIF(pkg, user.id, flags);
23415            }
23416        }
23417    }
23418
23419    /**
23420     * Prepare app data for the given app.
23421     * <p>
23422     * Verifies that directories exist and that ownership and labeling is
23423     * correct for all installed apps. If there is an ownership mismatch, this
23424     * will try recovering system apps by wiping data; third-party app data is
23425     * left intact.
23426     */
23427    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23428        if (pkg == null) {
23429            Slog.wtf(TAG, "Package was null!", new Throwable());
23430            return;
23431        }
23432        prepareAppDataLeafLIF(pkg, userId, flags);
23433        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23434        for (int i = 0; i < childCount; i++) {
23435            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23436        }
23437    }
23438
23439    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23440            boolean maybeMigrateAppData) {
23441        prepareAppDataLIF(pkg, userId, flags);
23442
23443        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23444            // We may have just shuffled around app data directories, so
23445            // prepare them one more time
23446            prepareAppDataLIF(pkg, userId, flags);
23447        }
23448    }
23449
23450    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23451        if (DEBUG_APP_DATA) {
23452            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23453                    + Integer.toHexString(flags));
23454        }
23455
23456        final String volumeUuid = pkg.volumeUuid;
23457        final String packageName = pkg.packageName;
23458        final ApplicationInfo app = pkg.applicationInfo;
23459        final int appId = UserHandle.getAppId(app.uid);
23460
23461        Preconditions.checkNotNull(app.seInfo);
23462
23463        long ceDataInode = -1;
23464        try {
23465            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23466                    appId, app.seInfo, app.targetSdkVersion);
23467        } catch (InstallerException e) {
23468            if (app.isSystemApp()) {
23469                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23470                        + ", but trying to recover: " + e);
23471                destroyAppDataLeafLIF(pkg, userId, flags);
23472                try {
23473                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23474                            appId, app.seInfo, app.targetSdkVersion);
23475                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23476                } catch (InstallerException e2) {
23477                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23478                }
23479            } else {
23480                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23481            }
23482        }
23483
23484        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23485            // TODO: mark this structure as dirty so we persist it!
23486            synchronized (mPackages) {
23487                final PackageSetting ps = mSettings.mPackages.get(packageName);
23488                if (ps != null) {
23489                    ps.setCeDataInode(ceDataInode, userId);
23490                }
23491            }
23492        }
23493
23494        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23495    }
23496
23497    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23498        if (pkg == null) {
23499            Slog.wtf(TAG, "Package was null!", new Throwable());
23500            return;
23501        }
23502        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23503        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23504        for (int i = 0; i < childCount; i++) {
23505            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23506        }
23507    }
23508
23509    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23510        final String volumeUuid = pkg.volumeUuid;
23511        final String packageName = pkg.packageName;
23512        final ApplicationInfo app = pkg.applicationInfo;
23513
23514        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23515            // Create a native library symlink only if we have native libraries
23516            // and if the native libraries are 32 bit libraries. We do not provide
23517            // this symlink for 64 bit libraries.
23518            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23519                final String nativeLibPath = app.nativeLibraryDir;
23520                try {
23521                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23522                            nativeLibPath, userId);
23523                } catch (InstallerException e) {
23524                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23525                }
23526            }
23527        }
23528    }
23529
23530    /**
23531     * For system apps on non-FBE devices, this method migrates any existing
23532     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23533     * requested by the app.
23534     */
23535    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23536        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23537                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23538            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23539                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23540            try {
23541                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23542                        storageTarget);
23543            } catch (InstallerException e) {
23544                logCriticalInfo(Log.WARN,
23545                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23546            }
23547            return true;
23548        } else {
23549            return false;
23550        }
23551    }
23552
23553    public PackageFreezer freezePackage(String packageName, String killReason) {
23554        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23555    }
23556
23557    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23558        return new PackageFreezer(packageName, userId, killReason);
23559    }
23560
23561    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23562            String killReason) {
23563        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23564    }
23565
23566    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23567            String killReason) {
23568        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23569            return new PackageFreezer();
23570        } else {
23571            return freezePackage(packageName, userId, killReason);
23572        }
23573    }
23574
23575    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23576            String killReason) {
23577        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23578    }
23579
23580    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23581            String killReason) {
23582        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23583            return new PackageFreezer();
23584        } else {
23585            return freezePackage(packageName, userId, killReason);
23586        }
23587    }
23588
23589    /**
23590     * Class that freezes and kills the given package upon creation, and
23591     * unfreezes it upon closing. This is typically used when doing surgery on
23592     * app code/data to prevent the app from running while you're working.
23593     */
23594    private class PackageFreezer implements AutoCloseable {
23595        private final String mPackageName;
23596        private final PackageFreezer[] mChildren;
23597
23598        private final boolean mWeFroze;
23599
23600        private final AtomicBoolean mClosed = new AtomicBoolean();
23601        private final CloseGuard mCloseGuard = CloseGuard.get();
23602
23603        /**
23604         * Create and return a stub freezer that doesn't actually do anything,
23605         * typically used when someone requested
23606         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23607         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23608         */
23609        public PackageFreezer() {
23610            mPackageName = null;
23611            mChildren = null;
23612            mWeFroze = false;
23613            mCloseGuard.open("close");
23614        }
23615
23616        public PackageFreezer(String packageName, int userId, String killReason) {
23617            synchronized (mPackages) {
23618                mPackageName = packageName;
23619                mWeFroze = mFrozenPackages.add(mPackageName);
23620
23621                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23622                if (ps != null) {
23623                    killApplication(ps.name, ps.appId, userId, killReason);
23624                }
23625
23626                final PackageParser.Package p = mPackages.get(packageName);
23627                if (p != null && p.childPackages != null) {
23628                    final int N = p.childPackages.size();
23629                    mChildren = new PackageFreezer[N];
23630                    for (int i = 0; i < N; i++) {
23631                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23632                                userId, killReason);
23633                    }
23634                } else {
23635                    mChildren = null;
23636                }
23637            }
23638            mCloseGuard.open("close");
23639        }
23640
23641        @Override
23642        protected void finalize() throws Throwable {
23643            try {
23644                if (mCloseGuard != null) {
23645                    mCloseGuard.warnIfOpen();
23646                }
23647
23648                close();
23649            } finally {
23650                super.finalize();
23651            }
23652        }
23653
23654        @Override
23655        public void close() {
23656            mCloseGuard.close();
23657            if (mClosed.compareAndSet(false, true)) {
23658                synchronized (mPackages) {
23659                    if (mWeFroze) {
23660                        mFrozenPackages.remove(mPackageName);
23661                    }
23662
23663                    if (mChildren != null) {
23664                        for (PackageFreezer freezer : mChildren) {
23665                            freezer.close();
23666                        }
23667                    }
23668                }
23669            }
23670        }
23671    }
23672
23673    /**
23674     * Verify that given package is currently frozen.
23675     */
23676    private void checkPackageFrozen(String packageName) {
23677        synchronized (mPackages) {
23678            if (!mFrozenPackages.contains(packageName)) {
23679                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23680            }
23681        }
23682    }
23683
23684    @Override
23685    public int movePackage(final String packageName, final String volumeUuid) {
23686        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23687
23688        final int callingUid = Binder.getCallingUid();
23689        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23690        final int moveId = mNextMoveId.getAndIncrement();
23691        mHandler.post(new Runnable() {
23692            @Override
23693            public void run() {
23694                try {
23695                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23696                } catch (PackageManagerException e) {
23697                    Slog.w(TAG, "Failed to move " + packageName, e);
23698                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
23699                }
23700            }
23701        });
23702        return moveId;
23703    }
23704
23705    private void movePackageInternal(final String packageName, final String volumeUuid,
23706            final int moveId, final int callingUid, UserHandle user)
23707                    throws PackageManagerException {
23708        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23709        final PackageManager pm = mContext.getPackageManager();
23710
23711        final boolean currentAsec;
23712        final String currentVolumeUuid;
23713        final File codeFile;
23714        final String installerPackageName;
23715        final String packageAbiOverride;
23716        final int appId;
23717        final String seinfo;
23718        final String label;
23719        final int targetSdkVersion;
23720        final PackageFreezer freezer;
23721        final int[] installedUserIds;
23722
23723        // reader
23724        synchronized (mPackages) {
23725            final PackageParser.Package pkg = mPackages.get(packageName);
23726            final PackageSetting ps = mSettings.mPackages.get(packageName);
23727            if (pkg == null
23728                    || ps == null
23729                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23730                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23731            }
23732            if (pkg.applicationInfo.isSystemApp()) {
23733                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23734                        "Cannot move system application");
23735            }
23736
23737            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23738            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23739                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23740            if (isInternalStorage && !allow3rdPartyOnInternal) {
23741                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23742                        "3rd party apps are not allowed on internal storage");
23743            }
23744
23745            if (pkg.applicationInfo.isExternalAsec()) {
23746                currentAsec = true;
23747                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23748            } else if (pkg.applicationInfo.isForwardLocked()) {
23749                currentAsec = true;
23750                currentVolumeUuid = "forward_locked";
23751            } else {
23752                currentAsec = false;
23753                currentVolumeUuid = ps.volumeUuid;
23754
23755                final File probe = new File(pkg.codePath);
23756                final File probeOat = new File(probe, "oat");
23757                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23758                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23759                            "Move only supported for modern cluster style installs");
23760                }
23761            }
23762
23763            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23764                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23765                        "Package already moved to " + volumeUuid);
23766            }
23767            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23768                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23769                        "Device admin cannot be moved");
23770            }
23771
23772            if (mFrozenPackages.contains(packageName)) {
23773                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23774                        "Failed to move already frozen package");
23775            }
23776
23777            codeFile = new File(pkg.codePath);
23778            installerPackageName = ps.installerPackageName;
23779            packageAbiOverride = ps.cpuAbiOverrideString;
23780            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23781            seinfo = pkg.applicationInfo.seInfo;
23782            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23783            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23784            freezer = freezePackage(packageName, "movePackageInternal");
23785            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23786        }
23787
23788        final Bundle extras = new Bundle();
23789        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23790        extras.putString(Intent.EXTRA_TITLE, label);
23791        mMoveCallbacks.notifyCreated(moveId, extras);
23792
23793        int installFlags;
23794        final boolean moveCompleteApp;
23795        final File measurePath;
23796
23797        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23798            installFlags = INSTALL_INTERNAL;
23799            moveCompleteApp = !currentAsec;
23800            measurePath = Environment.getDataAppDirectory(volumeUuid);
23801        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23802            installFlags = INSTALL_EXTERNAL;
23803            moveCompleteApp = false;
23804            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23805        } else {
23806            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23807            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23808                    || !volume.isMountedWritable()) {
23809                freezer.close();
23810                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23811                        "Move location not mounted private volume");
23812            }
23813
23814            Preconditions.checkState(!currentAsec);
23815
23816            installFlags = INSTALL_INTERNAL;
23817            moveCompleteApp = true;
23818            measurePath = Environment.getDataAppDirectory(volumeUuid);
23819        }
23820
23821        // If we're moving app data around, we need all the users unlocked
23822        if (moveCompleteApp) {
23823            for (int userId : installedUserIds) {
23824                if (StorageManager.isFileEncryptedNativeOrEmulated()
23825                        && !StorageManager.isUserKeyUnlocked(userId)) {
23826                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
23827                            "User " + userId + " must be unlocked");
23828                }
23829            }
23830        }
23831
23832        final PackageStats stats = new PackageStats(null, -1);
23833        synchronized (mInstaller) {
23834            for (int userId : installedUserIds) {
23835                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23836                    freezer.close();
23837                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23838                            "Failed to measure package size");
23839                }
23840            }
23841        }
23842
23843        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23844                + stats.dataSize);
23845
23846        final long startFreeBytes = measurePath.getUsableSpace();
23847        final long sizeBytes;
23848        if (moveCompleteApp) {
23849            sizeBytes = stats.codeSize + stats.dataSize;
23850        } else {
23851            sizeBytes = stats.codeSize;
23852        }
23853
23854        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23855            freezer.close();
23856            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23857                    "Not enough free space to move");
23858        }
23859
23860        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23861
23862        final CountDownLatch installedLatch = new CountDownLatch(1);
23863        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23864            @Override
23865            public void onUserActionRequired(Intent intent) throws RemoteException {
23866                throw new IllegalStateException();
23867            }
23868
23869            @Override
23870            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23871                    Bundle extras) throws RemoteException {
23872                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23873                        + PackageManager.installStatusToString(returnCode, msg));
23874
23875                installedLatch.countDown();
23876                freezer.close();
23877
23878                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23879                switch (status) {
23880                    case PackageInstaller.STATUS_SUCCESS:
23881                        mMoveCallbacks.notifyStatusChanged(moveId,
23882                                PackageManager.MOVE_SUCCEEDED);
23883                        break;
23884                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23885                        mMoveCallbacks.notifyStatusChanged(moveId,
23886                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23887                        break;
23888                    default:
23889                        mMoveCallbacks.notifyStatusChanged(moveId,
23890                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23891                        break;
23892                }
23893            }
23894        };
23895
23896        final MoveInfo move;
23897        if (moveCompleteApp) {
23898            // Kick off a thread to report progress estimates
23899            new Thread() {
23900                @Override
23901                public void run() {
23902                    while (true) {
23903                        try {
23904                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23905                                break;
23906                            }
23907                        } catch (InterruptedException ignored) {
23908                        }
23909
23910                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23911                        final int progress = 10 + (int) MathUtils.constrain(
23912                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23913                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23914                    }
23915                }
23916            }.start();
23917
23918            final String dataAppName = codeFile.getName();
23919            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23920                    dataAppName, appId, seinfo, targetSdkVersion);
23921        } else {
23922            move = null;
23923        }
23924
23925        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23926
23927        final Message msg = mHandler.obtainMessage(INIT_COPY);
23928        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23929        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23930                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23931                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23932                PackageManager.INSTALL_REASON_UNKNOWN);
23933        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23934        msg.obj = params;
23935
23936        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23937                System.identityHashCode(msg.obj));
23938        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23939                System.identityHashCode(msg.obj));
23940
23941        mHandler.sendMessage(msg);
23942    }
23943
23944    @Override
23945    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23946        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23947
23948        final int realMoveId = mNextMoveId.getAndIncrement();
23949        final Bundle extras = new Bundle();
23950        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23951        mMoveCallbacks.notifyCreated(realMoveId, extras);
23952
23953        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23954            @Override
23955            public void onCreated(int moveId, Bundle extras) {
23956                // Ignored
23957            }
23958
23959            @Override
23960            public void onStatusChanged(int moveId, int status, long estMillis) {
23961                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23962            }
23963        };
23964
23965        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23966        storage.setPrimaryStorageUuid(volumeUuid, callback);
23967        return realMoveId;
23968    }
23969
23970    @Override
23971    public int getMoveStatus(int moveId) {
23972        mContext.enforceCallingOrSelfPermission(
23973                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23974        return mMoveCallbacks.mLastStatus.get(moveId);
23975    }
23976
23977    @Override
23978    public void registerMoveCallback(IPackageMoveObserver callback) {
23979        mContext.enforceCallingOrSelfPermission(
23980                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23981        mMoveCallbacks.register(callback);
23982    }
23983
23984    @Override
23985    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23986        mContext.enforceCallingOrSelfPermission(
23987                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23988        mMoveCallbacks.unregister(callback);
23989    }
23990
23991    @Override
23992    public boolean setInstallLocation(int loc) {
23993        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23994                null);
23995        if (getInstallLocation() == loc) {
23996            return true;
23997        }
23998        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23999                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24000            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24001                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24002            return true;
24003        }
24004        return false;
24005   }
24006
24007    @Override
24008    public int getInstallLocation() {
24009        // allow instant app access
24010        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24011                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24012                PackageHelper.APP_INSTALL_AUTO);
24013    }
24014
24015    /** Called by UserManagerService */
24016    void cleanUpUser(UserManagerService userManager, int userHandle) {
24017        synchronized (mPackages) {
24018            mDirtyUsers.remove(userHandle);
24019            mUserNeedsBadging.delete(userHandle);
24020            mSettings.removeUserLPw(userHandle);
24021            mPendingBroadcasts.remove(userHandle);
24022            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24023            removeUnusedPackagesLPw(userManager, userHandle);
24024        }
24025    }
24026
24027    /**
24028     * We're removing userHandle and would like to remove any downloaded packages
24029     * that are no longer in use by any other user.
24030     * @param userHandle the user being removed
24031     */
24032    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24033        final boolean DEBUG_CLEAN_APKS = false;
24034        int [] users = userManager.getUserIds();
24035        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24036        while (psit.hasNext()) {
24037            PackageSetting ps = psit.next();
24038            if (ps.pkg == null) {
24039                continue;
24040            }
24041            final String packageName = ps.pkg.packageName;
24042            // Skip over if system app
24043            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24044                continue;
24045            }
24046            if (DEBUG_CLEAN_APKS) {
24047                Slog.i(TAG, "Checking package " + packageName);
24048            }
24049            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24050            if (keep) {
24051                if (DEBUG_CLEAN_APKS) {
24052                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24053                }
24054            } else {
24055                for (int i = 0; i < users.length; i++) {
24056                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24057                        keep = true;
24058                        if (DEBUG_CLEAN_APKS) {
24059                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24060                                    + users[i]);
24061                        }
24062                        break;
24063                    }
24064                }
24065            }
24066            if (!keep) {
24067                if (DEBUG_CLEAN_APKS) {
24068                    Slog.i(TAG, "  Removing package " + packageName);
24069                }
24070                mHandler.post(new Runnable() {
24071                    public void run() {
24072                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24073                                userHandle, 0);
24074                    } //end run
24075                });
24076            }
24077        }
24078    }
24079
24080    /** Called by UserManagerService */
24081    void createNewUser(int userId, String[] disallowedPackages) {
24082        synchronized (mInstallLock) {
24083            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24084        }
24085        synchronized (mPackages) {
24086            scheduleWritePackageRestrictionsLocked(userId);
24087            scheduleWritePackageListLocked(userId);
24088            applyFactoryDefaultBrowserLPw(userId);
24089            primeDomainVerificationsLPw(userId);
24090        }
24091    }
24092
24093    void onNewUserCreated(final int userId) {
24094        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24095        // If permission review for legacy apps is required, we represent
24096        // dagerous permissions for such apps as always granted runtime
24097        // permissions to keep per user flag state whether review is needed.
24098        // Hence, if a new user is added we have to propagate dangerous
24099        // permission grants for these legacy apps.
24100        if (mPermissionReviewRequired) {
24101            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24102                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24103        }
24104    }
24105
24106    @Override
24107    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24108        mContext.enforceCallingOrSelfPermission(
24109                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24110                "Only package verification agents can read the verifier device identity");
24111
24112        synchronized (mPackages) {
24113            return mSettings.getVerifierDeviceIdentityLPw();
24114        }
24115    }
24116
24117    @Override
24118    public void setPermissionEnforced(String permission, boolean enforced) {
24119        // TODO: Now that we no longer change GID for storage, this should to away.
24120        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24121                "setPermissionEnforced");
24122        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24123            synchronized (mPackages) {
24124                if (mSettings.mReadExternalStorageEnforced == null
24125                        || mSettings.mReadExternalStorageEnforced != enforced) {
24126                    mSettings.mReadExternalStorageEnforced = enforced;
24127                    mSettings.writeLPr();
24128                }
24129            }
24130            // kill any non-foreground processes so we restart them and
24131            // grant/revoke the GID.
24132            final IActivityManager am = ActivityManager.getService();
24133            if (am != null) {
24134                final long token = Binder.clearCallingIdentity();
24135                try {
24136                    am.killProcessesBelowForeground("setPermissionEnforcement");
24137                } catch (RemoteException e) {
24138                } finally {
24139                    Binder.restoreCallingIdentity(token);
24140                }
24141            }
24142        } else {
24143            throw new IllegalArgumentException("No selective enforcement for " + permission);
24144        }
24145    }
24146
24147    @Override
24148    @Deprecated
24149    public boolean isPermissionEnforced(String permission) {
24150        // allow instant applications
24151        return true;
24152    }
24153
24154    @Override
24155    public boolean isStorageLow() {
24156        // allow instant applications
24157        final long token = Binder.clearCallingIdentity();
24158        try {
24159            final DeviceStorageMonitorInternal
24160                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24161            if (dsm != null) {
24162                return dsm.isMemoryLow();
24163            } else {
24164                return false;
24165            }
24166        } finally {
24167            Binder.restoreCallingIdentity(token);
24168        }
24169    }
24170
24171    @Override
24172    public IPackageInstaller getPackageInstaller() {
24173        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24174            return null;
24175        }
24176        return mInstallerService;
24177    }
24178
24179    private boolean userNeedsBadging(int userId) {
24180        int index = mUserNeedsBadging.indexOfKey(userId);
24181        if (index < 0) {
24182            final UserInfo userInfo;
24183            final long token = Binder.clearCallingIdentity();
24184            try {
24185                userInfo = sUserManager.getUserInfo(userId);
24186            } finally {
24187                Binder.restoreCallingIdentity(token);
24188            }
24189            final boolean b;
24190            if (userInfo != null && userInfo.isManagedProfile()) {
24191                b = true;
24192            } else {
24193                b = false;
24194            }
24195            mUserNeedsBadging.put(userId, b);
24196            return b;
24197        }
24198        return mUserNeedsBadging.valueAt(index);
24199    }
24200
24201    @Override
24202    public KeySet getKeySetByAlias(String packageName, String alias) {
24203        if (packageName == null || alias == null) {
24204            return null;
24205        }
24206        synchronized(mPackages) {
24207            final PackageParser.Package pkg = mPackages.get(packageName);
24208            if (pkg == null) {
24209                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24210                throw new IllegalArgumentException("Unknown package: " + packageName);
24211            }
24212            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24213            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24214                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24215                throw new IllegalArgumentException("Unknown package: " + packageName);
24216            }
24217            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24218            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24219        }
24220    }
24221
24222    @Override
24223    public KeySet getSigningKeySet(String packageName) {
24224        if (packageName == null) {
24225            return null;
24226        }
24227        synchronized(mPackages) {
24228            final int callingUid = Binder.getCallingUid();
24229            final int callingUserId = UserHandle.getUserId(callingUid);
24230            final PackageParser.Package pkg = mPackages.get(packageName);
24231            if (pkg == null) {
24232                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24233                throw new IllegalArgumentException("Unknown package: " + packageName);
24234            }
24235            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24236            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24237                // filter and pretend the package doesn't exist
24238                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24239                        + ", uid:" + callingUid);
24240                throw new IllegalArgumentException("Unknown package: " + packageName);
24241            }
24242            if (pkg.applicationInfo.uid != callingUid
24243                    && Process.SYSTEM_UID != callingUid) {
24244                throw new SecurityException("May not access signing KeySet of other apps.");
24245            }
24246            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24247            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24248        }
24249    }
24250
24251    @Override
24252    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24253        final int callingUid = Binder.getCallingUid();
24254        if (getInstantAppPackageName(callingUid) != null) {
24255            return false;
24256        }
24257        if (packageName == null || ks == null) {
24258            return false;
24259        }
24260        synchronized(mPackages) {
24261            final PackageParser.Package pkg = mPackages.get(packageName);
24262            if (pkg == null
24263                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24264                            UserHandle.getUserId(callingUid))) {
24265                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24266                throw new IllegalArgumentException("Unknown package: " + packageName);
24267            }
24268            IBinder ksh = ks.getToken();
24269            if (ksh instanceof KeySetHandle) {
24270                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24271                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24272            }
24273            return false;
24274        }
24275    }
24276
24277    @Override
24278    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24279        final int callingUid = Binder.getCallingUid();
24280        if (getInstantAppPackageName(callingUid) != null) {
24281            return false;
24282        }
24283        if (packageName == null || ks == null) {
24284            return false;
24285        }
24286        synchronized(mPackages) {
24287            final PackageParser.Package pkg = mPackages.get(packageName);
24288            if (pkg == null
24289                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24290                            UserHandle.getUserId(callingUid))) {
24291                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24292                throw new IllegalArgumentException("Unknown package: " + packageName);
24293            }
24294            IBinder ksh = ks.getToken();
24295            if (ksh instanceof KeySetHandle) {
24296                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24297                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24298            }
24299            return false;
24300        }
24301    }
24302
24303    private void deletePackageIfUnusedLPr(final String packageName) {
24304        PackageSetting ps = mSettings.mPackages.get(packageName);
24305        if (ps == null) {
24306            return;
24307        }
24308        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24309            // TODO Implement atomic delete if package is unused
24310            // It is currently possible that the package will be deleted even if it is installed
24311            // after this method returns.
24312            mHandler.post(new Runnable() {
24313                public void run() {
24314                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24315                            0, PackageManager.DELETE_ALL_USERS);
24316                }
24317            });
24318        }
24319    }
24320
24321    /**
24322     * Check and throw if the given before/after packages would be considered a
24323     * downgrade.
24324     */
24325    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24326            throws PackageManagerException {
24327        if (after.versionCode < before.mVersionCode) {
24328            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24329                    "Update version code " + after.versionCode + " is older than current "
24330                    + before.mVersionCode);
24331        } else if (after.versionCode == before.mVersionCode) {
24332            if (after.baseRevisionCode < before.baseRevisionCode) {
24333                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24334                        "Update base revision code " + after.baseRevisionCode
24335                        + " is older than current " + before.baseRevisionCode);
24336            }
24337
24338            if (!ArrayUtils.isEmpty(after.splitNames)) {
24339                for (int i = 0; i < after.splitNames.length; i++) {
24340                    final String splitName = after.splitNames[i];
24341                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24342                    if (j != -1) {
24343                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24344                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24345                                    "Update split " + splitName + " revision code "
24346                                    + after.splitRevisionCodes[i] + " is older than current "
24347                                    + before.splitRevisionCodes[j]);
24348                        }
24349                    }
24350                }
24351            }
24352        }
24353    }
24354
24355    private static class MoveCallbacks extends Handler {
24356        private static final int MSG_CREATED = 1;
24357        private static final int MSG_STATUS_CHANGED = 2;
24358
24359        private final RemoteCallbackList<IPackageMoveObserver>
24360                mCallbacks = new RemoteCallbackList<>();
24361
24362        private final SparseIntArray mLastStatus = new SparseIntArray();
24363
24364        public MoveCallbacks(Looper looper) {
24365            super(looper);
24366        }
24367
24368        public void register(IPackageMoveObserver callback) {
24369            mCallbacks.register(callback);
24370        }
24371
24372        public void unregister(IPackageMoveObserver callback) {
24373            mCallbacks.unregister(callback);
24374        }
24375
24376        @Override
24377        public void handleMessage(Message msg) {
24378            final SomeArgs args = (SomeArgs) msg.obj;
24379            final int n = mCallbacks.beginBroadcast();
24380            for (int i = 0; i < n; i++) {
24381                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24382                try {
24383                    invokeCallback(callback, msg.what, args);
24384                } catch (RemoteException ignored) {
24385                }
24386            }
24387            mCallbacks.finishBroadcast();
24388            args.recycle();
24389        }
24390
24391        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24392                throws RemoteException {
24393            switch (what) {
24394                case MSG_CREATED: {
24395                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24396                    break;
24397                }
24398                case MSG_STATUS_CHANGED: {
24399                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24400                    break;
24401                }
24402            }
24403        }
24404
24405        private void notifyCreated(int moveId, Bundle extras) {
24406            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24407
24408            final SomeArgs args = SomeArgs.obtain();
24409            args.argi1 = moveId;
24410            args.arg2 = extras;
24411            obtainMessage(MSG_CREATED, args).sendToTarget();
24412        }
24413
24414        private void notifyStatusChanged(int moveId, int status) {
24415            notifyStatusChanged(moveId, status, -1);
24416        }
24417
24418        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24419            Slog.v(TAG, "Move " + moveId + " status " + status);
24420
24421            final SomeArgs args = SomeArgs.obtain();
24422            args.argi1 = moveId;
24423            args.argi2 = status;
24424            args.arg3 = estMillis;
24425            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24426
24427            synchronized (mLastStatus) {
24428                mLastStatus.put(moveId, status);
24429            }
24430        }
24431    }
24432
24433    private final static class OnPermissionChangeListeners extends Handler {
24434        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24435
24436        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24437                new RemoteCallbackList<>();
24438
24439        public OnPermissionChangeListeners(Looper looper) {
24440            super(looper);
24441        }
24442
24443        @Override
24444        public void handleMessage(Message msg) {
24445            switch (msg.what) {
24446                case MSG_ON_PERMISSIONS_CHANGED: {
24447                    final int uid = msg.arg1;
24448                    handleOnPermissionsChanged(uid);
24449                } break;
24450            }
24451        }
24452
24453        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24454            mPermissionListeners.register(listener);
24455
24456        }
24457
24458        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24459            mPermissionListeners.unregister(listener);
24460        }
24461
24462        public void onPermissionsChanged(int uid) {
24463            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24464                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24465            }
24466        }
24467
24468        private void handleOnPermissionsChanged(int uid) {
24469            final int count = mPermissionListeners.beginBroadcast();
24470            try {
24471                for (int i = 0; i < count; i++) {
24472                    IOnPermissionsChangeListener callback = mPermissionListeners
24473                            .getBroadcastItem(i);
24474                    try {
24475                        callback.onPermissionsChanged(uid);
24476                    } catch (RemoteException e) {
24477                        Log.e(TAG, "Permission listener is dead", e);
24478                    }
24479                }
24480            } finally {
24481                mPermissionListeners.finishBroadcast();
24482            }
24483        }
24484    }
24485
24486    private class PackageManagerInternalImpl extends PackageManagerInternal {
24487        @Override
24488        public void setLocationPackagesProvider(PackagesProvider provider) {
24489            synchronized (mPackages) {
24490                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24491            }
24492        }
24493
24494        @Override
24495        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24496            synchronized (mPackages) {
24497                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24498            }
24499        }
24500
24501        @Override
24502        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24503            synchronized (mPackages) {
24504                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24505            }
24506        }
24507
24508        @Override
24509        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24510            synchronized (mPackages) {
24511                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24512            }
24513        }
24514
24515        @Override
24516        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24517            synchronized (mPackages) {
24518                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24519            }
24520        }
24521
24522        @Override
24523        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24524            synchronized (mPackages) {
24525                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24526            }
24527        }
24528
24529        @Override
24530        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24531            synchronized (mPackages) {
24532                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24533                        packageName, userId);
24534            }
24535        }
24536
24537        @Override
24538        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24539            synchronized (mPackages) {
24540                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24541                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24542                        packageName, userId);
24543            }
24544        }
24545
24546        @Override
24547        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24548            synchronized (mPackages) {
24549                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24550                        packageName, userId);
24551            }
24552        }
24553
24554        @Override
24555        public void setKeepUninstalledPackages(final List<String> packageList) {
24556            Preconditions.checkNotNull(packageList);
24557            List<String> removedFromList = null;
24558            synchronized (mPackages) {
24559                if (mKeepUninstalledPackages != null) {
24560                    final int packagesCount = mKeepUninstalledPackages.size();
24561                    for (int i = 0; i < packagesCount; i++) {
24562                        String oldPackage = mKeepUninstalledPackages.get(i);
24563                        if (packageList != null && packageList.contains(oldPackage)) {
24564                            continue;
24565                        }
24566                        if (removedFromList == null) {
24567                            removedFromList = new ArrayList<>();
24568                        }
24569                        removedFromList.add(oldPackage);
24570                    }
24571                }
24572                mKeepUninstalledPackages = new ArrayList<>(packageList);
24573                if (removedFromList != null) {
24574                    final int removedCount = removedFromList.size();
24575                    for (int i = 0; i < removedCount; i++) {
24576                        deletePackageIfUnusedLPr(removedFromList.get(i));
24577                    }
24578                }
24579            }
24580        }
24581
24582        @Override
24583        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24584            synchronized (mPackages) {
24585                // If we do not support permission review, done.
24586                if (!mPermissionReviewRequired) {
24587                    return false;
24588                }
24589
24590                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24591                if (packageSetting == null) {
24592                    return false;
24593                }
24594
24595                // Permission review applies only to apps not supporting the new permission model.
24596                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24597                    return false;
24598                }
24599
24600                // Legacy apps have the permission and get user consent on launch.
24601                PermissionsState permissionsState = packageSetting.getPermissionsState();
24602                return permissionsState.isPermissionReviewRequired(userId);
24603            }
24604        }
24605
24606        @Override
24607        public PackageInfo getPackageInfo(
24608                String packageName, int flags, int filterCallingUid, int userId) {
24609            return PackageManagerService.this
24610                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24611                            flags, filterCallingUid, userId);
24612        }
24613
24614        @Override
24615        public ApplicationInfo getApplicationInfo(
24616                String packageName, int flags, int filterCallingUid, int userId) {
24617            return PackageManagerService.this
24618                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24619        }
24620
24621        @Override
24622        public ActivityInfo getActivityInfo(
24623                ComponentName component, int flags, int filterCallingUid, int userId) {
24624            return PackageManagerService.this
24625                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24626        }
24627
24628        @Override
24629        public List<ResolveInfo> queryIntentActivities(
24630                Intent intent, int flags, int filterCallingUid, int userId) {
24631            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24632            return PackageManagerService.this
24633                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24634                            userId, false /*resolveForStart*/);
24635        }
24636
24637        @Override
24638        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24639                int userId) {
24640            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24641        }
24642
24643        @Override
24644        public void setDeviceAndProfileOwnerPackages(
24645                int deviceOwnerUserId, String deviceOwnerPackage,
24646                SparseArray<String> profileOwnerPackages) {
24647            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24648                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24649        }
24650
24651        @Override
24652        public boolean isPackageDataProtected(int userId, String packageName) {
24653            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24654        }
24655
24656        @Override
24657        public boolean isPackageEphemeral(int userId, String packageName) {
24658            synchronized (mPackages) {
24659                final PackageSetting ps = mSettings.mPackages.get(packageName);
24660                return ps != null ? ps.getInstantApp(userId) : false;
24661            }
24662        }
24663
24664        @Override
24665        public boolean wasPackageEverLaunched(String packageName, int userId) {
24666            synchronized (mPackages) {
24667                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24668            }
24669        }
24670
24671        @Override
24672        public void grantRuntimePermission(String packageName, String name, int userId,
24673                boolean overridePolicy) {
24674            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24675                    overridePolicy);
24676        }
24677
24678        @Override
24679        public void revokeRuntimePermission(String packageName, String name, int userId,
24680                boolean overridePolicy) {
24681            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24682                    overridePolicy);
24683        }
24684
24685        @Override
24686        public String getNameForUid(int uid) {
24687            return PackageManagerService.this.getNameForUid(uid);
24688        }
24689
24690        @Override
24691        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24692                Intent origIntent, String resolvedType, String callingPackage,
24693                Bundle verificationBundle, int userId) {
24694            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24695                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24696                    userId);
24697        }
24698
24699        @Override
24700        public void grantEphemeralAccess(int userId, Intent intent,
24701                int targetAppId, int ephemeralAppId) {
24702            synchronized (mPackages) {
24703                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24704                        targetAppId, ephemeralAppId);
24705            }
24706        }
24707
24708        @Override
24709        public boolean isInstantAppInstallerComponent(ComponentName component) {
24710            synchronized (mPackages) {
24711                return mInstantAppInstallerActivity != null
24712                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24713            }
24714        }
24715
24716        @Override
24717        public void pruneInstantApps() {
24718            mInstantAppRegistry.pruneInstantApps();
24719        }
24720
24721        @Override
24722        public String getSetupWizardPackageName() {
24723            return mSetupWizardPackage;
24724        }
24725
24726        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24727            if (policy != null) {
24728                mExternalSourcesPolicy = policy;
24729            }
24730        }
24731
24732        @Override
24733        public boolean isPackagePersistent(String packageName) {
24734            synchronized (mPackages) {
24735                PackageParser.Package pkg = mPackages.get(packageName);
24736                return pkg != null
24737                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24738                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24739                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24740                        : false;
24741            }
24742        }
24743
24744        @Override
24745        public List<PackageInfo> getOverlayPackages(int userId) {
24746            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24747            synchronized (mPackages) {
24748                for (PackageParser.Package p : mPackages.values()) {
24749                    if (p.mOverlayTarget != null) {
24750                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24751                        if (pkg != null) {
24752                            overlayPackages.add(pkg);
24753                        }
24754                    }
24755                }
24756            }
24757            return overlayPackages;
24758        }
24759
24760        @Override
24761        public List<String> getTargetPackageNames(int userId) {
24762            List<String> targetPackages = new ArrayList<>();
24763            synchronized (mPackages) {
24764                for (PackageParser.Package p : mPackages.values()) {
24765                    if (p.mOverlayTarget == null) {
24766                        targetPackages.add(p.packageName);
24767                    }
24768                }
24769            }
24770            return targetPackages;
24771        }
24772
24773        @Override
24774        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24775                @Nullable List<String> overlayPackageNames) {
24776            synchronized (mPackages) {
24777                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24778                    Slog.e(TAG, "failed to find package " + targetPackageName);
24779                    return false;
24780                }
24781                ArrayList<String> overlayPaths = null;
24782                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24783                    final int N = overlayPackageNames.size();
24784                    overlayPaths = new ArrayList<>(N);
24785                    for (int i = 0; i < N; i++) {
24786                        final String packageName = overlayPackageNames.get(i);
24787                        final PackageParser.Package pkg = mPackages.get(packageName);
24788                        if (pkg == null) {
24789                            Slog.e(TAG, "failed to find package " + packageName);
24790                            return false;
24791                        }
24792                        overlayPaths.add(pkg.baseCodePath);
24793                    }
24794                }
24795
24796                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24797                ps.setOverlayPaths(overlayPaths, userId);
24798                return true;
24799            }
24800        }
24801
24802        @Override
24803        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24804                int flags, int userId) {
24805            return resolveIntentInternal(
24806                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24807        }
24808
24809        @Override
24810        public ResolveInfo resolveService(Intent intent, String resolvedType,
24811                int flags, int userId, int callingUid) {
24812            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24813        }
24814
24815        @Override
24816        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24817            synchronized (mPackages) {
24818                mIsolatedOwners.put(isolatedUid, ownerUid);
24819            }
24820        }
24821
24822        @Override
24823        public void removeIsolatedUid(int isolatedUid) {
24824            synchronized (mPackages) {
24825                mIsolatedOwners.delete(isolatedUid);
24826            }
24827        }
24828
24829        @Override
24830        public int getUidTargetSdkVersion(int uid) {
24831            synchronized (mPackages) {
24832                return getUidTargetSdkVersionLockedLPr(uid);
24833            }
24834        }
24835
24836        @Override
24837        public boolean canAccessInstantApps(int callingUid, int userId) {
24838            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24839        }
24840    }
24841
24842    @Override
24843    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24844        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24845        synchronized (mPackages) {
24846            final long identity = Binder.clearCallingIdentity();
24847            try {
24848                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24849                        packageNames, userId);
24850            } finally {
24851                Binder.restoreCallingIdentity(identity);
24852            }
24853        }
24854    }
24855
24856    @Override
24857    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24858        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24859        synchronized (mPackages) {
24860            final long identity = Binder.clearCallingIdentity();
24861            try {
24862                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24863                        packageNames, userId);
24864            } finally {
24865                Binder.restoreCallingIdentity(identity);
24866            }
24867        }
24868    }
24869
24870    private static void enforceSystemOrPhoneCaller(String tag) {
24871        int callingUid = Binder.getCallingUid();
24872        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24873            throw new SecurityException(
24874                    "Cannot call " + tag + " from UID " + callingUid);
24875        }
24876    }
24877
24878    boolean isHistoricalPackageUsageAvailable() {
24879        return mPackageUsage.isHistoricalPackageUsageAvailable();
24880    }
24881
24882    /**
24883     * Return a <b>copy</b> of the collection of packages known to the package manager.
24884     * @return A copy of the values of mPackages.
24885     */
24886    Collection<PackageParser.Package> getPackages() {
24887        synchronized (mPackages) {
24888            return new ArrayList<>(mPackages.values());
24889        }
24890    }
24891
24892    /**
24893     * Logs process start information (including base APK hash) to the security log.
24894     * @hide
24895     */
24896    @Override
24897    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24898            String apkFile, int pid) {
24899        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24900            return;
24901        }
24902        if (!SecurityLog.isLoggingEnabled()) {
24903            return;
24904        }
24905        Bundle data = new Bundle();
24906        data.putLong("startTimestamp", System.currentTimeMillis());
24907        data.putString("processName", processName);
24908        data.putInt("uid", uid);
24909        data.putString("seinfo", seinfo);
24910        data.putString("apkFile", apkFile);
24911        data.putInt("pid", pid);
24912        Message msg = mProcessLoggingHandler.obtainMessage(
24913                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24914        msg.setData(data);
24915        mProcessLoggingHandler.sendMessage(msg);
24916    }
24917
24918    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24919        return mCompilerStats.getPackageStats(pkgName);
24920    }
24921
24922    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24923        return getOrCreateCompilerPackageStats(pkg.packageName);
24924    }
24925
24926    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24927        return mCompilerStats.getOrCreatePackageStats(pkgName);
24928    }
24929
24930    public void deleteCompilerPackageStats(String pkgName) {
24931        mCompilerStats.deletePackageStats(pkgName);
24932    }
24933
24934    @Override
24935    public int getInstallReason(String packageName, int userId) {
24936        final int callingUid = Binder.getCallingUid();
24937        enforceCrossUserPermission(callingUid, userId,
24938                true /* requireFullPermission */, false /* checkShell */,
24939                "get install reason");
24940        synchronized (mPackages) {
24941            final PackageSetting ps = mSettings.mPackages.get(packageName);
24942            if (filterAppAccessLPr(ps, callingUid, userId)) {
24943                return PackageManager.INSTALL_REASON_UNKNOWN;
24944            }
24945            if (ps != null) {
24946                return ps.getInstallReason(userId);
24947            }
24948        }
24949        return PackageManager.INSTALL_REASON_UNKNOWN;
24950    }
24951
24952    @Override
24953    public boolean canRequestPackageInstalls(String packageName, int userId) {
24954        return canRequestPackageInstallsInternal(packageName, 0, userId,
24955                true /* throwIfPermNotDeclared*/);
24956    }
24957
24958    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24959            boolean throwIfPermNotDeclared) {
24960        int callingUid = Binder.getCallingUid();
24961        int uid = getPackageUid(packageName, 0, userId);
24962        if (callingUid != uid && callingUid != Process.ROOT_UID
24963                && callingUid != Process.SYSTEM_UID) {
24964            throw new SecurityException(
24965                    "Caller uid " + callingUid + " does not own package " + packageName);
24966        }
24967        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24968        if (info == null) {
24969            return false;
24970        }
24971        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24972            return false;
24973        }
24974        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24975        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24976        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24977            if (throwIfPermNotDeclared) {
24978                throw new SecurityException("Need to declare " + appOpPermission
24979                        + " to call this api");
24980            } else {
24981                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24982                return false;
24983            }
24984        }
24985        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24986            return false;
24987        }
24988        if (mExternalSourcesPolicy != null) {
24989            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24990            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24991                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24992            }
24993        }
24994        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24995    }
24996
24997    @Override
24998    public ComponentName getInstantAppResolverSettingsComponent() {
24999        return mInstantAppResolverSettingsComponent;
25000    }
25001
25002    @Override
25003    public ComponentName getInstantAppInstallerComponent() {
25004        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25005            return null;
25006        }
25007        return mInstantAppInstallerActivity == null
25008                ? null : mInstantAppInstallerActivity.getComponentName();
25009    }
25010
25011    @Override
25012    public String getInstantAppAndroidId(String packageName, int userId) {
25013        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25014                "getInstantAppAndroidId");
25015        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25016                true /* requireFullPermission */, false /* checkShell */,
25017                "getInstantAppAndroidId");
25018        // Make sure the target is an Instant App.
25019        if (!isInstantApp(packageName, userId)) {
25020            return null;
25021        }
25022        synchronized (mPackages) {
25023            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25024        }
25025    }
25026
25027    boolean canHaveOatDir(String packageName) {
25028        synchronized (mPackages) {
25029            PackageParser.Package p = mPackages.get(packageName);
25030            if (p == null) {
25031                return false;
25032            }
25033            return p.canHaveOatDir();
25034        }
25035    }
25036
25037    private String getOatDir(PackageParser.Package pkg) {
25038        if (!pkg.canHaveOatDir()) {
25039            return null;
25040        }
25041        File codePath = new File(pkg.codePath);
25042        if (codePath.isDirectory()) {
25043            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25044        }
25045        return null;
25046    }
25047
25048    void deleteOatArtifactsOfPackage(String packageName) {
25049        final String[] instructionSets;
25050        final List<String> codePaths;
25051        final String oatDir;
25052        final PackageParser.Package pkg;
25053        synchronized (mPackages) {
25054            pkg = mPackages.get(packageName);
25055        }
25056        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25057        codePaths = pkg.getAllCodePaths();
25058        oatDir = getOatDir(pkg);
25059
25060        for (String codePath : codePaths) {
25061            for (String isa : instructionSets) {
25062                try {
25063                    mInstaller.deleteOdex(codePath, isa, oatDir);
25064                } catch (InstallerException e) {
25065                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25066                }
25067            }
25068        }
25069    }
25070
25071    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25072        Set<String> unusedPackages = new HashSet<>();
25073        long currentTimeInMillis = System.currentTimeMillis();
25074        synchronized (mPackages) {
25075            for (PackageParser.Package pkg : mPackages.values()) {
25076                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25077                if (ps == null) {
25078                    continue;
25079                }
25080                PackageDexUsage.PackageUseInfo packageUseInfo = getDexManager().getPackageUseInfo(
25081                        pkg.packageName);
25082                if (PackageManagerServiceUtils
25083                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25084                                downgradeTimeThresholdMillis, packageUseInfo,
25085                                pkg.getLatestPackageUseTimeInMills(),
25086                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25087                    unusedPackages.add(pkg.packageName);
25088                }
25089            }
25090        }
25091        return unusedPackages;
25092    }
25093}
25094
25095interface PackageSender {
25096    void sendPackageBroadcast(final String action, final String pkg,
25097        final Bundle extras, final int flags, final String targetPkg,
25098        final IIntentReceiver finishedReceiver, final int[] userIds);
25099    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
25100        int appId, int... userIds);
25101}
25102