PackageManagerService.java revision 66a285d9d7afe197a5a562525641400db80edcef
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
66import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
67import static android.content.pm.PackageManager.MATCH_ALL;
68import static android.content.pm.PackageManager.MATCH_ANY_USER;
69import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
71import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
72import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
73import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
74import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
75import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
76import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
77import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
78import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
79import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
80import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
92import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
93import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
94import static com.android.internal.util.ArrayUtils.appendInt;
95import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
98import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
99import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
105import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
106
107import android.Manifest;
108import android.annotation.IntDef;
109import android.annotation.NonNull;
110import android.annotation.Nullable;
111import android.app.ActivityManager;
112import android.app.AppOpsManager;
113import android.app.IActivityManager;
114import android.app.ResourcesManager;
115import android.app.admin.IDevicePolicyManager;
116import android.app.admin.SecurityLog;
117import android.app.backup.IBackupManager;
118import android.content.BroadcastReceiver;
119import android.content.ComponentName;
120import android.content.ContentResolver;
121import android.content.Context;
122import android.content.IIntentReceiver;
123import android.content.Intent;
124import android.content.IntentFilter;
125import android.content.IntentSender;
126import android.content.IntentSender.SendIntentException;
127import android.content.ServiceConnection;
128import android.content.pm.ActivityInfo;
129import android.content.pm.ApplicationInfo;
130import android.content.pm.AppsQueryHelper;
131import android.content.pm.AuxiliaryResolveInfo;
132import android.content.pm.ChangedPackages;
133import android.content.pm.FallbackCategoryProvider;
134import android.content.pm.FeatureInfo;
135import android.content.pm.IDexModuleRegisterCallback;
136import android.content.pm.IOnPermissionsChangeListener;
137import android.content.pm.IPackageDataObserver;
138import android.content.pm.IPackageDeleteObserver;
139import android.content.pm.IPackageDeleteObserver2;
140import android.content.pm.IPackageInstallObserver2;
141import android.content.pm.IPackageInstaller;
142import android.content.pm.IPackageManager;
143import android.content.pm.IPackageMoveObserver;
144import android.content.pm.IPackageStatsObserver;
145import android.content.pm.InstantAppInfo;
146import android.content.pm.InstantAppRequest;
147import android.content.pm.InstantAppResolveInfo;
148import android.content.pm.InstrumentationInfo;
149import android.content.pm.IntentFilterVerificationInfo;
150import android.content.pm.KeySet;
151import android.content.pm.PackageCleanItem;
152import android.content.pm.PackageInfo;
153import android.content.pm.PackageInfoLite;
154import android.content.pm.PackageInstaller;
155import android.content.pm.PackageManager;
156import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
157import android.content.pm.PackageManagerInternal;
158import android.content.pm.PackageParser;
159import android.content.pm.PackageParser.ActivityIntentInfo;
160import android.content.pm.PackageParser.PackageLite;
161import android.content.pm.PackageParser.PackageParserException;
162import android.content.pm.PackageStats;
163import android.content.pm.PackageUserState;
164import android.content.pm.ParceledListSlice;
165import android.content.pm.PermissionGroupInfo;
166import android.content.pm.PermissionInfo;
167import android.content.pm.ProviderInfo;
168import android.content.pm.ResolveInfo;
169import android.content.pm.ServiceInfo;
170import android.content.pm.SharedLibraryInfo;
171import android.content.pm.Signature;
172import android.content.pm.UserInfo;
173import android.content.pm.VerifierDeviceIdentity;
174import android.content.pm.VerifierInfo;
175import android.content.pm.VersionedPackage;
176import android.content.res.Resources;
177import android.database.ContentObserver;
178import android.graphics.Bitmap;
179import android.hardware.display.DisplayManager;
180import android.net.Uri;
181import android.os.Binder;
182import android.os.Build;
183import android.os.Bundle;
184import android.os.Debug;
185import android.os.Environment;
186import android.os.Environment.UserEnvironment;
187import android.os.FileUtils;
188import android.os.Handler;
189import android.os.IBinder;
190import android.os.Looper;
191import android.os.Message;
192import android.os.Parcel;
193import android.os.ParcelFileDescriptor;
194import android.os.PatternMatcher;
195import android.os.Process;
196import android.os.RemoteCallbackList;
197import android.os.RemoteException;
198import android.os.ResultReceiver;
199import android.os.SELinux;
200import android.os.ServiceManager;
201import android.os.ShellCallback;
202import android.os.SystemClock;
203import android.os.SystemProperties;
204import android.os.Trace;
205import android.os.UserHandle;
206import android.os.UserManager;
207import android.os.UserManagerInternal;
208import android.os.storage.IStorageManager;
209import android.os.storage.StorageEventListener;
210import android.os.storage.StorageManager;
211import android.os.storage.StorageManagerInternal;
212import android.os.storage.VolumeInfo;
213import android.os.storage.VolumeRecord;
214import android.provider.Settings.Global;
215import android.provider.Settings.Secure;
216import android.security.KeyStore;
217import android.security.SystemKeyStore;
218import android.service.pm.PackageServiceDumpProto;
219import android.system.ErrnoException;
220import android.system.Os;
221import android.text.TextUtils;
222import android.text.format.DateUtils;
223import android.util.ArrayMap;
224import android.util.ArraySet;
225import android.util.Base64;
226import android.util.BootTimingsTraceLog;
227import android.util.DisplayMetrics;
228import android.util.EventLog;
229import android.util.ExceptionUtils;
230import android.util.Log;
231import android.util.LogPrinter;
232import android.util.MathUtils;
233import android.util.PackageUtils;
234import android.util.Pair;
235import android.util.PrintStreamPrinter;
236import android.util.Slog;
237import android.util.SparseArray;
238import android.util.SparseBooleanArray;
239import android.util.SparseIntArray;
240import android.util.Xml;
241import android.util.jar.StrictJarFile;
242import android.util.proto.ProtoOutputStream;
243import android.view.Display;
244
245import com.android.internal.R;
246import com.android.internal.annotations.GuardedBy;
247import com.android.internal.app.IMediaContainerService;
248import com.android.internal.app.ResolverActivity;
249import com.android.internal.content.NativeLibraryHelper;
250import com.android.internal.content.PackageHelper;
251import com.android.internal.logging.MetricsLogger;
252import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
253import com.android.internal.os.IParcelFileDescriptorFactory;
254import com.android.internal.os.RoSystemProperties;
255import com.android.internal.os.SomeArgs;
256import com.android.internal.os.Zygote;
257import com.android.internal.telephony.CarrierAppUtils;
258import com.android.internal.util.ArrayUtils;
259import com.android.internal.util.ConcurrentUtils;
260import com.android.internal.util.DumpUtils;
261import com.android.internal.util.FastPrintWriter;
262import com.android.internal.util.FastXmlSerializer;
263import com.android.internal.util.IndentingPrintWriter;
264import com.android.internal.util.Preconditions;
265import com.android.internal.util.XmlUtils;
266import com.android.server.AttributeCache;
267import com.android.server.DeviceIdleController;
268import com.android.server.EventLogTags;
269import com.android.server.FgThread;
270import com.android.server.IntentResolver;
271import com.android.server.LocalServices;
272import com.android.server.LockGuard;
273import com.android.server.ServiceThread;
274import com.android.server.SystemConfig;
275import com.android.server.SystemServerInitThreadPool;
276import com.android.server.Watchdog;
277import com.android.server.net.NetworkPolicyManagerInternal;
278import com.android.server.pm.Installer.InstallerException;
279import com.android.server.pm.PermissionsState.PermissionState;
280import com.android.server.pm.Settings.DatabaseVersion;
281import com.android.server.pm.Settings.VersionInfo;
282import com.android.server.pm.dex.DexManager;
283import com.android.server.pm.dex.DexoptOptions;
284import com.android.server.pm.dex.PackageDexUsage;
285import com.android.server.storage.DeviceStorageMonitorInternal;
286
287import dalvik.system.CloseGuard;
288import dalvik.system.DexFile;
289import dalvik.system.VMRuntime;
290
291import libcore.io.IoUtils;
292import libcore.util.EmptyArray;
293
294import org.xmlpull.v1.XmlPullParser;
295import org.xmlpull.v1.XmlPullParserException;
296import org.xmlpull.v1.XmlSerializer;
297
298import java.io.BufferedOutputStream;
299import java.io.BufferedReader;
300import java.io.ByteArrayInputStream;
301import java.io.ByteArrayOutputStream;
302import java.io.File;
303import java.io.FileDescriptor;
304import java.io.FileInputStream;
305import java.io.FileOutputStream;
306import java.io.FileReader;
307import java.io.FilenameFilter;
308import java.io.IOException;
309import java.io.PrintWriter;
310import java.lang.annotation.Retention;
311import java.lang.annotation.RetentionPolicy;
312import java.nio.charset.StandardCharsets;
313import java.security.DigestInputStream;
314import java.security.MessageDigest;
315import java.security.NoSuchAlgorithmException;
316import java.security.PublicKey;
317import java.security.SecureRandom;
318import java.security.cert.Certificate;
319import java.security.cert.CertificateEncodingException;
320import java.security.cert.CertificateException;
321import java.text.SimpleDateFormat;
322import java.util.ArrayList;
323import java.util.Arrays;
324import java.util.Collection;
325import java.util.Collections;
326import java.util.Comparator;
327import java.util.Date;
328import java.util.HashMap;
329import java.util.HashSet;
330import java.util.Iterator;
331import java.util.LinkedHashSet;
332import java.util.List;
333import java.util.Map;
334import java.util.Objects;
335import java.util.Set;
336import java.util.concurrent.CountDownLatch;
337import java.util.concurrent.Future;
338import java.util.concurrent.TimeUnit;
339import java.util.concurrent.atomic.AtomicBoolean;
340import java.util.concurrent.atomic.AtomicInteger;
341
342/**
343 * Keep track of all those APKs everywhere.
344 * <p>
345 * Internally there are two important locks:
346 * <ul>
347 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
348 * and other related state. It is a fine-grained lock that should only be held
349 * momentarily, as it's one of the most contended locks in the system.
350 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
351 * operations typically involve heavy lifting of application data on disk. Since
352 * {@code installd} is single-threaded, and it's operations can often be slow,
353 * this lock should never be acquired while already holding {@link #mPackages}.
354 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
355 * holding {@link #mInstallLock}.
356 * </ul>
357 * Many internal methods rely on the caller to hold the appropriate locks, and
358 * this contract is expressed through method name suffixes:
359 * <ul>
360 * <li>fooLI(): the caller must hold {@link #mInstallLock}
361 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
362 * being modified must be frozen
363 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
364 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
365 * </ul>
366 * <p>
367 * Because this class is very central to the platform's security; please run all
368 * CTS and unit tests whenever making modifications:
369 *
370 * <pre>
371 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
372 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
373 * </pre>
374 */
375public class PackageManagerService extends IPackageManager.Stub
376        implements PackageSender {
377    static final String TAG = "PackageManager";
378    static final boolean DEBUG_SETTINGS = false;
379    static final boolean DEBUG_PREFERRED = false;
380    static final boolean DEBUG_UPGRADE = false;
381    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
382    private static final boolean DEBUG_BACKUP = false;
383    private static final boolean DEBUG_INSTALL = false;
384    private static final boolean DEBUG_REMOVE = false;
385    private static final boolean DEBUG_BROADCASTS = false;
386    private static final boolean DEBUG_SHOW_INFO = false;
387    private static final boolean DEBUG_PACKAGE_INFO = false;
388    private static final boolean DEBUG_INTENT_MATCHING = false;
389    private static final boolean DEBUG_PACKAGE_SCANNING = false;
390    private static final boolean DEBUG_VERIFY = false;
391    private static final boolean DEBUG_FILTERS = false;
392    private static final boolean DEBUG_PERMISSIONS = false;
393    private static final boolean DEBUG_SHARED_LIBRARIES = false;
394
395    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
396    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
397    // user, but by default initialize to this.
398    public static final boolean DEBUG_DEXOPT = false;
399
400    private static final boolean DEBUG_ABI_SELECTION = false;
401    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
402    private static final boolean DEBUG_TRIAGED_MISSING = false;
403    private static final boolean DEBUG_APP_DATA = false;
404
405    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
406    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
407
408    private static final boolean HIDE_EPHEMERAL_APIS = false;
409
410    private static final boolean ENABLE_FREE_CACHE_V2 =
411            SystemProperties.getBoolean("fw.free_cache_v2", true);
412
413    private static final int RADIO_UID = Process.PHONE_UID;
414    private static final int LOG_UID = Process.LOG_UID;
415    private static final int NFC_UID = Process.NFC_UID;
416    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
417    private static final int SHELL_UID = Process.SHELL_UID;
418
419    // Cap the size of permission trees that 3rd party apps can define
420    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
421
422    // Suffix used during package installation when copying/moving
423    // package apks to install directory.
424    private static final String INSTALL_PACKAGE_SUFFIX = "-";
425
426    static final int SCAN_NO_DEX = 1<<1;
427    static final int SCAN_FORCE_DEX = 1<<2;
428    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
429    static final int SCAN_NEW_INSTALL = 1<<4;
430    static final int SCAN_UPDATE_TIME = 1<<5;
431    static final int SCAN_BOOTING = 1<<6;
432    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
433    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
434    static final int SCAN_REPLACING = 1<<9;
435    static final int SCAN_REQUIRE_KNOWN = 1<<10;
436    static final int SCAN_MOVE = 1<<11;
437    static final int SCAN_INITIAL = 1<<12;
438    static final int SCAN_CHECK_ONLY = 1<<13;
439    static final int SCAN_DONT_KILL_APP = 1<<14;
440    static final int SCAN_IGNORE_FROZEN = 1<<15;
441    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
442    static final int SCAN_AS_INSTANT_APP = 1<<17;
443    static final int SCAN_AS_FULL_APP = 1<<18;
444    /** Should not be with the scan flags */
445    static final int FLAGS_REMOVE_CHATTY = 1<<31;
446
447    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
448
449    private static final int[] EMPTY_INT_ARRAY = new int[0];
450
451    private static final int TYPE_UNKNOWN = 0;
452    private static final int TYPE_ACTIVITY = 1;
453    private static final int TYPE_RECEIVER = 2;
454    private static final int TYPE_SERVICE = 3;
455    private static final int TYPE_PROVIDER = 4;
456    @IntDef(prefix = { "TYPE_" }, value = {
457            TYPE_UNKNOWN,
458            TYPE_ACTIVITY,
459            TYPE_RECEIVER,
460            TYPE_SERVICE,
461            TYPE_PROVIDER,
462    })
463    @Retention(RetentionPolicy.SOURCE)
464    public @interface ComponentType {}
465
466    /**
467     * Timeout (in milliseconds) after which the watchdog should declare that
468     * our handler thread is wedged.  The usual default for such things is one
469     * minute but we sometimes do very lengthy I/O operations on this thread,
470     * such as installing multi-gigabyte applications, so ours needs to be longer.
471     */
472    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
473
474    /**
475     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
476     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
477     * settings entry if available, otherwise we use the hardcoded default.  If it's been
478     * more than this long since the last fstrim, we force one during the boot sequence.
479     *
480     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
481     * one gets run at the next available charging+idle time.  This final mandatory
482     * no-fstrim check kicks in only of the other scheduling criteria is never met.
483     */
484    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
485
486    /**
487     * Whether verification is enabled by default.
488     */
489    private static final boolean DEFAULT_VERIFY_ENABLE = true;
490
491    /**
492     * The default maximum time to wait for the verification agent to return in
493     * milliseconds.
494     */
495    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
496
497    /**
498     * The default response for package verification timeout.
499     *
500     * This can be either PackageManager.VERIFICATION_ALLOW or
501     * PackageManager.VERIFICATION_REJECT.
502     */
503    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
504
505    static final String PLATFORM_PACKAGE_NAME = "android";
506
507    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
508
509    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
510            DEFAULT_CONTAINER_PACKAGE,
511            "com.android.defcontainer.DefaultContainerService");
512
513    private static final String KILL_APP_REASON_GIDS_CHANGED =
514            "permission grant or revoke changed gids";
515
516    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
517            "permissions revoked";
518
519    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
520
521    private static final String PACKAGE_SCHEME = "package";
522
523    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
524
525    /** Permission grant: not grant the permission. */
526    private static final int GRANT_DENIED = 1;
527
528    /** Permission grant: grant the permission as an install permission. */
529    private static final int GRANT_INSTALL = 2;
530
531    /** Permission grant: grant the permission as a runtime one. */
532    private static final int GRANT_RUNTIME = 3;
533
534    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
535    private static final int GRANT_UPGRADE = 4;
536
537    /** Canonical intent used to identify what counts as a "web browser" app */
538    private static final Intent sBrowserIntent;
539    static {
540        sBrowserIntent = new Intent();
541        sBrowserIntent.setAction(Intent.ACTION_VIEW);
542        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
543        sBrowserIntent.setData(Uri.parse("http:"));
544    }
545
546    /**
547     * The set of all protected actions [i.e. those actions for which a high priority
548     * intent filter is disallowed].
549     */
550    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
551    static {
552        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
553        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
554        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
555        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
556    }
557
558    // Compilation reasons.
559    public static final int REASON_FIRST_BOOT = 0;
560    public static final int REASON_BOOT = 1;
561    public static final int REASON_INSTALL = 2;
562    public static final int REASON_BACKGROUND_DEXOPT = 3;
563    public static final int REASON_AB_OTA = 4;
564    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
565    public static final int REASON_SHARED = 6;
566
567    public static final int REASON_LAST = REASON_SHARED;
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    boolean mFirstBoot;
733
734    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
735
736    // System configuration read by SystemConfig.
737    final int[] mGlobalGids;
738    final SparseArray<ArraySet<String>> mSystemPermissions;
739    @GuardedBy("mAvailableFeatures")
740    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
741
742    // If mac_permissions.xml was found for seinfo labeling.
743    boolean mFoundPolicyFile;
744
745    private final InstantAppRegistry mInstantAppRegistry;
746
747    @GuardedBy("mPackages")
748    int mChangedPackagesSequenceNumber;
749    /**
750     * List of changed [installed, removed or updated] packages.
751     * mapping from user id -> sequence number -> package name
752     */
753    @GuardedBy("mPackages")
754    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
755    /**
756     * The sequence number of the last change to a package.
757     * mapping from user id -> package name -> sequence number
758     */
759    @GuardedBy("mPackages")
760    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
761
762    class PackageParserCallback implements PackageParser.Callback {
763        @Override public final boolean hasFeature(String feature) {
764            return PackageManagerService.this.hasSystemFeature(feature, 0);
765        }
766
767        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
768                Collection<PackageParser.Package> allPackages, String targetPackageName) {
769            List<PackageParser.Package> overlayPackages = null;
770            for (PackageParser.Package p : allPackages) {
771                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
772                    if (overlayPackages == null) {
773                        overlayPackages = new ArrayList<PackageParser.Package>();
774                    }
775                    overlayPackages.add(p);
776                }
777            }
778            if (overlayPackages != null) {
779                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
780                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
781                        return p1.mOverlayPriority - p2.mOverlayPriority;
782                    }
783                };
784                Collections.sort(overlayPackages, cmp);
785            }
786            return overlayPackages;
787        }
788
789        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
790                String targetPackageName, String targetPath) {
791            if ("android".equals(targetPackageName)) {
792                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
793                // native AssetManager.
794                return null;
795            }
796            List<PackageParser.Package> overlayPackages =
797                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
798            if (overlayPackages == null || overlayPackages.isEmpty()) {
799                return null;
800            }
801            List<String> overlayPathList = null;
802            for (PackageParser.Package overlayPackage : overlayPackages) {
803                if (targetPath == null) {
804                    if (overlayPathList == null) {
805                        overlayPathList = new ArrayList<String>();
806                    }
807                    overlayPathList.add(overlayPackage.baseCodePath);
808                    continue;
809                }
810
811                try {
812                    // Creates idmaps for system to parse correctly the Android manifest of the
813                    // target package.
814                    //
815                    // OverlayManagerService will update each of them with a correct gid from its
816                    // target package app id.
817                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
818                            UserHandle.getSharedAppGid(
819                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
820                    if (overlayPathList == null) {
821                        overlayPathList = new ArrayList<String>();
822                    }
823                    overlayPathList.add(overlayPackage.baseCodePath);
824                } catch (InstallerException e) {
825                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
826                            overlayPackage.baseCodePath);
827                }
828            }
829            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
830        }
831
832        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
833            synchronized (mPackages) {
834                return getStaticOverlayPathsLocked(
835                        mPackages.values(), targetPackageName, targetPath);
836            }
837        }
838
839        @Override public final String[] getOverlayApks(String targetPackageName) {
840            return getStaticOverlayPaths(targetPackageName, null);
841        }
842
843        @Override public final String[] getOverlayPaths(String targetPackageName,
844                String targetPath) {
845            return getStaticOverlayPaths(targetPackageName, targetPath);
846        }
847    };
848
849    class ParallelPackageParserCallback extends PackageParserCallback {
850        List<PackageParser.Package> mOverlayPackages = null;
851
852        void findStaticOverlayPackages() {
853            synchronized (mPackages) {
854                for (PackageParser.Package p : mPackages.values()) {
855                    if (p.mIsStaticOverlay) {
856                        if (mOverlayPackages == null) {
857                            mOverlayPackages = new ArrayList<PackageParser.Package>();
858                        }
859                        mOverlayPackages.add(p);
860                    }
861                }
862            }
863        }
864
865        @Override
866        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
867            // We can trust mOverlayPackages without holding mPackages because package uninstall
868            // can't happen while running parallel parsing.
869            // Moreover holding mPackages on each parsing thread causes dead-lock.
870            return mOverlayPackages == null ? null :
871                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
872        }
873    }
874
875    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
876    final ParallelPackageParserCallback mParallelPackageParserCallback =
877            new ParallelPackageParserCallback();
878
879    public static final class SharedLibraryEntry {
880        public final @Nullable String path;
881        public final @Nullable String apk;
882        public final @NonNull SharedLibraryInfo info;
883
884        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
885                String declaringPackageName, int declaringPackageVersionCode) {
886            path = _path;
887            apk = _apk;
888            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
889                    declaringPackageName, declaringPackageVersionCode), null);
890        }
891    }
892
893    // Currently known shared libraries.
894    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
895    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
896            new ArrayMap<>();
897
898    // All available activities, for your resolving pleasure.
899    final ActivityIntentResolver mActivities =
900            new ActivityIntentResolver();
901
902    // All available receivers, for your resolving pleasure.
903    final ActivityIntentResolver mReceivers =
904            new ActivityIntentResolver();
905
906    // All available services, for your resolving pleasure.
907    final ServiceIntentResolver mServices = new ServiceIntentResolver();
908
909    // All available providers, for your resolving pleasure.
910    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
911
912    // Mapping from provider base names (first directory in content URI codePath)
913    // to the provider information.
914    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
915            new ArrayMap<String, PackageParser.Provider>();
916
917    // Mapping from instrumentation class names to info about them.
918    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
919            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
920
921    // Mapping from permission names to info about them.
922    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
923            new ArrayMap<String, PackageParser.PermissionGroup>();
924
925    // Packages whose data we have transfered into another package, thus
926    // should no longer exist.
927    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
928
929    // Broadcast actions that are only available to the system.
930    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
931
932    /** List of packages waiting for verification. */
933    final SparseArray<PackageVerificationState> mPendingVerification
934            = new SparseArray<PackageVerificationState>();
935
936    /** Set of packages associated with each app op permission. */
937    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
938
939    final PackageInstallerService mInstallerService;
940
941    private final PackageDexOptimizer mPackageDexOptimizer;
942    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
943    // is used by other apps).
944    private final DexManager mDexManager;
945
946    private AtomicInteger mNextMoveId = new AtomicInteger();
947    private final MoveCallbacks mMoveCallbacks;
948
949    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
950
951    // Cache of users who need badging.
952    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
953
954    /** Token for keys in mPendingVerification. */
955    private int mPendingVerificationToken = 0;
956
957    volatile boolean mSystemReady;
958    volatile boolean mSafeMode;
959    volatile boolean mHasSystemUidErrors;
960    private volatile boolean mEphemeralAppsDisabled;
961
962    ApplicationInfo mAndroidApplication;
963    final ActivityInfo mResolveActivity = new ActivityInfo();
964    final ResolveInfo mResolveInfo = new ResolveInfo();
965    ComponentName mResolveComponentName;
966    PackageParser.Package mPlatformPackage;
967    ComponentName mCustomResolverComponentName;
968
969    boolean mResolverReplaced = false;
970
971    private final @Nullable ComponentName mIntentFilterVerifierComponent;
972    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
973
974    private int mIntentFilterVerificationToken = 0;
975
976    /** The service connection to the ephemeral resolver */
977    final EphemeralResolverConnection mInstantAppResolverConnection;
978    /** Component used to show resolver settings for Instant Apps */
979    final ComponentName mInstantAppResolverSettingsComponent;
980
981    /** Activity used to install instant applications */
982    ActivityInfo mInstantAppInstallerActivity;
983    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
984
985    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
986            = new SparseArray<IntentFilterVerificationState>();
987
988    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
989
990    // List of packages names to keep cached, even if they are uninstalled for all users
991    private List<String> mKeepUninstalledPackages;
992
993    private UserManagerInternal mUserManagerInternal;
994
995    private DeviceIdleController.LocalService mDeviceIdleController;
996
997    private File mCacheDir;
998
999    private ArraySet<String> mPrivappPermissionsViolations;
1000
1001    private Future<?> mPrepareAppDataFuture;
1002
1003    private static class IFVerificationParams {
1004        PackageParser.Package pkg;
1005        boolean replacing;
1006        int userId;
1007        int verifierUid;
1008
1009        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1010                int _userId, int _verifierUid) {
1011            pkg = _pkg;
1012            replacing = _replacing;
1013            userId = _userId;
1014            replacing = _replacing;
1015            verifierUid = _verifierUid;
1016        }
1017    }
1018
1019    private interface IntentFilterVerifier<T extends IntentFilter> {
1020        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1021                                               T filter, String packageName);
1022        void startVerifications(int userId);
1023        void receiveVerificationResponse(int verificationId);
1024    }
1025
1026    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1027        private Context mContext;
1028        private ComponentName mIntentFilterVerifierComponent;
1029        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1030
1031        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1032            mContext = context;
1033            mIntentFilterVerifierComponent = verifierComponent;
1034        }
1035
1036        private String getDefaultScheme() {
1037            return IntentFilter.SCHEME_HTTPS;
1038        }
1039
1040        @Override
1041        public void startVerifications(int userId) {
1042            // Launch verifications requests
1043            int count = mCurrentIntentFilterVerifications.size();
1044            for (int n=0; n<count; n++) {
1045                int verificationId = mCurrentIntentFilterVerifications.get(n);
1046                final IntentFilterVerificationState ivs =
1047                        mIntentFilterVerificationStates.get(verificationId);
1048
1049                String packageName = ivs.getPackageName();
1050
1051                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1052                final int filterCount = filters.size();
1053                ArraySet<String> domainsSet = new ArraySet<>();
1054                for (int m=0; m<filterCount; m++) {
1055                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1056                    domainsSet.addAll(filter.getHostsList());
1057                }
1058                synchronized (mPackages) {
1059                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1060                            packageName, domainsSet) != null) {
1061                        scheduleWriteSettingsLocked();
1062                    }
1063                }
1064                sendVerificationRequest(userId, verificationId, ivs);
1065            }
1066            mCurrentIntentFilterVerifications.clear();
1067        }
1068
1069        private void sendVerificationRequest(int userId, int verificationId,
1070                IntentFilterVerificationState ivs) {
1071
1072            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1073            verificationIntent.putExtra(
1074                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1075                    verificationId);
1076            verificationIntent.putExtra(
1077                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1078                    getDefaultScheme());
1079            verificationIntent.putExtra(
1080                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1081                    ivs.getHostsString());
1082            verificationIntent.putExtra(
1083                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1084                    ivs.getPackageName());
1085            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1086            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1087
1088            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1089            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1090                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1091                    userId, false, "intent filter verifier");
1092
1093            UserHandle user = new UserHandle(userId);
1094            mContext.sendBroadcastAsUser(verificationIntent, user);
1095            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1096                    "Sending IntentFilter verification broadcast");
1097        }
1098
1099        public void receiveVerificationResponse(int verificationId) {
1100            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1101
1102            final boolean verified = ivs.isVerified();
1103
1104            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1105            final int count = filters.size();
1106            if (DEBUG_DOMAIN_VERIFICATION) {
1107                Slog.i(TAG, "Received verification response " + verificationId
1108                        + " for " + count + " filters, verified=" + verified);
1109            }
1110            for (int n=0; n<count; n++) {
1111                PackageParser.ActivityIntentInfo filter = filters.get(n);
1112                filter.setVerified(verified);
1113
1114                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1115                        + " verified with result:" + verified + " and hosts:"
1116                        + ivs.getHostsString());
1117            }
1118
1119            mIntentFilterVerificationStates.remove(verificationId);
1120
1121            final String packageName = ivs.getPackageName();
1122            IntentFilterVerificationInfo ivi = null;
1123
1124            synchronized (mPackages) {
1125                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1126            }
1127            if (ivi == null) {
1128                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1129                        + verificationId + " packageName:" + packageName);
1130                return;
1131            }
1132            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1133                    "Updating IntentFilterVerificationInfo for package " + packageName
1134                            +" verificationId:" + verificationId);
1135
1136            synchronized (mPackages) {
1137                if (verified) {
1138                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1139                } else {
1140                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1141                }
1142                scheduleWriteSettingsLocked();
1143
1144                final int userId = ivs.getUserId();
1145                if (userId != UserHandle.USER_ALL) {
1146                    final int userStatus =
1147                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1148
1149                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1150                    boolean needUpdate = false;
1151
1152                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1153                    // already been set by the User thru the Disambiguation dialog
1154                    switch (userStatus) {
1155                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1156                            if (verified) {
1157                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1158                            } else {
1159                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1160                            }
1161                            needUpdate = true;
1162                            break;
1163
1164                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1165                            if (verified) {
1166                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1167                                needUpdate = true;
1168                            }
1169                            break;
1170
1171                        default:
1172                            // Nothing to do
1173                    }
1174
1175                    if (needUpdate) {
1176                        mSettings.updateIntentFilterVerificationStatusLPw(
1177                                packageName, updatedStatus, userId);
1178                        scheduleWritePackageRestrictionsLocked(userId);
1179                    }
1180                }
1181            }
1182        }
1183
1184        @Override
1185        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1186                    ActivityIntentInfo filter, String packageName) {
1187            if (!hasValidDomains(filter)) {
1188                return false;
1189            }
1190            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1191            if (ivs == null) {
1192                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1193                        packageName);
1194            }
1195            if (DEBUG_DOMAIN_VERIFICATION) {
1196                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1197            }
1198            ivs.addFilter(filter);
1199            return true;
1200        }
1201
1202        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1203                int userId, int verificationId, String packageName) {
1204            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1205                    verifierUid, userId, packageName);
1206            ivs.setPendingState();
1207            synchronized (mPackages) {
1208                mIntentFilterVerificationStates.append(verificationId, ivs);
1209                mCurrentIntentFilterVerifications.add(verificationId);
1210            }
1211            return ivs;
1212        }
1213    }
1214
1215    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1216        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1217                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1218                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1219    }
1220
1221    // Set of pending broadcasts for aggregating enable/disable of components.
1222    static class PendingPackageBroadcasts {
1223        // for each user id, a map of <package name -> components within that package>
1224        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1225
1226        public PendingPackageBroadcasts() {
1227            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1228        }
1229
1230        public ArrayList<String> get(int userId, String packageName) {
1231            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1232            return packages.get(packageName);
1233        }
1234
1235        public void put(int userId, String packageName, ArrayList<String> components) {
1236            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1237            packages.put(packageName, components);
1238        }
1239
1240        public void remove(int userId, String packageName) {
1241            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1242            if (packages != null) {
1243                packages.remove(packageName);
1244            }
1245        }
1246
1247        public void remove(int userId) {
1248            mUidMap.remove(userId);
1249        }
1250
1251        public int userIdCount() {
1252            return mUidMap.size();
1253        }
1254
1255        public int userIdAt(int n) {
1256            return mUidMap.keyAt(n);
1257        }
1258
1259        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1260            return mUidMap.get(userId);
1261        }
1262
1263        public int size() {
1264            // total number of pending broadcast entries across all userIds
1265            int num = 0;
1266            for (int i = 0; i< mUidMap.size(); i++) {
1267                num += mUidMap.valueAt(i).size();
1268            }
1269            return num;
1270        }
1271
1272        public void clear() {
1273            mUidMap.clear();
1274        }
1275
1276        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1277            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1278            if (map == null) {
1279                map = new ArrayMap<String, ArrayList<String>>();
1280                mUidMap.put(userId, map);
1281            }
1282            return map;
1283        }
1284    }
1285    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1286
1287    // Service Connection to remote media container service to copy
1288    // package uri's from external media onto secure containers
1289    // or internal storage.
1290    private IMediaContainerService mContainerService = null;
1291
1292    static final int SEND_PENDING_BROADCAST = 1;
1293    static final int MCS_BOUND = 3;
1294    static final int END_COPY = 4;
1295    static final int INIT_COPY = 5;
1296    static final int MCS_UNBIND = 6;
1297    static final int START_CLEANING_PACKAGE = 7;
1298    static final int FIND_INSTALL_LOC = 8;
1299    static final int POST_INSTALL = 9;
1300    static final int MCS_RECONNECT = 10;
1301    static final int MCS_GIVE_UP = 11;
1302    static final int UPDATED_MEDIA_STATUS = 12;
1303    static final int WRITE_SETTINGS = 13;
1304    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1305    static final int PACKAGE_VERIFIED = 15;
1306    static final int CHECK_PENDING_VERIFICATION = 16;
1307    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1308    static final int INTENT_FILTER_VERIFIED = 18;
1309    static final int WRITE_PACKAGE_LIST = 19;
1310    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1311
1312    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1313
1314    // Delay time in millisecs
1315    static final int BROADCAST_DELAY = 10 * 1000;
1316
1317    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1318            2 * 60 * 60 * 1000L; /* two hours */
1319
1320    static UserManagerService sUserManager;
1321
1322    // Stores a list of users whose package restrictions file needs to be updated
1323    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1324
1325    final private DefaultContainerConnection mDefContainerConn =
1326            new DefaultContainerConnection();
1327    class DefaultContainerConnection implements ServiceConnection {
1328        public void onServiceConnected(ComponentName name, IBinder service) {
1329            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1330            final IMediaContainerService imcs = IMediaContainerService.Stub
1331                    .asInterface(Binder.allowBlocking(service));
1332            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1333        }
1334
1335        public void onServiceDisconnected(ComponentName name) {
1336            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1337        }
1338    }
1339
1340    // Recordkeeping of restore-after-install operations that are currently in flight
1341    // between the Package Manager and the Backup Manager
1342    static class PostInstallData {
1343        public InstallArgs args;
1344        public PackageInstalledInfo res;
1345
1346        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1347            args = _a;
1348            res = _r;
1349        }
1350    }
1351
1352    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1353    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1354
1355    // XML tags for backup/restore of various bits of state
1356    private static final String TAG_PREFERRED_BACKUP = "pa";
1357    private static final String TAG_DEFAULT_APPS = "da";
1358    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1359
1360    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1361    private static final String TAG_ALL_GRANTS = "rt-grants";
1362    private static final String TAG_GRANT = "grant";
1363    private static final String ATTR_PACKAGE_NAME = "pkg";
1364
1365    private static final String TAG_PERMISSION = "perm";
1366    private static final String ATTR_PERMISSION_NAME = "name";
1367    private static final String ATTR_IS_GRANTED = "g";
1368    private static final String ATTR_USER_SET = "set";
1369    private static final String ATTR_USER_FIXED = "fixed";
1370    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1371
1372    // System/policy permission grants are not backed up
1373    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1374            FLAG_PERMISSION_POLICY_FIXED
1375            | FLAG_PERMISSION_SYSTEM_FIXED
1376            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1377
1378    // And we back up these user-adjusted states
1379    private static final int USER_RUNTIME_GRANT_MASK =
1380            FLAG_PERMISSION_USER_SET
1381            | FLAG_PERMISSION_USER_FIXED
1382            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1383
1384    final @Nullable String mRequiredVerifierPackage;
1385    final @NonNull String mRequiredInstallerPackage;
1386    final @NonNull String mRequiredUninstallerPackage;
1387    final @Nullable String mSetupWizardPackage;
1388    final @Nullable String mStorageManagerPackage;
1389    final @NonNull String mServicesSystemSharedLibraryPackageName;
1390    final @NonNull String mSharedSystemSharedLibraryPackageName;
1391
1392    final boolean mPermissionReviewRequired;
1393
1394    private final PackageUsage mPackageUsage = new PackageUsage();
1395    private final CompilerStats mCompilerStats = new CompilerStats();
1396
1397    class PackageHandler extends Handler {
1398        private boolean mBound = false;
1399        final ArrayList<HandlerParams> mPendingInstalls =
1400            new ArrayList<HandlerParams>();
1401
1402        private boolean connectToService() {
1403            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1404                    " DefaultContainerService");
1405            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1406            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1407            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1408                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1409                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1410                mBound = true;
1411                return true;
1412            }
1413            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1414            return false;
1415        }
1416
1417        private void disconnectService() {
1418            mContainerService = null;
1419            mBound = false;
1420            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1421            mContext.unbindService(mDefContainerConn);
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1423        }
1424
1425        PackageHandler(Looper looper) {
1426            super(looper);
1427        }
1428
1429        public void handleMessage(Message msg) {
1430            try {
1431                doHandleMessage(msg);
1432            } finally {
1433                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1434            }
1435        }
1436
1437        void doHandleMessage(Message msg) {
1438            switch (msg.what) {
1439                case INIT_COPY: {
1440                    HandlerParams params = (HandlerParams) msg.obj;
1441                    int idx = mPendingInstalls.size();
1442                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1443                    // If a bind was already initiated we dont really
1444                    // need to do anything. The pending install
1445                    // will be processed later on.
1446                    if (!mBound) {
1447                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1448                                System.identityHashCode(mHandler));
1449                        // If this is the only one pending we might
1450                        // have to bind to the service again.
1451                        if (!connectToService()) {
1452                            Slog.e(TAG, "Failed to bind to media container service");
1453                            params.serviceError();
1454                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1455                                    System.identityHashCode(mHandler));
1456                            if (params.traceMethod != null) {
1457                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1458                                        params.traceCookie);
1459                            }
1460                            return;
1461                        } else {
1462                            // Once we bind to the service, the first
1463                            // pending request will be processed.
1464                            mPendingInstalls.add(idx, params);
1465                        }
1466                    } else {
1467                        mPendingInstalls.add(idx, params);
1468                        // Already bound to the service. Just make
1469                        // sure we trigger off processing the first request.
1470                        if (idx == 0) {
1471                            mHandler.sendEmptyMessage(MCS_BOUND);
1472                        }
1473                    }
1474                    break;
1475                }
1476                case MCS_BOUND: {
1477                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1478                    if (msg.obj != null) {
1479                        mContainerService = (IMediaContainerService) msg.obj;
1480                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1481                                System.identityHashCode(mHandler));
1482                    }
1483                    if (mContainerService == null) {
1484                        if (!mBound) {
1485                            // Something seriously wrong since we are not bound and we are not
1486                            // waiting for connection. Bail out.
1487                            Slog.e(TAG, "Cannot bind to media container service");
1488                            for (HandlerParams params : mPendingInstalls) {
1489                                // Indicate service bind error
1490                                params.serviceError();
1491                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1492                                        System.identityHashCode(params));
1493                                if (params.traceMethod != null) {
1494                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1495                                            params.traceMethod, params.traceCookie);
1496                                }
1497                                return;
1498                            }
1499                            mPendingInstalls.clear();
1500                        } else {
1501                            Slog.w(TAG, "Waiting to connect to media container service");
1502                        }
1503                    } else if (mPendingInstalls.size() > 0) {
1504                        HandlerParams params = mPendingInstalls.get(0);
1505                        if (params != null) {
1506                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1507                                    System.identityHashCode(params));
1508                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1509                            if (params.startCopy()) {
1510                                // We are done...  look for more work or to
1511                                // go idle.
1512                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1513                                        "Checking for more work or unbind...");
1514                                // Delete pending install
1515                                if (mPendingInstalls.size() > 0) {
1516                                    mPendingInstalls.remove(0);
1517                                }
1518                                if (mPendingInstalls.size() == 0) {
1519                                    if (mBound) {
1520                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1521                                                "Posting delayed MCS_UNBIND");
1522                                        removeMessages(MCS_UNBIND);
1523                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1524                                        // Unbind after a little delay, to avoid
1525                                        // continual thrashing.
1526                                        sendMessageDelayed(ubmsg, 10000);
1527                                    }
1528                                } else {
1529                                    // There are more pending requests in queue.
1530                                    // Just post MCS_BOUND message to trigger processing
1531                                    // of next pending install.
1532                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1533                                            "Posting MCS_BOUND for next work");
1534                                    mHandler.sendEmptyMessage(MCS_BOUND);
1535                                }
1536                            }
1537                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1538                        }
1539                    } else {
1540                        // Should never happen ideally.
1541                        Slog.w(TAG, "Empty queue");
1542                    }
1543                    break;
1544                }
1545                case MCS_RECONNECT: {
1546                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1547                    if (mPendingInstalls.size() > 0) {
1548                        if (mBound) {
1549                            disconnectService();
1550                        }
1551                        if (!connectToService()) {
1552                            Slog.e(TAG, "Failed to bind to media container service");
1553                            for (HandlerParams params : mPendingInstalls) {
1554                                // Indicate service bind error
1555                                params.serviceError();
1556                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1557                                        System.identityHashCode(params));
1558                            }
1559                            mPendingInstalls.clear();
1560                        }
1561                    }
1562                    break;
1563                }
1564                case MCS_UNBIND: {
1565                    // If there is no actual work left, then time to unbind.
1566                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1567
1568                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1569                        if (mBound) {
1570                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1571
1572                            disconnectService();
1573                        }
1574                    } else if (mPendingInstalls.size() > 0) {
1575                        // There are more pending requests in queue.
1576                        // Just post MCS_BOUND message to trigger processing
1577                        // of next pending install.
1578                        mHandler.sendEmptyMessage(MCS_BOUND);
1579                    }
1580
1581                    break;
1582                }
1583                case MCS_GIVE_UP: {
1584                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1585                    HandlerParams params = mPendingInstalls.remove(0);
1586                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1587                            System.identityHashCode(params));
1588                    break;
1589                }
1590                case SEND_PENDING_BROADCAST: {
1591                    String packages[];
1592                    ArrayList<String> components[];
1593                    int size = 0;
1594                    int uids[];
1595                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1596                    synchronized (mPackages) {
1597                        if (mPendingBroadcasts == null) {
1598                            return;
1599                        }
1600                        size = mPendingBroadcasts.size();
1601                        if (size <= 0) {
1602                            // Nothing to be done. Just return
1603                            return;
1604                        }
1605                        packages = new String[size];
1606                        components = new ArrayList[size];
1607                        uids = new int[size];
1608                        int i = 0;  // filling out the above arrays
1609
1610                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1611                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1612                            Iterator<Map.Entry<String, ArrayList<String>>> it
1613                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1614                                            .entrySet().iterator();
1615                            while (it.hasNext() && i < size) {
1616                                Map.Entry<String, ArrayList<String>> ent = it.next();
1617                                packages[i] = ent.getKey();
1618                                components[i] = ent.getValue();
1619                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1620                                uids[i] = (ps != null)
1621                                        ? UserHandle.getUid(packageUserId, ps.appId)
1622                                        : -1;
1623                                i++;
1624                            }
1625                        }
1626                        size = i;
1627                        mPendingBroadcasts.clear();
1628                    }
1629                    // Send broadcasts
1630                    for (int i = 0; i < size; i++) {
1631                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1632                    }
1633                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1634                    break;
1635                }
1636                case START_CLEANING_PACKAGE: {
1637                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1638                    final String packageName = (String)msg.obj;
1639                    final int userId = msg.arg1;
1640                    final boolean andCode = msg.arg2 != 0;
1641                    synchronized (mPackages) {
1642                        if (userId == UserHandle.USER_ALL) {
1643                            int[] users = sUserManager.getUserIds();
1644                            for (int user : users) {
1645                                mSettings.addPackageToCleanLPw(
1646                                        new PackageCleanItem(user, packageName, andCode));
1647                            }
1648                        } else {
1649                            mSettings.addPackageToCleanLPw(
1650                                    new PackageCleanItem(userId, packageName, andCode));
1651                        }
1652                    }
1653                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1654                    startCleaningPackages();
1655                } break;
1656                case POST_INSTALL: {
1657                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1658
1659                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1660                    final boolean didRestore = (msg.arg2 != 0);
1661                    mRunningInstalls.delete(msg.arg1);
1662
1663                    if (data != null) {
1664                        InstallArgs args = data.args;
1665                        PackageInstalledInfo parentRes = data.res;
1666
1667                        final boolean grantPermissions = (args.installFlags
1668                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1669                        final boolean killApp = (args.installFlags
1670                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1671                        final String[] grantedPermissions = args.installGrantPermissions;
1672
1673                        // Handle the parent package
1674                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1675                                grantedPermissions, didRestore, args.installerPackageName,
1676                                args.observer);
1677
1678                        // Handle the child packages
1679                        final int childCount = (parentRes.addedChildPackages != null)
1680                                ? parentRes.addedChildPackages.size() : 0;
1681                        for (int i = 0; i < childCount; i++) {
1682                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1683                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1684                                    grantedPermissions, false, args.installerPackageName,
1685                                    args.observer);
1686                        }
1687
1688                        // Log tracing if needed
1689                        if (args.traceMethod != null) {
1690                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1691                                    args.traceCookie);
1692                        }
1693                    } else {
1694                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1695                    }
1696
1697                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1698                } break;
1699                case UPDATED_MEDIA_STATUS: {
1700                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1701                    boolean reportStatus = msg.arg1 == 1;
1702                    boolean doGc = msg.arg2 == 1;
1703                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1704                    if (doGc) {
1705                        // Force a gc to clear up stale containers.
1706                        Runtime.getRuntime().gc();
1707                    }
1708                    if (msg.obj != null) {
1709                        @SuppressWarnings("unchecked")
1710                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1711                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1712                        // Unload containers
1713                        unloadAllContainers(args);
1714                    }
1715                    if (reportStatus) {
1716                        try {
1717                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1718                                    "Invoking StorageManagerService call back");
1719                            PackageHelper.getStorageManager().finishMediaUpdate();
1720                        } catch (RemoteException e) {
1721                            Log.e(TAG, "StorageManagerService not running?");
1722                        }
1723                    }
1724                } break;
1725                case WRITE_SETTINGS: {
1726                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1727                    synchronized (mPackages) {
1728                        removeMessages(WRITE_SETTINGS);
1729                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1730                        mSettings.writeLPr();
1731                        mDirtyUsers.clear();
1732                    }
1733                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1734                } break;
1735                case WRITE_PACKAGE_RESTRICTIONS: {
1736                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1737                    synchronized (mPackages) {
1738                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1739                        for (int userId : mDirtyUsers) {
1740                            mSettings.writePackageRestrictionsLPr(userId);
1741                        }
1742                        mDirtyUsers.clear();
1743                    }
1744                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1745                } break;
1746                case WRITE_PACKAGE_LIST: {
1747                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1748                    synchronized (mPackages) {
1749                        removeMessages(WRITE_PACKAGE_LIST);
1750                        mSettings.writePackageListLPr(msg.arg1);
1751                    }
1752                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1753                } break;
1754                case CHECK_PENDING_VERIFICATION: {
1755                    final int verificationId = msg.arg1;
1756                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1757
1758                    if ((state != null) && !state.timeoutExtended()) {
1759                        final InstallArgs args = state.getInstallArgs();
1760                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1761
1762                        Slog.i(TAG, "Verification timed out for " + originUri);
1763                        mPendingVerification.remove(verificationId);
1764
1765                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1766
1767                        final UserHandle user = args.getUser();
1768                        if (getDefaultVerificationResponse(user)
1769                                == PackageManager.VERIFICATION_ALLOW) {
1770                            Slog.i(TAG, "Continuing with installation of " + originUri);
1771                            state.setVerifierResponse(Binder.getCallingUid(),
1772                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1773                            broadcastPackageVerified(verificationId, originUri,
1774                                    PackageManager.VERIFICATION_ALLOW, user);
1775                            try {
1776                                ret = args.copyApk(mContainerService, true);
1777                            } catch (RemoteException e) {
1778                                Slog.e(TAG, "Could not contact the ContainerService");
1779                            }
1780                        } else {
1781                            broadcastPackageVerified(verificationId, originUri,
1782                                    PackageManager.VERIFICATION_REJECT, user);
1783                        }
1784
1785                        Trace.asyncTraceEnd(
1786                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1787
1788                        processPendingInstall(args, ret);
1789                        mHandler.sendEmptyMessage(MCS_UNBIND);
1790                    }
1791                    break;
1792                }
1793                case PACKAGE_VERIFIED: {
1794                    final int verificationId = msg.arg1;
1795
1796                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1797                    if (state == null) {
1798                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1799                        break;
1800                    }
1801
1802                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1803
1804                    state.setVerifierResponse(response.callerUid, response.code);
1805
1806                    if (state.isVerificationComplete()) {
1807                        mPendingVerification.remove(verificationId);
1808
1809                        final InstallArgs args = state.getInstallArgs();
1810                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1811
1812                        int ret;
1813                        if (state.isInstallAllowed()) {
1814                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1815                            broadcastPackageVerified(verificationId, originUri,
1816                                    response.code, state.getInstallArgs().getUser());
1817                            try {
1818                                ret = args.copyApk(mContainerService, true);
1819                            } catch (RemoteException e) {
1820                                Slog.e(TAG, "Could not contact the ContainerService");
1821                            }
1822                        } else {
1823                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1824                        }
1825
1826                        Trace.asyncTraceEnd(
1827                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1828
1829                        processPendingInstall(args, ret);
1830                        mHandler.sendEmptyMessage(MCS_UNBIND);
1831                    }
1832
1833                    break;
1834                }
1835                case START_INTENT_FILTER_VERIFICATIONS: {
1836                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1837                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1838                            params.replacing, params.pkg);
1839                    break;
1840                }
1841                case INTENT_FILTER_VERIFIED: {
1842                    final int verificationId = msg.arg1;
1843
1844                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1845                            verificationId);
1846                    if (state == null) {
1847                        Slog.w(TAG, "Invalid IntentFilter verification token "
1848                                + verificationId + " received");
1849                        break;
1850                    }
1851
1852                    final int userId = state.getUserId();
1853
1854                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1855                            "Processing IntentFilter verification with token:"
1856                            + verificationId + " and userId:" + userId);
1857
1858                    final IntentFilterVerificationResponse response =
1859                            (IntentFilterVerificationResponse) msg.obj;
1860
1861                    state.setVerifierResponse(response.callerUid, response.code);
1862
1863                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1864                            "IntentFilter verification with token:" + verificationId
1865                            + " and userId:" + userId
1866                            + " is settings verifier response with response code:"
1867                            + response.code);
1868
1869                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1870                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1871                                + response.getFailedDomainsString());
1872                    }
1873
1874                    if (state.isVerificationComplete()) {
1875                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1876                    } else {
1877                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1878                                "IntentFilter verification with token:" + verificationId
1879                                + " was not said to be complete");
1880                    }
1881
1882                    break;
1883                }
1884                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1885                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1886                            mInstantAppResolverConnection,
1887                            (InstantAppRequest) msg.obj,
1888                            mInstantAppInstallerActivity,
1889                            mHandler);
1890                }
1891            }
1892        }
1893    }
1894
1895    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1896            boolean killApp, String[] grantedPermissions,
1897            boolean launchedForRestore, String installerPackage,
1898            IPackageInstallObserver2 installObserver) {
1899        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1900            // Send the removed broadcasts
1901            if (res.removedInfo != null) {
1902                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1903            }
1904
1905            // Now that we successfully installed the package, grant runtime
1906            // permissions if requested before broadcasting the install. Also
1907            // for legacy apps in permission review mode we clear the permission
1908            // review flag which is used to emulate runtime permissions for
1909            // legacy apps.
1910            if (grantPermissions) {
1911                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1912            }
1913
1914            final boolean update = res.removedInfo != null
1915                    && res.removedInfo.removedPackage != null;
1916            final String origInstallerPackageName = res.removedInfo != null
1917                    ? res.removedInfo.installerPackageName : null;
1918
1919            // If this is the first time we have child packages for a disabled privileged
1920            // app that had no children, we grant requested runtime permissions to the new
1921            // children if the parent on the system image had them already granted.
1922            if (res.pkg.parentPackage != null) {
1923                synchronized (mPackages) {
1924                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1925                }
1926            }
1927
1928            synchronized (mPackages) {
1929                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1930            }
1931
1932            final String packageName = res.pkg.applicationInfo.packageName;
1933
1934            // Determine the set of users who are adding this package for
1935            // the first time vs. those who are seeing an update.
1936            int[] firstUsers = EMPTY_INT_ARRAY;
1937            int[] updateUsers = EMPTY_INT_ARRAY;
1938            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1939            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1940            for (int newUser : res.newUsers) {
1941                if (ps.getInstantApp(newUser)) {
1942                    continue;
1943                }
1944                if (allNewUsers) {
1945                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1946                    continue;
1947                }
1948                boolean isNew = true;
1949                for (int origUser : res.origUsers) {
1950                    if (origUser == newUser) {
1951                        isNew = false;
1952                        break;
1953                    }
1954                }
1955                if (isNew) {
1956                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1957                } else {
1958                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1959                }
1960            }
1961
1962            // Send installed broadcasts if the package is not a static shared lib.
1963            if (res.pkg.staticSharedLibName == null) {
1964                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1965
1966                // Send added for users that see the package for the first time
1967                // sendPackageAddedForNewUsers also deals with system apps
1968                int appId = UserHandle.getAppId(res.uid);
1969                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1970                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1971
1972                // Send added for users that don't see the package for the first time
1973                Bundle extras = new Bundle(1);
1974                extras.putInt(Intent.EXTRA_UID, res.uid);
1975                if (update) {
1976                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1977                }
1978                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1979                        extras, 0 /*flags*/,
1980                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1981                if (origInstallerPackageName != null) {
1982                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1983                            extras, 0 /*flags*/,
1984                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1985                }
1986
1987                // Send replaced for users that don't see the package for the first time
1988                if (update) {
1989                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1990                            packageName, extras, 0 /*flags*/,
1991                            null /*targetPackage*/, null /*finishedReceiver*/,
1992                            updateUsers);
1993                    if (origInstallerPackageName != null) {
1994                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1995                                extras, 0 /*flags*/,
1996                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1997                    }
1998                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1999                            null /*package*/, null /*extras*/, 0 /*flags*/,
2000                            packageName /*targetPackage*/,
2001                            null /*finishedReceiver*/, updateUsers);
2002                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2003                    // First-install and we did a restore, so we're responsible for the
2004                    // first-launch broadcast.
2005                    if (DEBUG_BACKUP) {
2006                        Slog.i(TAG, "Post-restore of " + packageName
2007                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2008                    }
2009                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2010                }
2011
2012                // Send broadcast package appeared if forward locked/external for all users
2013                // treat asec-hosted packages like removable media on upgrade
2014                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2015                    if (DEBUG_INSTALL) {
2016                        Slog.i(TAG, "upgrading pkg " + res.pkg
2017                                + " is ASEC-hosted -> AVAILABLE");
2018                    }
2019                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2020                    ArrayList<String> pkgList = new ArrayList<>(1);
2021                    pkgList.add(packageName);
2022                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2023                }
2024            }
2025
2026            // Work that needs to happen on first install within each user
2027            if (firstUsers != null && firstUsers.length > 0) {
2028                synchronized (mPackages) {
2029                    for (int userId : firstUsers) {
2030                        // If this app is a browser and it's newly-installed for some
2031                        // users, clear any default-browser state in those users. The
2032                        // app's nature doesn't depend on the user, so we can just check
2033                        // its browser nature in any user and generalize.
2034                        if (packageIsBrowser(packageName, userId)) {
2035                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2036                        }
2037
2038                        // We may also need to apply pending (restored) runtime
2039                        // permission grants within these users.
2040                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2041                    }
2042                }
2043            }
2044
2045            // Log current value of "unknown sources" setting
2046            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2047                    getUnknownSourcesSettings());
2048
2049            // Remove the replaced package's older resources safely now
2050            // We delete after a gc for applications  on sdcard.
2051            if (res.removedInfo != null && res.removedInfo.args != null) {
2052                Runtime.getRuntime().gc();
2053                synchronized (mInstallLock) {
2054                    res.removedInfo.args.doPostDeleteLI(true);
2055                }
2056            } else {
2057                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2058                // and not block here.
2059                VMRuntime.getRuntime().requestConcurrentGC();
2060            }
2061
2062            // Notify DexManager that the package was installed for new users.
2063            // The updated users should already be indexed and the package code paths
2064            // should not change.
2065            // Don't notify the manager for ephemeral apps as they are not expected to
2066            // survive long enough to benefit of background optimizations.
2067            for (int userId : firstUsers) {
2068                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2069                // There's a race currently where some install events may interleave with an uninstall.
2070                // This can lead to package info being null (b/36642664).
2071                if (info != null) {
2072                    mDexManager.notifyPackageInstalled(info, userId);
2073                }
2074            }
2075        }
2076
2077        // If someone is watching installs - notify them
2078        if (installObserver != null) {
2079            try {
2080                Bundle extras = extrasForInstallResult(res);
2081                installObserver.onPackageInstalled(res.name, res.returnCode,
2082                        res.returnMsg, extras);
2083            } catch (RemoteException e) {
2084                Slog.i(TAG, "Observer no longer exists.");
2085            }
2086        }
2087    }
2088
2089    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2090            PackageParser.Package pkg) {
2091        if (pkg.parentPackage == null) {
2092            return;
2093        }
2094        if (pkg.requestedPermissions == null) {
2095            return;
2096        }
2097        final PackageSetting disabledSysParentPs = mSettings
2098                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2099        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2100                || !disabledSysParentPs.isPrivileged()
2101                || (disabledSysParentPs.childPackageNames != null
2102                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2103            return;
2104        }
2105        final int[] allUserIds = sUserManager.getUserIds();
2106        final int permCount = pkg.requestedPermissions.size();
2107        for (int i = 0; i < permCount; i++) {
2108            String permission = pkg.requestedPermissions.get(i);
2109            BasePermission bp = mSettings.mPermissions.get(permission);
2110            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2111                continue;
2112            }
2113            for (int userId : allUserIds) {
2114                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2115                        permission, userId)) {
2116                    grantRuntimePermission(pkg.packageName, permission, userId);
2117                }
2118            }
2119        }
2120    }
2121
2122    private StorageEventListener mStorageListener = new StorageEventListener() {
2123        @Override
2124        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2125            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2126                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2127                    final String volumeUuid = vol.getFsUuid();
2128
2129                    // Clean up any users or apps that were removed or recreated
2130                    // while this volume was missing
2131                    sUserManager.reconcileUsers(volumeUuid);
2132                    reconcileApps(volumeUuid);
2133
2134                    // Clean up any install sessions that expired or were
2135                    // cancelled while this volume was missing
2136                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2137
2138                    loadPrivatePackages(vol);
2139
2140                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2141                    unloadPrivatePackages(vol);
2142                }
2143            }
2144
2145            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2146                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2147                    updateExternalMediaStatus(true, false);
2148                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2149                    updateExternalMediaStatus(false, false);
2150                }
2151            }
2152        }
2153
2154        @Override
2155        public void onVolumeForgotten(String fsUuid) {
2156            if (TextUtils.isEmpty(fsUuid)) {
2157                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2158                return;
2159            }
2160
2161            // Remove any apps installed on the forgotten volume
2162            synchronized (mPackages) {
2163                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2164                for (PackageSetting ps : packages) {
2165                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2166                    deletePackageVersioned(new VersionedPackage(ps.name,
2167                            PackageManager.VERSION_CODE_HIGHEST),
2168                            new LegacyPackageDeleteObserver(null).getBinder(),
2169                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2170                    // Try very hard to release any references to this package
2171                    // so we don't risk the system server being killed due to
2172                    // open FDs
2173                    AttributeCache.instance().removePackage(ps.name);
2174                }
2175
2176                mSettings.onVolumeForgotten(fsUuid);
2177                mSettings.writeLPr();
2178            }
2179        }
2180    };
2181
2182    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2183            String[] grantedPermissions) {
2184        for (int userId : userIds) {
2185            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2186        }
2187    }
2188
2189    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2190            String[] grantedPermissions) {
2191        PackageSetting ps = (PackageSetting) pkg.mExtras;
2192        if (ps == null) {
2193            return;
2194        }
2195
2196        PermissionsState permissionsState = ps.getPermissionsState();
2197
2198        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2199                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2200
2201        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2202                >= Build.VERSION_CODES.M;
2203
2204        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2205
2206        for (String permission : pkg.requestedPermissions) {
2207            final BasePermission bp;
2208            synchronized (mPackages) {
2209                bp = mSettings.mPermissions.get(permission);
2210            }
2211            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2212                    && (!instantApp || bp.isInstant())
2213                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2214                    && (grantedPermissions == null
2215                           || ArrayUtils.contains(grantedPermissions, permission))) {
2216                final int flags = permissionsState.getPermissionFlags(permission, userId);
2217                if (supportsRuntimePermissions) {
2218                    // Installer cannot change immutable permissions.
2219                    if ((flags & immutableFlags) == 0) {
2220                        grantRuntimePermission(pkg.packageName, permission, userId);
2221                    }
2222                } else if (mPermissionReviewRequired) {
2223                    // In permission review mode we clear the review flag when we
2224                    // are asked to install the app with all permissions granted.
2225                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2226                        updatePermissionFlags(permission, pkg.packageName,
2227                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2228                    }
2229                }
2230            }
2231        }
2232    }
2233
2234    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2235        Bundle extras = null;
2236        switch (res.returnCode) {
2237            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2238                extras = new Bundle();
2239                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2240                        res.origPermission);
2241                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2242                        res.origPackage);
2243                break;
2244            }
2245            case PackageManager.INSTALL_SUCCEEDED: {
2246                extras = new Bundle();
2247                extras.putBoolean(Intent.EXTRA_REPLACING,
2248                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2249                break;
2250            }
2251        }
2252        return extras;
2253    }
2254
2255    void scheduleWriteSettingsLocked() {
2256        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2257            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2258        }
2259    }
2260
2261    void scheduleWritePackageListLocked(int userId) {
2262        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2263            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2264            msg.arg1 = userId;
2265            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2266        }
2267    }
2268
2269    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2270        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2271        scheduleWritePackageRestrictionsLocked(userId);
2272    }
2273
2274    void scheduleWritePackageRestrictionsLocked(int userId) {
2275        final int[] userIds = (userId == UserHandle.USER_ALL)
2276                ? sUserManager.getUserIds() : new int[]{userId};
2277        for (int nextUserId : userIds) {
2278            if (!sUserManager.exists(nextUserId)) return;
2279            mDirtyUsers.add(nextUserId);
2280            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2281                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2282            }
2283        }
2284    }
2285
2286    public static PackageManagerService main(Context context, Installer installer,
2287            boolean factoryTest, boolean onlyCore) {
2288        // Self-check for initial settings.
2289        PackageManagerServiceCompilerMapping.checkProperties();
2290
2291        PackageManagerService m = new PackageManagerService(context, installer,
2292                factoryTest, onlyCore);
2293        m.enableSystemUserPackages();
2294        ServiceManager.addService("package", m);
2295        return m;
2296    }
2297
2298    private void enableSystemUserPackages() {
2299        if (!UserManager.isSplitSystemUser()) {
2300            return;
2301        }
2302        // For system user, enable apps based on the following conditions:
2303        // - app is whitelisted or belong to one of these groups:
2304        //   -- system app which has no launcher icons
2305        //   -- system app which has INTERACT_ACROSS_USERS permission
2306        //   -- system IME app
2307        // - app is not in the blacklist
2308        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2309        Set<String> enableApps = new ArraySet<>();
2310        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2311                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2312                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2313        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2314        enableApps.addAll(wlApps);
2315        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2316                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2317        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2318        enableApps.removeAll(blApps);
2319        Log.i(TAG, "Applications installed for system user: " + enableApps);
2320        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2321                UserHandle.SYSTEM);
2322        final int allAppsSize = allAps.size();
2323        synchronized (mPackages) {
2324            for (int i = 0; i < allAppsSize; i++) {
2325                String pName = allAps.get(i);
2326                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2327                // Should not happen, but we shouldn't be failing if it does
2328                if (pkgSetting == null) {
2329                    continue;
2330                }
2331                boolean install = enableApps.contains(pName);
2332                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2333                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2334                            + " for system user");
2335                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2336                }
2337            }
2338            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2339        }
2340    }
2341
2342    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2343        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2344                Context.DISPLAY_SERVICE);
2345        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2346    }
2347
2348    /**
2349     * Requests that files preopted on a secondary system partition be copied to the data partition
2350     * if possible.  Note that the actual copying of the files is accomplished by init for security
2351     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2352     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2353     */
2354    private static void requestCopyPreoptedFiles() {
2355        final int WAIT_TIME_MS = 100;
2356        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2357        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2358            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2359            // We will wait for up to 100 seconds.
2360            final long timeStart = SystemClock.uptimeMillis();
2361            final long timeEnd = timeStart + 100 * 1000;
2362            long timeNow = timeStart;
2363            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2364                try {
2365                    Thread.sleep(WAIT_TIME_MS);
2366                } catch (InterruptedException e) {
2367                    // Do nothing
2368                }
2369                timeNow = SystemClock.uptimeMillis();
2370                if (timeNow > timeEnd) {
2371                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2372                    Slog.wtf(TAG, "cppreopt did not finish!");
2373                    break;
2374                }
2375            }
2376
2377            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2378        }
2379    }
2380
2381    public PackageManagerService(Context context, Installer installer,
2382            boolean factoryTest, boolean onlyCore) {
2383        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2384        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2385        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2386                SystemClock.uptimeMillis());
2387
2388        if (mSdkVersion <= 0) {
2389            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2390        }
2391
2392        mContext = context;
2393
2394        mPermissionReviewRequired = context.getResources().getBoolean(
2395                R.bool.config_permissionReviewRequired);
2396
2397        mFactoryTest = factoryTest;
2398        mOnlyCore = onlyCore;
2399        mMetrics = new DisplayMetrics();
2400        mSettings = new Settings(mPackages);
2401        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2402                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2408                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2409        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2410                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2411        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2412                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2413
2414        String separateProcesses = SystemProperties.get("debug.separate_processes");
2415        if (separateProcesses != null && separateProcesses.length() > 0) {
2416            if ("*".equals(separateProcesses)) {
2417                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2418                mSeparateProcesses = null;
2419                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2420            } else {
2421                mDefParseFlags = 0;
2422                mSeparateProcesses = separateProcesses.split(",");
2423                Slog.w(TAG, "Running with debug.separate_processes: "
2424                        + separateProcesses);
2425            }
2426        } else {
2427            mDefParseFlags = 0;
2428            mSeparateProcesses = null;
2429        }
2430
2431        mInstaller = installer;
2432        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2433                "*dexopt*");
2434        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2435        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2436
2437        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2438                FgThread.get().getLooper());
2439
2440        getDefaultDisplayMetrics(context, mMetrics);
2441
2442        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2443        SystemConfig systemConfig = SystemConfig.getInstance();
2444        mGlobalGids = systemConfig.getGlobalGids();
2445        mSystemPermissions = systemConfig.getSystemPermissions();
2446        mAvailableFeatures = systemConfig.getAvailableFeatures();
2447        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2448
2449        mProtectedPackages = new ProtectedPackages(mContext);
2450
2451        synchronized (mInstallLock) {
2452        // writer
2453        synchronized (mPackages) {
2454            mHandlerThread = new ServiceThread(TAG,
2455                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2456            mHandlerThread.start();
2457            mHandler = new PackageHandler(mHandlerThread.getLooper());
2458            mProcessLoggingHandler = new ProcessLoggingHandler();
2459            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2460
2461            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2462            mInstantAppRegistry = new InstantAppRegistry(this);
2463
2464            File dataDir = Environment.getDataDirectory();
2465            mAppInstallDir = new File(dataDir, "app");
2466            mAppLib32InstallDir = new File(dataDir, "app-lib");
2467            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2468            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2469            sUserManager = new UserManagerService(context, this,
2470                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2471
2472            // Propagate permission configuration in to package manager.
2473            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2474                    = systemConfig.getPermissions();
2475            for (int i=0; i<permConfig.size(); i++) {
2476                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2477                BasePermission bp = mSettings.mPermissions.get(perm.name);
2478                if (bp == null) {
2479                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2480                    mSettings.mPermissions.put(perm.name, bp);
2481                }
2482                if (perm.gids != null) {
2483                    bp.setGids(perm.gids, perm.perUser);
2484                }
2485            }
2486
2487            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2488            final int builtInLibCount = libConfig.size();
2489            for (int i = 0; i < builtInLibCount; i++) {
2490                String name = libConfig.keyAt(i);
2491                String path = libConfig.valueAt(i);
2492                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2493                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2494            }
2495
2496            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2497
2498            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2499            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2500            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2501
2502            // Clean up orphaned packages for which the code path doesn't exist
2503            // and they are an update to a system app - caused by bug/32321269
2504            final int packageSettingCount = mSettings.mPackages.size();
2505            for (int i = packageSettingCount - 1; i >= 0; i--) {
2506                PackageSetting ps = mSettings.mPackages.valueAt(i);
2507                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2508                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2509                    mSettings.mPackages.removeAt(i);
2510                    mSettings.enableSystemPackageLPw(ps.name);
2511                }
2512            }
2513
2514            if (mFirstBoot) {
2515                requestCopyPreoptedFiles();
2516            }
2517
2518            String customResolverActivity = Resources.getSystem().getString(
2519                    R.string.config_customResolverActivity);
2520            if (TextUtils.isEmpty(customResolverActivity)) {
2521                customResolverActivity = null;
2522            } else {
2523                mCustomResolverComponentName = ComponentName.unflattenFromString(
2524                        customResolverActivity);
2525            }
2526
2527            long startTime = SystemClock.uptimeMillis();
2528
2529            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2530                    startTime);
2531
2532            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2533            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2534
2535            if (bootClassPath == null) {
2536                Slog.w(TAG, "No BOOTCLASSPATH found!");
2537            }
2538
2539            if (systemServerClassPath == null) {
2540                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2541            }
2542
2543            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2544
2545            final VersionInfo ver = mSettings.getInternalVersion();
2546            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2547            if (mIsUpgrade) {
2548                logCriticalInfo(Log.INFO,
2549                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2550            }
2551
2552            // when upgrading from pre-M, promote system app permissions from install to runtime
2553            mPromoteSystemApps =
2554                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2555
2556            // When upgrading from pre-N, we need to handle package extraction like first boot,
2557            // as there is no profiling data available.
2558            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2559
2560            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2561
2562            // save off the names of pre-existing system packages prior to scanning; we don't
2563            // want to automatically grant runtime permissions for new system apps
2564            if (mPromoteSystemApps) {
2565                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2566                while (pkgSettingIter.hasNext()) {
2567                    PackageSetting ps = pkgSettingIter.next();
2568                    if (isSystemApp(ps)) {
2569                        mExistingSystemPackages.add(ps.name);
2570                    }
2571                }
2572            }
2573
2574            mCacheDir = preparePackageParserCache(mIsUpgrade);
2575
2576            // Set flag to monitor and not change apk file paths when
2577            // scanning install directories.
2578            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2579
2580            if (mIsUpgrade || mFirstBoot) {
2581                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2582            }
2583
2584            // Collect vendor overlay packages. (Do this before scanning any apps.)
2585            // For security and version matching reason, only consider
2586            // overlay packages if they reside in the right directory.
2587            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2588                    | PackageParser.PARSE_IS_SYSTEM
2589                    | PackageParser.PARSE_IS_SYSTEM_DIR
2590                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2591
2592            mParallelPackageParserCallback.findStaticOverlayPackages();
2593
2594            // Find base frameworks (resource packages without code).
2595            scanDirTracedLI(frameworkDir, mDefParseFlags
2596                    | PackageParser.PARSE_IS_SYSTEM
2597                    | PackageParser.PARSE_IS_SYSTEM_DIR
2598                    | PackageParser.PARSE_IS_PRIVILEGED,
2599                    scanFlags | SCAN_NO_DEX, 0);
2600
2601            // Collected privileged system packages.
2602            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2603            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2604                    | PackageParser.PARSE_IS_SYSTEM
2605                    | PackageParser.PARSE_IS_SYSTEM_DIR
2606                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2607
2608            // Collect ordinary system packages.
2609            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2610            scanDirTracedLI(systemAppDir, mDefParseFlags
2611                    | PackageParser.PARSE_IS_SYSTEM
2612                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2613
2614            // Collect all vendor packages.
2615            File vendorAppDir = new File("/vendor/app");
2616            try {
2617                vendorAppDir = vendorAppDir.getCanonicalFile();
2618            } catch (IOException e) {
2619                // failed to look up canonical path, continue with original one
2620            }
2621            scanDirTracedLI(vendorAppDir, mDefParseFlags
2622                    | PackageParser.PARSE_IS_SYSTEM
2623                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2624
2625            // Collect all OEM packages.
2626            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2627            scanDirTracedLI(oemAppDir, mDefParseFlags
2628                    | PackageParser.PARSE_IS_SYSTEM
2629                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2630
2631            // Prune any system packages that no longer exist.
2632            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2633            if (!mOnlyCore) {
2634                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2635                while (psit.hasNext()) {
2636                    PackageSetting ps = psit.next();
2637
2638                    /*
2639                     * If this is not a system app, it can't be a
2640                     * disable system app.
2641                     */
2642                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2643                        continue;
2644                    }
2645
2646                    /*
2647                     * If the package is scanned, it's not erased.
2648                     */
2649                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2650                    if (scannedPkg != null) {
2651                        /*
2652                         * If the system app is both scanned and in the
2653                         * disabled packages list, then it must have been
2654                         * added via OTA. Remove it from the currently
2655                         * scanned package so the previously user-installed
2656                         * application can be scanned.
2657                         */
2658                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2659                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2660                                    + ps.name + "; removing system app.  Last known codePath="
2661                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2662                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2663                                    + scannedPkg.mVersionCode);
2664                            removePackageLI(scannedPkg, true);
2665                            mExpectingBetter.put(ps.name, ps.codePath);
2666                        }
2667
2668                        continue;
2669                    }
2670
2671                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2672                        psit.remove();
2673                        logCriticalInfo(Log.WARN, "System package " + ps.name
2674                                + " no longer exists; it's data will be wiped");
2675                        // Actual deletion of code and data will be handled by later
2676                        // reconciliation step
2677                    } else {
2678                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2679                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2680                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2681                        }
2682                    }
2683                }
2684            }
2685
2686            //look for any incomplete package installations
2687            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2688            for (int i = 0; i < deletePkgsList.size(); i++) {
2689                // Actual deletion of code and data will be handled by later
2690                // reconciliation step
2691                final String packageName = deletePkgsList.get(i).name;
2692                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2693                synchronized (mPackages) {
2694                    mSettings.removePackageLPw(packageName);
2695                }
2696            }
2697
2698            //delete tmp files
2699            deleteTempPackageFiles();
2700
2701            // Remove any shared userIDs that have no associated packages
2702            mSettings.pruneSharedUsersLPw();
2703
2704            if (!mOnlyCore) {
2705                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2706                        SystemClock.uptimeMillis());
2707                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2708
2709                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2710                        | PackageParser.PARSE_FORWARD_LOCK,
2711                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2712
2713                /**
2714                 * Remove disable package settings for any updated system
2715                 * apps that were removed via an OTA. If they're not a
2716                 * previously-updated app, remove them completely.
2717                 * Otherwise, just revoke their system-level permissions.
2718                 */
2719                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2720                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2721                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2722
2723                    String msg;
2724                    if (deletedPkg == null) {
2725                        msg = "Updated system package " + deletedAppName
2726                                + " no longer exists; it's data will be wiped";
2727                        // Actual deletion of code and data will be handled by later
2728                        // reconciliation step
2729                    } else {
2730                        msg = "Updated system app + " + deletedAppName
2731                                + " no longer present; removing system privileges for "
2732                                + deletedAppName;
2733
2734                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2735
2736                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2737                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2738                    }
2739                    logCriticalInfo(Log.WARN, msg);
2740                }
2741
2742                /**
2743                 * Make sure all system apps that we expected to appear on
2744                 * the userdata partition actually showed up. If they never
2745                 * appeared, crawl back and revive the system version.
2746                 */
2747                for (int i = 0; i < mExpectingBetter.size(); i++) {
2748                    final String packageName = mExpectingBetter.keyAt(i);
2749                    if (!mPackages.containsKey(packageName)) {
2750                        final File scanFile = mExpectingBetter.valueAt(i);
2751
2752                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2753                                + " but never showed up; reverting to system");
2754
2755                        int reparseFlags = mDefParseFlags;
2756                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2757                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2758                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2759                                    | PackageParser.PARSE_IS_PRIVILEGED;
2760                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2761                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2762                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2763                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2764                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2765                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2766                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2767                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2768                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2769                        } else {
2770                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2771                            continue;
2772                        }
2773
2774                        mSettings.enableSystemPackageLPw(packageName);
2775
2776                        try {
2777                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2778                        } catch (PackageManagerException e) {
2779                            Slog.e(TAG, "Failed to parse original system package: "
2780                                    + e.getMessage());
2781                        }
2782                    }
2783                }
2784            }
2785            mExpectingBetter.clear();
2786
2787            // Resolve the storage manager.
2788            mStorageManagerPackage = getStorageManagerPackageName();
2789
2790            // Resolve protected action filters. Only the setup wizard is allowed to
2791            // have a high priority filter for these actions.
2792            mSetupWizardPackage = getSetupWizardPackageName();
2793            if (mProtectedFilters.size() > 0) {
2794                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2795                    Slog.i(TAG, "No setup wizard;"
2796                        + " All protected intents capped to priority 0");
2797                }
2798                for (ActivityIntentInfo filter : mProtectedFilters) {
2799                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2800                        if (DEBUG_FILTERS) {
2801                            Slog.i(TAG, "Found setup wizard;"
2802                                + " allow priority " + filter.getPriority() + ";"
2803                                + " package: " + filter.activity.info.packageName
2804                                + " activity: " + filter.activity.className
2805                                + " priority: " + filter.getPriority());
2806                        }
2807                        // skip setup wizard; allow it to keep the high priority filter
2808                        continue;
2809                    }
2810                    if (DEBUG_FILTERS) {
2811                        Slog.i(TAG, "Protected action; cap priority to 0;"
2812                                + " package: " + filter.activity.info.packageName
2813                                + " activity: " + filter.activity.className
2814                                + " origPrio: " + filter.getPriority());
2815                    }
2816                    filter.setPriority(0);
2817                }
2818            }
2819            mDeferProtectedFilters = false;
2820            mProtectedFilters.clear();
2821
2822            // Now that we know all of the shared libraries, update all clients to have
2823            // the correct library paths.
2824            updateAllSharedLibrariesLPw(null);
2825
2826            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2827                // NOTE: We ignore potential failures here during a system scan (like
2828                // the rest of the commands above) because there's precious little we
2829                // can do about it. A settings error is reported, though.
2830                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2831            }
2832
2833            // Now that we know all the packages we are keeping,
2834            // read and update their last usage times.
2835            mPackageUsage.read(mPackages);
2836            mCompilerStats.read();
2837
2838            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2839                    SystemClock.uptimeMillis());
2840            Slog.i(TAG, "Time to scan packages: "
2841                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2842                    + " seconds");
2843
2844            // If the platform SDK has changed since the last time we booted,
2845            // we need to re-grant app permission to catch any new ones that
2846            // appear.  This is really a hack, and means that apps can in some
2847            // cases get permissions that the user didn't initially explicitly
2848            // allow...  it would be nice to have some better way to handle
2849            // this situation.
2850            int updateFlags = UPDATE_PERMISSIONS_ALL;
2851            if (ver.sdkVersion != mSdkVersion) {
2852                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2853                        + mSdkVersion + "; regranting permissions for internal storage");
2854                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2855            }
2856            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2857            ver.sdkVersion = mSdkVersion;
2858
2859            // If this is the first boot or an update from pre-M, and it is a normal
2860            // boot, then we need to initialize the default preferred apps across
2861            // all defined users.
2862            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2863                for (UserInfo user : sUserManager.getUsers(true)) {
2864                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2865                    applyFactoryDefaultBrowserLPw(user.id);
2866                    primeDomainVerificationsLPw(user.id);
2867                }
2868            }
2869
2870            // Prepare storage for system user really early during boot,
2871            // since core system apps like SettingsProvider and SystemUI
2872            // can't wait for user to start
2873            final int storageFlags;
2874            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2875                storageFlags = StorageManager.FLAG_STORAGE_DE;
2876            } else {
2877                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2878            }
2879            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2880                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2881                    true /* onlyCoreApps */);
2882            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2883                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2884                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2885                traceLog.traceBegin("AppDataFixup");
2886                try {
2887                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2888                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2889                } catch (InstallerException e) {
2890                    Slog.w(TAG, "Trouble fixing GIDs", e);
2891                }
2892                traceLog.traceEnd();
2893
2894                traceLog.traceBegin("AppDataPrepare");
2895                if (deferPackages == null || deferPackages.isEmpty()) {
2896                    return;
2897                }
2898                int count = 0;
2899                for (String pkgName : deferPackages) {
2900                    PackageParser.Package pkg = null;
2901                    synchronized (mPackages) {
2902                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2903                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2904                            pkg = ps.pkg;
2905                        }
2906                    }
2907                    if (pkg != null) {
2908                        synchronized (mInstallLock) {
2909                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2910                                    true /* maybeMigrateAppData */);
2911                        }
2912                        count++;
2913                    }
2914                }
2915                traceLog.traceEnd();
2916                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2917            }, "prepareAppData");
2918
2919            // If this is first boot after an OTA, and a normal boot, then
2920            // we need to clear code cache directories.
2921            // Note that we do *not* clear the application profiles. These remain valid
2922            // across OTAs and are used to drive profile verification (post OTA) and
2923            // profile compilation (without waiting to collect a fresh set of profiles).
2924            if (mIsUpgrade && !onlyCore) {
2925                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2926                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2927                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2928                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2929                        // No apps are running this early, so no need to freeze
2930                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2931                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2932                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2933                    }
2934                }
2935                ver.fingerprint = Build.FINGERPRINT;
2936            }
2937
2938            checkDefaultBrowser();
2939
2940            // clear only after permissions and other defaults have been updated
2941            mExistingSystemPackages.clear();
2942            mPromoteSystemApps = false;
2943
2944            // All the changes are done during package scanning.
2945            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2946
2947            // can downgrade to reader
2948            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2949            mSettings.writeLPr();
2950            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2951            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2952                    SystemClock.uptimeMillis());
2953
2954            if (!mOnlyCore) {
2955                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2956                mRequiredInstallerPackage = getRequiredInstallerLPr();
2957                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2958                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2959                if (mIntentFilterVerifierComponent != null) {
2960                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2961                            mIntentFilterVerifierComponent);
2962                } else {
2963                    mIntentFilterVerifier = null;
2964                }
2965                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2966                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2967                        SharedLibraryInfo.VERSION_UNDEFINED);
2968                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2969                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2970                        SharedLibraryInfo.VERSION_UNDEFINED);
2971            } else {
2972                mRequiredVerifierPackage = null;
2973                mRequiredInstallerPackage = null;
2974                mRequiredUninstallerPackage = null;
2975                mIntentFilterVerifierComponent = null;
2976                mIntentFilterVerifier = null;
2977                mServicesSystemSharedLibraryPackageName = null;
2978                mSharedSystemSharedLibraryPackageName = null;
2979            }
2980
2981            mInstallerService = new PackageInstallerService(context, this);
2982            final Pair<ComponentName, String> instantAppResolverComponent =
2983                    getInstantAppResolverLPr();
2984            if (instantAppResolverComponent != null) {
2985                if (DEBUG_EPHEMERAL) {
2986                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2987                }
2988                mInstantAppResolverConnection = new EphemeralResolverConnection(
2989                        mContext, instantAppResolverComponent.first,
2990                        instantAppResolverComponent.second);
2991                mInstantAppResolverSettingsComponent =
2992                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2993            } else {
2994                mInstantAppResolverConnection = null;
2995                mInstantAppResolverSettingsComponent = null;
2996            }
2997            updateInstantAppInstallerLocked(null);
2998
2999            // Read and update the usage of dex files.
3000            // Do this at the end of PM init so that all the packages have their
3001            // data directory reconciled.
3002            // At this point we know the code paths of the packages, so we can validate
3003            // the disk file and build the internal cache.
3004            // The usage file is expected to be small so loading and verifying it
3005            // should take a fairly small time compare to the other activities (e.g. package
3006            // scanning).
3007            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3008            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3009            for (int userId : currentUserIds) {
3010                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3011            }
3012            mDexManager.load(userPackages);
3013        } // synchronized (mPackages)
3014        } // synchronized (mInstallLock)
3015
3016        // Now after opening every single application zip, make sure they
3017        // are all flushed.  Not really needed, but keeps things nice and
3018        // tidy.
3019        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3020        Runtime.getRuntime().gc();
3021        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3022
3023        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3024        FallbackCategoryProvider.loadFallbacks();
3025        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3026
3027        // The initial scanning above does many calls into installd while
3028        // holding the mPackages lock, but we're mostly interested in yelling
3029        // once we have a booted system.
3030        mInstaller.setWarnIfHeld(mPackages);
3031
3032        // Expose private service for system components to use.
3033        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3034        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3035    }
3036
3037    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3038        // we're only interested in updating the installer appliction when 1) it's not
3039        // already set or 2) the modified package is the installer
3040        if (mInstantAppInstallerActivity != null
3041                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3042                        .equals(modifiedPackage)) {
3043            return;
3044        }
3045        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3046    }
3047
3048    private static File preparePackageParserCache(boolean isUpgrade) {
3049        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3050            return null;
3051        }
3052
3053        // Disable package parsing on eng builds to allow for faster incremental development.
3054        if ("eng".equals(Build.TYPE)) {
3055            return null;
3056        }
3057
3058        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3059            Slog.i(TAG, "Disabling package parser cache due to system property.");
3060            return null;
3061        }
3062
3063        // The base directory for the package parser cache lives under /data/system/.
3064        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3065                "package_cache");
3066        if (cacheBaseDir == null) {
3067            return null;
3068        }
3069
3070        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3071        // This also serves to "GC" unused entries when the package cache version changes (which
3072        // can only happen during upgrades).
3073        if (isUpgrade) {
3074            FileUtils.deleteContents(cacheBaseDir);
3075        }
3076
3077
3078        // Return the versioned package cache directory. This is something like
3079        // "/data/system/package_cache/1"
3080        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3081
3082        // The following is a workaround to aid development on non-numbered userdebug
3083        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3084        // the system partition is newer.
3085        //
3086        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3087        // that starts with "eng." to signify that this is an engineering build and not
3088        // destined for release.
3089        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3090            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3091
3092            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3093            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3094            // in general and should not be used for production changes. In this specific case,
3095            // we know that they will work.
3096            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3097            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3098                FileUtils.deleteContents(cacheBaseDir);
3099                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3100            }
3101        }
3102
3103        return cacheDir;
3104    }
3105
3106    @Override
3107    public boolean isFirstBoot() {
3108        // allow instant applications
3109        return mFirstBoot;
3110    }
3111
3112    @Override
3113    public boolean isOnlyCoreApps() {
3114        // allow instant applications
3115        return mOnlyCore;
3116    }
3117
3118    @Override
3119    public boolean isUpgrade() {
3120        // allow instant applications
3121        return mIsUpgrade;
3122    }
3123
3124    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3125        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3126
3127        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3128                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3129                UserHandle.USER_SYSTEM);
3130        if (matches.size() == 1) {
3131            return matches.get(0).getComponentInfo().packageName;
3132        } else if (matches.size() == 0) {
3133            Log.e(TAG, "There should probably be a verifier, but, none were found");
3134            return null;
3135        }
3136        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3137    }
3138
3139    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3140        synchronized (mPackages) {
3141            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3142            if (libraryEntry == null) {
3143                throw new IllegalStateException("Missing required shared library:" + name);
3144            }
3145            return libraryEntry.apk;
3146        }
3147    }
3148
3149    private @NonNull String getRequiredInstallerLPr() {
3150        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3151        intent.addCategory(Intent.CATEGORY_DEFAULT);
3152        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3153
3154        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3155                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3156                UserHandle.USER_SYSTEM);
3157        if (matches.size() == 1) {
3158            ResolveInfo resolveInfo = matches.get(0);
3159            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3160                throw new RuntimeException("The installer must be a privileged app");
3161            }
3162            return matches.get(0).getComponentInfo().packageName;
3163        } else {
3164            throw new RuntimeException("There must be exactly one installer; found " + matches);
3165        }
3166    }
3167
3168    private @NonNull String getRequiredUninstallerLPr() {
3169        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3170        intent.addCategory(Intent.CATEGORY_DEFAULT);
3171        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3172
3173        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3174                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3175                UserHandle.USER_SYSTEM);
3176        if (resolveInfo == null ||
3177                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3178            throw new RuntimeException("There must be exactly one uninstaller; found "
3179                    + resolveInfo);
3180        }
3181        return resolveInfo.getComponentInfo().packageName;
3182    }
3183
3184    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3185        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3186
3187        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3188                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3189                UserHandle.USER_SYSTEM);
3190        ResolveInfo best = null;
3191        final int N = matches.size();
3192        for (int i = 0; i < N; i++) {
3193            final ResolveInfo cur = matches.get(i);
3194            final String packageName = cur.getComponentInfo().packageName;
3195            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3196                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3197                continue;
3198            }
3199
3200            if (best == null || cur.priority > best.priority) {
3201                best = cur;
3202            }
3203        }
3204
3205        if (best != null) {
3206            return best.getComponentInfo().getComponentName();
3207        }
3208        Slog.w(TAG, "Intent filter verifier not found");
3209        return null;
3210    }
3211
3212    @Override
3213    public @Nullable ComponentName getInstantAppResolverComponent() {
3214        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3215            return null;
3216        }
3217        synchronized (mPackages) {
3218            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3219            if (instantAppResolver == null) {
3220                return null;
3221            }
3222            return instantAppResolver.first;
3223        }
3224    }
3225
3226    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3227        final String[] packageArray =
3228                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3229        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3230            if (DEBUG_EPHEMERAL) {
3231                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3232            }
3233            return null;
3234        }
3235
3236        final int callingUid = Binder.getCallingUid();
3237        final int resolveFlags =
3238                MATCH_DIRECT_BOOT_AWARE
3239                | MATCH_DIRECT_BOOT_UNAWARE
3240                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3241        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3242        final Intent resolverIntent = new Intent(actionName);
3243        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3244                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3245        // temporarily look for the old action
3246        if (resolvers.size() == 0) {
3247            if (DEBUG_EPHEMERAL) {
3248                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3249            }
3250            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3251            resolverIntent.setAction(actionName);
3252            resolvers = queryIntentServicesInternal(resolverIntent, null,
3253                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3254        }
3255        final int N = resolvers.size();
3256        if (N == 0) {
3257            if (DEBUG_EPHEMERAL) {
3258                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3259            }
3260            return null;
3261        }
3262
3263        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3264        for (int i = 0; i < N; i++) {
3265            final ResolveInfo info = resolvers.get(i);
3266
3267            if (info.serviceInfo == null) {
3268                continue;
3269            }
3270
3271            final String packageName = info.serviceInfo.packageName;
3272            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3273                if (DEBUG_EPHEMERAL) {
3274                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3275                            + " pkg: " + packageName + ", info:" + info);
3276                }
3277                continue;
3278            }
3279
3280            if (DEBUG_EPHEMERAL) {
3281                Slog.v(TAG, "Ephemeral resolver found;"
3282                        + " pkg: " + packageName + ", info:" + info);
3283            }
3284            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3285        }
3286        if (DEBUG_EPHEMERAL) {
3287            Slog.v(TAG, "Ephemeral resolver NOT found");
3288        }
3289        return null;
3290    }
3291
3292    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3293        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3294        intent.addCategory(Intent.CATEGORY_DEFAULT);
3295        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3296
3297        final int resolveFlags =
3298                MATCH_DIRECT_BOOT_AWARE
3299                | MATCH_DIRECT_BOOT_UNAWARE
3300                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3301        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3302                resolveFlags, UserHandle.USER_SYSTEM);
3303        // temporarily look for the old action
3304        if (matches.isEmpty()) {
3305            if (DEBUG_EPHEMERAL) {
3306                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3307            }
3308            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3309            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3310                    resolveFlags, UserHandle.USER_SYSTEM);
3311        }
3312        Iterator<ResolveInfo> iter = matches.iterator();
3313        while (iter.hasNext()) {
3314            final ResolveInfo rInfo = iter.next();
3315            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3316            if (ps != null) {
3317                final PermissionsState permissionsState = ps.getPermissionsState();
3318                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3319                    continue;
3320                }
3321            }
3322            iter.remove();
3323        }
3324        if (matches.size() == 0) {
3325            return null;
3326        } else if (matches.size() == 1) {
3327            return (ActivityInfo) matches.get(0).getComponentInfo();
3328        } else {
3329            throw new RuntimeException(
3330                    "There must be at most one ephemeral installer; found " + matches);
3331        }
3332    }
3333
3334    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3335            @NonNull ComponentName resolver) {
3336        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3337                .addCategory(Intent.CATEGORY_DEFAULT)
3338                .setPackage(resolver.getPackageName());
3339        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3340        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3341                UserHandle.USER_SYSTEM);
3342        // temporarily look for the old action
3343        if (matches.isEmpty()) {
3344            if (DEBUG_EPHEMERAL) {
3345                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3346            }
3347            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3348            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3349                    UserHandle.USER_SYSTEM);
3350        }
3351        if (matches.isEmpty()) {
3352            return null;
3353        }
3354        return matches.get(0).getComponentInfo().getComponentName();
3355    }
3356
3357    private void primeDomainVerificationsLPw(int userId) {
3358        if (DEBUG_DOMAIN_VERIFICATION) {
3359            Slog.d(TAG, "Priming domain verifications in user " + userId);
3360        }
3361
3362        SystemConfig systemConfig = SystemConfig.getInstance();
3363        ArraySet<String> packages = systemConfig.getLinkedApps();
3364
3365        for (String packageName : packages) {
3366            PackageParser.Package pkg = mPackages.get(packageName);
3367            if (pkg != null) {
3368                if (!pkg.isSystemApp()) {
3369                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3370                    continue;
3371                }
3372
3373                ArraySet<String> domains = null;
3374                for (PackageParser.Activity a : pkg.activities) {
3375                    for (ActivityIntentInfo filter : a.intents) {
3376                        if (hasValidDomains(filter)) {
3377                            if (domains == null) {
3378                                domains = new ArraySet<String>();
3379                            }
3380                            domains.addAll(filter.getHostsList());
3381                        }
3382                    }
3383                }
3384
3385                if (domains != null && domains.size() > 0) {
3386                    if (DEBUG_DOMAIN_VERIFICATION) {
3387                        Slog.v(TAG, "      + " + packageName);
3388                    }
3389                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3390                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3391                    // and then 'always' in the per-user state actually used for intent resolution.
3392                    final IntentFilterVerificationInfo ivi;
3393                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3394                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3395                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3396                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3397                } else {
3398                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3399                            + "' does not handle web links");
3400                }
3401            } else {
3402                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3403            }
3404        }
3405
3406        scheduleWritePackageRestrictionsLocked(userId);
3407        scheduleWriteSettingsLocked();
3408    }
3409
3410    private void applyFactoryDefaultBrowserLPw(int userId) {
3411        // The default browser app's package name is stored in a string resource,
3412        // with a product-specific overlay used for vendor customization.
3413        String browserPkg = mContext.getResources().getString(
3414                com.android.internal.R.string.default_browser);
3415        if (!TextUtils.isEmpty(browserPkg)) {
3416            // non-empty string => required to be a known package
3417            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3418            if (ps == null) {
3419                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3420                browserPkg = null;
3421            } else {
3422                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3423            }
3424        }
3425
3426        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3427        // default.  If there's more than one, just leave everything alone.
3428        if (browserPkg == null) {
3429            calculateDefaultBrowserLPw(userId);
3430        }
3431    }
3432
3433    private void calculateDefaultBrowserLPw(int userId) {
3434        List<String> allBrowsers = resolveAllBrowserApps(userId);
3435        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3436        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3437    }
3438
3439    private List<String> resolveAllBrowserApps(int userId) {
3440        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3441        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3442                PackageManager.MATCH_ALL, userId);
3443
3444        final int count = list.size();
3445        List<String> result = new ArrayList<String>(count);
3446        for (int i=0; i<count; i++) {
3447            ResolveInfo info = list.get(i);
3448            if (info.activityInfo == null
3449                    || !info.handleAllWebDataURI
3450                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3451                    || result.contains(info.activityInfo.packageName)) {
3452                continue;
3453            }
3454            result.add(info.activityInfo.packageName);
3455        }
3456
3457        return result;
3458    }
3459
3460    private boolean packageIsBrowser(String packageName, int userId) {
3461        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3462                PackageManager.MATCH_ALL, userId);
3463        final int N = list.size();
3464        for (int i = 0; i < N; i++) {
3465            ResolveInfo info = list.get(i);
3466            if (packageName.equals(info.activityInfo.packageName)) {
3467                return true;
3468            }
3469        }
3470        return false;
3471    }
3472
3473    private void checkDefaultBrowser() {
3474        final int myUserId = UserHandle.myUserId();
3475        final String packageName = getDefaultBrowserPackageName(myUserId);
3476        if (packageName != null) {
3477            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3478            if (info == null) {
3479                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3480                synchronized (mPackages) {
3481                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3482                }
3483            }
3484        }
3485    }
3486
3487    @Override
3488    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3489            throws RemoteException {
3490        try {
3491            return super.onTransact(code, data, reply, flags);
3492        } catch (RuntimeException e) {
3493            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3494                Slog.wtf(TAG, "Package Manager Crash", e);
3495            }
3496            throw e;
3497        }
3498    }
3499
3500    static int[] appendInts(int[] cur, int[] add) {
3501        if (add == null) return cur;
3502        if (cur == null) return add;
3503        final int N = add.length;
3504        for (int i=0; i<N; i++) {
3505            cur = appendInt(cur, add[i]);
3506        }
3507        return cur;
3508    }
3509
3510    /**
3511     * Returns whether or not a full application can see an instant application.
3512     * <p>
3513     * Currently, there are three cases in which this can occur:
3514     * <ol>
3515     * <li>The calling application is a "special" process. The special
3516     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3517     *     and {@code 0}</li>
3518     * <li>The calling application has the permission
3519     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3520     * <li>The calling application is the default launcher on the
3521     *     system partition.</li>
3522     * </ol>
3523     */
3524    private boolean canViewInstantApps(int callingUid, int userId) {
3525        if (callingUid == Process.SYSTEM_UID
3526                || callingUid == Process.SHELL_UID
3527                || callingUid == Process.ROOT_UID) {
3528            return true;
3529        }
3530        if (mContext.checkCallingOrSelfPermission(
3531                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3532            return true;
3533        }
3534        if (mContext.checkCallingOrSelfPermission(
3535                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3536            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3537            if (homeComponent != null
3538                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3539                return true;
3540            }
3541        }
3542        return false;
3543    }
3544
3545    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3546        if (!sUserManager.exists(userId)) return null;
3547        if (ps == null) {
3548            return null;
3549        }
3550        PackageParser.Package p = ps.pkg;
3551        if (p == null) {
3552            return null;
3553        }
3554        final int callingUid = Binder.getCallingUid();
3555        // Filter out ephemeral app metadata:
3556        //   * The system/shell/root can see metadata for any app
3557        //   * An installed app can see metadata for 1) other installed apps
3558        //     and 2) ephemeral apps that have explicitly interacted with it
3559        //   * Ephemeral apps can only see their own data and exposed installed apps
3560        //   * Holding a signature permission allows seeing instant apps
3561        if (filterAppAccessLPr(ps, callingUid, userId)) {
3562            return null;
3563        }
3564
3565        final PermissionsState permissionsState = ps.getPermissionsState();
3566
3567        // Compute GIDs only if requested
3568        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3569                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3570        // Compute granted permissions only if package has requested permissions
3571        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3572                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3573        final PackageUserState state = ps.readUserState(userId);
3574
3575        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3576                && ps.isSystem()) {
3577            flags |= MATCH_ANY_USER;
3578        }
3579
3580        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3581                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3582
3583        if (packageInfo == null) {
3584            return null;
3585        }
3586
3587        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3588                resolveExternalPackageNameLPr(p);
3589
3590        return packageInfo;
3591    }
3592
3593    @Override
3594    public void checkPackageStartable(String packageName, int userId) {
3595        final int callingUid = Binder.getCallingUid();
3596        if (getInstantAppPackageName(callingUid) != null) {
3597            throw new SecurityException("Instant applications don't have access to this method");
3598        }
3599        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3600        synchronized (mPackages) {
3601            final PackageSetting ps = mSettings.mPackages.get(packageName);
3602            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3603                throw new SecurityException("Package " + packageName + " was not found!");
3604            }
3605
3606            if (!ps.getInstalled(userId)) {
3607                throw new SecurityException(
3608                        "Package " + packageName + " was not installed for user " + userId + "!");
3609            }
3610
3611            if (mSafeMode && !ps.isSystem()) {
3612                throw new SecurityException("Package " + packageName + " not a system app!");
3613            }
3614
3615            if (mFrozenPackages.contains(packageName)) {
3616                throw new SecurityException("Package " + packageName + " is currently frozen!");
3617            }
3618
3619            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3620                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3621                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3622            }
3623        }
3624    }
3625
3626    @Override
3627    public boolean isPackageAvailable(String packageName, int userId) {
3628        if (!sUserManager.exists(userId)) return false;
3629        final int callingUid = Binder.getCallingUid();
3630        enforceCrossUserPermission(callingUid, userId,
3631                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3632        synchronized (mPackages) {
3633            PackageParser.Package p = mPackages.get(packageName);
3634            if (p != null) {
3635                final PackageSetting ps = (PackageSetting) p.mExtras;
3636                if (filterAppAccessLPr(ps, callingUid, userId)) {
3637                    return false;
3638                }
3639                if (ps != null) {
3640                    final PackageUserState state = ps.readUserState(userId);
3641                    if (state != null) {
3642                        return PackageParser.isAvailable(state);
3643                    }
3644                }
3645            }
3646        }
3647        return false;
3648    }
3649
3650    @Override
3651    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3652        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3653                flags, Binder.getCallingUid(), userId);
3654    }
3655
3656    @Override
3657    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3658            int flags, int userId) {
3659        return getPackageInfoInternal(versionedPackage.getPackageName(),
3660                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3661    }
3662
3663    /**
3664     * Important: The provided filterCallingUid is used exclusively to filter out packages
3665     * that can be seen based on user state. It's typically the original caller uid prior
3666     * to clearing. Because it can only be provided by trusted code, it's value can be
3667     * trusted and will be used as-is; unlike userId which will be validated by this method.
3668     */
3669    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3670            int flags, int filterCallingUid, int userId) {
3671        if (!sUserManager.exists(userId)) return null;
3672        flags = updateFlagsForPackage(flags, userId, packageName);
3673        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3674                false /* requireFullPermission */, false /* checkShell */, "get package info");
3675
3676        // reader
3677        synchronized (mPackages) {
3678            // Normalize package name to handle renamed packages and static libs
3679            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3680
3681            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3682            if (matchFactoryOnly) {
3683                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3684                if (ps != null) {
3685                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3686                        return null;
3687                    }
3688                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3689                        return null;
3690                    }
3691                    return generatePackageInfo(ps, flags, userId);
3692                }
3693            }
3694
3695            PackageParser.Package p = mPackages.get(packageName);
3696            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3697                return null;
3698            }
3699            if (DEBUG_PACKAGE_INFO)
3700                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3701            if (p != null) {
3702                final PackageSetting ps = (PackageSetting) p.mExtras;
3703                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3704                    return null;
3705                }
3706                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3707                    return null;
3708                }
3709                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3710            }
3711            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3712                final PackageSetting ps = mSettings.mPackages.get(packageName);
3713                if (ps == null) return null;
3714                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3715                    return null;
3716                }
3717                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3718                    return null;
3719                }
3720                return generatePackageInfo(ps, flags, userId);
3721            }
3722        }
3723        return null;
3724    }
3725
3726    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3727        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3728            return true;
3729        }
3730        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3731            return true;
3732        }
3733        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3734            return true;
3735        }
3736        return false;
3737    }
3738
3739    private boolean isComponentVisibleToInstantApp(
3740            @Nullable ComponentName component, @ComponentType int type) {
3741        if (type == TYPE_ACTIVITY) {
3742            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3743            return activity != null
3744                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3745                    : false;
3746        } else if (type == TYPE_RECEIVER) {
3747            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3748            return activity != null
3749                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3750                    : false;
3751        } else if (type == TYPE_SERVICE) {
3752            final PackageParser.Service service = mServices.mServices.get(component);
3753            return service != null
3754                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3755                    : false;
3756        } else if (type == TYPE_PROVIDER) {
3757            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3758            return provider != null
3759                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3760                    : false;
3761        } else if (type == TYPE_UNKNOWN) {
3762            return isComponentVisibleToInstantApp(component);
3763        }
3764        return false;
3765    }
3766
3767    /**
3768     * Returns whether or not access to the application should be filtered.
3769     * <p>
3770     * Access may be limited based upon whether the calling or target applications
3771     * are instant applications.
3772     *
3773     * @see #canAccessInstantApps(int)
3774     */
3775    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3776            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3777        // if we're in an isolated process, get the real calling UID
3778        if (Process.isIsolated(callingUid)) {
3779            callingUid = mIsolatedOwners.get(callingUid);
3780        }
3781        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3782        final boolean callerIsInstantApp = instantAppPkgName != null;
3783        if (ps == null) {
3784            if (callerIsInstantApp) {
3785                // pretend the application exists, but, needs to be filtered
3786                return true;
3787            }
3788            return false;
3789        }
3790        // if the target and caller are the same application, don't filter
3791        if (isCallerSameApp(ps.name, callingUid)) {
3792            return false;
3793        }
3794        if (callerIsInstantApp) {
3795            // request for a specific component; if it hasn't been explicitly exposed, filter
3796            if (component != null) {
3797                return !isComponentVisibleToInstantApp(component, componentType);
3798            }
3799            // request for application; if no components have been explicitly exposed, filter
3800            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3801        }
3802        if (ps.getInstantApp(userId)) {
3803            // caller can see all components of all instant applications, don't filter
3804            if (canViewInstantApps(callingUid, userId)) {
3805                return false;
3806            }
3807            // request for a specific instant application component, filter
3808            if (component != null) {
3809                return true;
3810            }
3811            // request for an instant application; if the caller hasn't been granted access, filter
3812            return !mInstantAppRegistry.isInstantAccessGranted(
3813                    userId, UserHandle.getAppId(callingUid), ps.appId);
3814        }
3815        return false;
3816    }
3817
3818    /**
3819     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3820     */
3821    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3822        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3823    }
3824
3825    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3826            int flags) {
3827        // Callers can access only the libs they depend on, otherwise they need to explicitly
3828        // ask for the shared libraries given the caller is allowed to access all static libs.
3829        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3830            // System/shell/root get to see all static libs
3831            final int appId = UserHandle.getAppId(uid);
3832            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3833                    || appId == Process.ROOT_UID) {
3834                return false;
3835            }
3836        }
3837
3838        // No package means no static lib as it is always on internal storage
3839        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3840            return false;
3841        }
3842
3843        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3844                ps.pkg.staticSharedLibVersion);
3845        if (libEntry == null) {
3846            return false;
3847        }
3848
3849        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3850        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3851        if (uidPackageNames == null) {
3852            return true;
3853        }
3854
3855        for (String uidPackageName : uidPackageNames) {
3856            if (ps.name.equals(uidPackageName)) {
3857                return false;
3858            }
3859            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3860            if (uidPs != null) {
3861                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3862                        libEntry.info.getName());
3863                if (index < 0) {
3864                    continue;
3865                }
3866                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3867                    return false;
3868                }
3869            }
3870        }
3871        return true;
3872    }
3873
3874    @Override
3875    public String[] currentToCanonicalPackageNames(String[] names) {
3876        final int callingUid = Binder.getCallingUid();
3877        if (getInstantAppPackageName(callingUid) != null) {
3878            return names;
3879        }
3880        final String[] out = new String[names.length];
3881        // reader
3882        synchronized (mPackages) {
3883            final int callingUserId = UserHandle.getUserId(callingUid);
3884            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3885            for (int i=names.length-1; i>=0; i--) {
3886                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3887                boolean translateName = false;
3888                if (ps != null && ps.realName != null) {
3889                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3890                    translateName = !targetIsInstantApp
3891                            || canViewInstantApps
3892                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3893                                    UserHandle.getAppId(callingUid), ps.appId);
3894                }
3895                out[i] = translateName ? ps.realName : names[i];
3896            }
3897        }
3898        return out;
3899    }
3900
3901    @Override
3902    public String[] canonicalToCurrentPackageNames(String[] names) {
3903        final int callingUid = Binder.getCallingUid();
3904        if (getInstantAppPackageName(callingUid) != null) {
3905            return names;
3906        }
3907        final String[] out = new String[names.length];
3908        // reader
3909        synchronized (mPackages) {
3910            final int callingUserId = UserHandle.getUserId(callingUid);
3911            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3912            for (int i=names.length-1; i>=0; i--) {
3913                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3914                boolean translateName = false;
3915                if (cur != null) {
3916                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3917                    final boolean targetIsInstantApp =
3918                            ps != null && ps.getInstantApp(callingUserId);
3919                    translateName = !targetIsInstantApp
3920                            || canViewInstantApps
3921                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3922                                    UserHandle.getAppId(callingUid), ps.appId);
3923                }
3924                out[i] = translateName ? cur : names[i];
3925            }
3926        }
3927        return out;
3928    }
3929
3930    @Override
3931    public int getPackageUid(String packageName, int flags, int userId) {
3932        if (!sUserManager.exists(userId)) return -1;
3933        final int callingUid = Binder.getCallingUid();
3934        flags = updateFlagsForPackage(flags, userId, packageName);
3935        enforceCrossUserPermission(callingUid, userId,
3936                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3937
3938        // reader
3939        synchronized (mPackages) {
3940            final PackageParser.Package p = mPackages.get(packageName);
3941            if (p != null && p.isMatch(flags)) {
3942                PackageSetting ps = (PackageSetting) p.mExtras;
3943                if (filterAppAccessLPr(ps, callingUid, userId)) {
3944                    return -1;
3945                }
3946                return UserHandle.getUid(userId, p.applicationInfo.uid);
3947            }
3948            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3949                final PackageSetting ps = mSettings.mPackages.get(packageName);
3950                if (ps != null && ps.isMatch(flags)
3951                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3952                    return UserHandle.getUid(userId, ps.appId);
3953                }
3954            }
3955        }
3956
3957        return -1;
3958    }
3959
3960    @Override
3961    public int[] getPackageGids(String packageName, int flags, int userId) {
3962        if (!sUserManager.exists(userId)) return null;
3963        final int callingUid = Binder.getCallingUid();
3964        flags = updateFlagsForPackage(flags, userId, packageName);
3965        enforceCrossUserPermission(callingUid, userId,
3966                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3967
3968        // reader
3969        synchronized (mPackages) {
3970            final PackageParser.Package p = mPackages.get(packageName);
3971            if (p != null && p.isMatch(flags)) {
3972                PackageSetting ps = (PackageSetting) p.mExtras;
3973                if (filterAppAccessLPr(ps, callingUid, userId)) {
3974                    return null;
3975                }
3976                // TODO: Shouldn't this be checking for package installed state for userId and
3977                // return null?
3978                return ps.getPermissionsState().computeGids(userId);
3979            }
3980            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3981                final PackageSetting ps = mSettings.mPackages.get(packageName);
3982                if (ps != null && ps.isMatch(flags)
3983                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3984                    return ps.getPermissionsState().computeGids(userId);
3985                }
3986            }
3987        }
3988
3989        return null;
3990    }
3991
3992    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3993        if (bp.perm != null) {
3994            return PackageParser.generatePermissionInfo(bp.perm, flags);
3995        }
3996        PermissionInfo pi = new PermissionInfo();
3997        pi.name = bp.name;
3998        pi.packageName = bp.sourcePackage;
3999        pi.nonLocalizedLabel = bp.name;
4000        pi.protectionLevel = bp.protectionLevel;
4001        return pi;
4002    }
4003
4004    @Override
4005    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4006        final int callingUid = Binder.getCallingUid();
4007        if (getInstantAppPackageName(callingUid) != null) {
4008            return null;
4009        }
4010        // reader
4011        synchronized (mPackages) {
4012            final BasePermission p = mSettings.mPermissions.get(name);
4013            if (p == null) {
4014                return null;
4015            }
4016            // If the caller is an app that targets pre 26 SDK drop protection flags.
4017            final PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4018            if (permissionInfo != null) {
4019                permissionInfo.protectionLevel = adjustPermissionProtectionFlagsLPr(
4020                        permissionInfo.protectionLevel, packageName, callingUid);
4021            }
4022            return permissionInfo;
4023        }
4024    }
4025
4026    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4027            String packageName, int uid) {
4028        // Signature permission flags area always reported
4029        final int protectionLevelMasked = protectionLevel
4030                & (PermissionInfo.PROTECTION_NORMAL
4031                | PermissionInfo.PROTECTION_DANGEROUS
4032                | PermissionInfo.PROTECTION_SIGNATURE);
4033        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4034            return protectionLevel;
4035        }
4036
4037        // System sees all flags.
4038        final int appId = UserHandle.getAppId(uid);
4039        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4040                || appId == Process.SHELL_UID) {
4041            return protectionLevel;
4042        }
4043
4044        // Normalize package name to handle renamed packages and static libs
4045        packageName = resolveInternalPackageNameLPr(packageName,
4046                PackageManager.VERSION_CODE_HIGHEST);
4047
4048        // Apps that target O see flags for all protection levels.
4049        final PackageSetting ps = mSettings.mPackages.get(packageName);
4050        if (ps == null) {
4051            return protectionLevel;
4052        }
4053        if (ps.appId != appId) {
4054            return protectionLevel;
4055        }
4056
4057        final PackageParser.Package pkg = mPackages.get(packageName);
4058        if (pkg == null) {
4059            return protectionLevel;
4060        }
4061        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4062            return protectionLevelMasked;
4063        }
4064
4065        return protectionLevel;
4066    }
4067
4068    @Override
4069    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4070            int flags) {
4071        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4072            return null;
4073        }
4074        // reader
4075        synchronized (mPackages) {
4076            if (group != null && !mPermissionGroups.containsKey(group)) {
4077                // This is thrown as NameNotFoundException
4078                return null;
4079            }
4080
4081            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4082            for (BasePermission p : mSettings.mPermissions.values()) {
4083                if (group == null) {
4084                    if (p.perm == null || p.perm.info.group == null) {
4085                        out.add(generatePermissionInfo(p, flags));
4086                    }
4087                } else {
4088                    if (p.perm != null && group.equals(p.perm.info.group)) {
4089                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4090                    }
4091                }
4092            }
4093            return new ParceledListSlice<>(out);
4094        }
4095    }
4096
4097    @Override
4098    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4099        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4100            return null;
4101        }
4102        // reader
4103        synchronized (mPackages) {
4104            return PackageParser.generatePermissionGroupInfo(
4105                    mPermissionGroups.get(name), flags);
4106        }
4107    }
4108
4109    @Override
4110    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4111        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4112            return ParceledListSlice.emptyList();
4113        }
4114        // reader
4115        synchronized (mPackages) {
4116            final int N = mPermissionGroups.size();
4117            ArrayList<PermissionGroupInfo> out
4118                    = new ArrayList<PermissionGroupInfo>(N);
4119            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4120                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4121            }
4122            return new ParceledListSlice<>(out);
4123        }
4124    }
4125
4126    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4127            int filterCallingUid, int userId) {
4128        if (!sUserManager.exists(userId)) return null;
4129        PackageSetting ps = mSettings.mPackages.get(packageName);
4130        if (ps != null) {
4131            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4132                return null;
4133            }
4134            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4135                return null;
4136            }
4137            if (ps.pkg == null) {
4138                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4139                if (pInfo != null) {
4140                    return pInfo.applicationInfo;
4141                }
4142                return null;
4143            }
4144            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4145                    ps.readUserState(userId), userId);
4146            if (ai != null) {
4147                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4148            }
4149            return ai;
4150        }
4151        return null;
4152    }
4153
4154    @Override
4155    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4156        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4157    }
4158
4159    /**
4160     * Important: The provided filterCallingUid is used exclusively to filter out applications
4161     * that can be seen based on user state. It's typically the original caller uid prior
4162     * to clearing. Because it can only be provided by trusted code, it's value can be
4163     * trusted and will be used as-is; unlike userId which will be validated by this method.
4164     */
4165    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4166            int filterCallingUid, int userId) {
4167        if (!sUserManager.exists(userId)) return null;
4168        flags = updateFlagsForApplication(flags, userId, packageName);
4169        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4170                false /* requireFullPermission */, false /* checkShell */, "get application info");
4171
4172        // writer
4173        synchronized (mPackages) {
4174            // Normalize package name to handle renamed packages and static libs
4175            packageName = resolveInternalPackageNameLPr(packageName,
4176                    PackageManager.VERSION_CODE_HIGHEST);
4177
4178            PackageParser.Package p = mPackages.get(packageName);
4179            if (DEBUG_PACKAGE_INFO) Log.v(
4180                    TAG, "getApplicationInfo " + packageName
4181                    + ": " + p);
4182            if (p != null) {
4183                PackageSetting ps = mSettings.mPackages.get(packageName);
4184                if (ps == null) return null;
4185                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4186                    return null;
4187                }
4188                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4189                    return null;
4190                }
4191                // Note: isEnabledLP() does not apply here - always return info
4192                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4193                        p, flags, ps.readUserState(userId), userId);
4194                if (ai != null) {
4195                    ai.packageName = resolveExternalPackageNameLPr(p);
4196                }
4197                return ai;
4198            }
4199            if ("android".equals(packageName)||"system".equals(packageName)) {
4200                return mAndroidApplication;
4201            }
4202            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4203                // Already generates the external package name
4204                return generateApplicationInfoFromSettingsLPw(packageName,
4205                        flags, filterCallingUid, userId);
4206            }
4207        }
4208        return null;
4209    }
4210
4211    private String normalizePackageNameLPr(String packageName) {
4212        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4213        return normalizedPackageName != null ? normalizedPackageName : packageName;
4214    }
4215
4216    @Override
4217    public void deletePreloadsFileCache() {
4218        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4219            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4220        }
4221        File dir = Environment.getDataPreloadsFileCacheDirectory();
4222        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4223        FileUtils.deleteContents(dir);
4224    }
4225
4226    @Override
4227    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4228            final int storageFlags, final IPackageDataObserver observer) {
4229        mContext.enforceCallingOrSelfPermission(
4230                android.Manifest.permission.CLEAR_APP_CACHE, null);
4231        mHandler.post(() -> {
4232            boolean success = false;
4233            try {
4234                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4235                success = true;
4236            } catch (IOException e) {
4237                Slog.w(TAG, e);
4238            }
4239            if (observer != null) {
4240                try {
4241                    observer.onRemoveCompleted(null, success);
4242                } catch (RemoteException e) {
4243                    Slog.w(TAG, e);
4244                }
4245            }
4246        });
4247    }
4248
4249    @Override
4250    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4251            final int storageFlags, final IntentSender pi) {
4252        mContext.enforceCallingOrSelfPermission(
4253                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4254        mHandler.post(() -> {
4255            boolean success = false;
4256            try {
4257                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4258                success = true;
4259            } catch (IOException e) {
4260                Slog.w(TAG, e);
4261            }
4262            if (pi != null) {
4263                try {
4264                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4265                } catch (SendIntentException e) {
4266                    Slog.w(TAG, e);
4267                }
4268            }
4269        });
4270    }
4271
4272    /**
4273     * Blocking call to clear various types of cached data across the system
4274     * until the requested bytes are available.
4275     */
4276    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4277        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4278        final File file = storage.findPathForUuid(volumeUuid);
4279        if (file.getUsableSpace() >= bytes) return;
4280
4281        if (ENABLE_FREE_CACHE_V2) {
4282            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4283                    volumeUuid);
4284            final boolean aggressive = (storageFlags
4285                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4286            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4287
4288            // 1. Pre-flight to determine if we have any chance to succeed
4289            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4290            if (internalVolume && (aggressive || SystemProperties
4291                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4292                deletePreloadsFileCache();
4293                if (file.getUsableSpace() >= bytes) return;
4294            }
4295
4296            // 3. Consider parsed APK data (aggressive only)
4297            if (internalVolume && aggressive) {
4298                FileUtils.deleteContents(mCacheDir);
4299                if (file.getUsableSpace() >= bytes) return;
4300            }
4301
4302            // 4. Consider cached app data (above quotas)
4303            try {
4304                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4305                        Installer.FLAG_FREE_CACHE_V2);
4306            } catch (InstallerException ignored) {
4307            }
4308            if (file.getUsableSpace() >= bytes) return;
4309
4310            // 5. Consider shared libraries with refcount=0 and age>min cache period
4311            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4312                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4313                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4314                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4315                return;
4316            }
4317
4318            // 6. Consider dexopt output (aggressive only)
4319            // TODO: Implement
4320
4321            // 7. Consider installed instant apps unused longer than min cache period
4322            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4323                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4324                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4325                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4326                return;
4327            }
4328
4329            // 8. Consider cached app data (below quotas)
4330            try {
4331                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4332                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4333            } catch (InstallerException ignored) {
4334            }
4335            if (file.getUsableSpace() >= bytes) return;
4336
4337            // 9. Consider DropBox entries
4338            // TODO: Implement
4339
4340            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4341            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4342                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4343                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4344                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4345                return;
4346            }
4347        } else {
4348            try {
4349                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4350            } catch (InstallerException ignored) {
4351            }
4352            if (file.getUsableSpace() >= bytes) return;
4353        }
4354
4355        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4356    }
4357
4358    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4359            throws IOException {
4360        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4361        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4362
4363        List<VersionedPackage> packagesToDelete = null;
4364        final long now = System.currentTimeMillis();
4365
4366        synchronized (mPackages) {
4367            final int[] allUsers = sUserManager.getUserIds();
4368            final int libCount = mSharedLibraries.size();
4369            for (int i = 0; i < libCount; i++) {
4370                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4371                if (versionedLib == null) {
4372                    continue;
4373                }
4374                final int versionCount = versionedLib.size();
4375                for (int j = 0; j < versionCount; j++) {
4376                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4377                    // Skip packages that are not static shared libs.
4378                    if (!libInfo.isStatic()) {
4379                        break;
4380                    }
4381                    // Important: We skip static shared libs used for some user since
4382                    // in such a case we need to keep the APK on the device. The check for
4383                    // a lib being used for any user is performed by the uninstall call.
4384                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4385                    // Resolve the package name - we use synthetic package names internally
4386                    final String internalPackageName = resolveInternalPackageNameLPr(
4387                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4388                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4389                    // Skip unused static shared libs cached less than the min period
4390                    // to prevent pruning a lib needed by a subsequently installed package.
4391                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4392                        continue;
4393                    }
4394                    if (packagesToDelete == null) {
4395                        packagesToDelete = new ArrayList<>();
4396                    }
4397                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4398                            declaringPackage.getVersionCode()));
4399                }
4400            }
4401        }
4402
4403        if (packagesToDelete != null) {
4404            final int packageCount = packagesToDelete.size();
4405            for (int i = 0; i < packageCount; i++) {
4406                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4407                // Delete the package synchronously (will fail of the lib used for any user).
4408                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4409                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4410                                == PackageManager.DELETE_SUCCEEDED) {
4411                    if (volume.getUsableSpace() >= neededSpace) {
4412                        return true;
4413                    }
4414                }
4415            }
4416        }
4417
4418        return false;
4419    }
4420
4421    /**
4422     * Update given flags based on encryption status of current user.
4423     */
4424    private int updateFlags(int flags, int userId) {
4425        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4426                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4427            // Caller expressed an explicit opinion about what encryption
4428            // aware/unaware components they want to see, so fall through and
4429            // give them what they want
4430        } else {
4431            // Caller expressed no opinion, so match based on user state
4432            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4433                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4434            } else {
4435                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4436            }
4437        }
4438        return flags;
4439    }
4440
4441    private UserManagerInternal getUserManagerInternal() {
4442        if (mUserManagerInternal == null) {
4443            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4444        }
4445        return mUserManagerInternal;
4446    }
4447
4448    private DeviceIdleController.LocalService getDeviceIdleController() {
4449        if (mDeviceIdleController == null) {
4450            mDeviceIdleController =
4451                    LocalServices.getService(DeviceIdleController.LocalService.class);
4452        }
4453        return mDeviceIdleController;
4454    }
4455
4456    /**
4457     * Update given flags when being used to request {@link PackageInfo}.
4458     */
4459    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4460        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4461        boolean triaged = true;
4462        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4463                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4464            // Caller is asking for component details, so they'd better be
4465            // asking for specific encryption matching behavior, or be triaged
4466            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4467                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4468                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4469                triaged = false;
4470            }
4471        }
4472        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4473                | PackageManager.MATCH_SYSTEM_ONLY
4474                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4475            triaged = false;
4476        }
4477        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4478            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4479                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4480                    + Debug.getCallers(5));
4481        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4482                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4483            // If the caller wants all packages and has a restricted profile associated with it,
4484            // then match all users. This is to make sure that launchers that need to access work
4485            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4486            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4487            flags |= PackageManager.MATCH_ANY_USER;
4488        }
4489        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4490            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4491                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4492        }
4493        return updateFlags(flags, userId);
4494    }
4495
4496    /**
4497     * Update given flags when being used to request {@link ApplicationInfo}.
4498     */
4499    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4500        return updateFlagsForPackage(flags, userId, cookie);
4501    }
4502
4503    /**
4504     * Update given flags when being used to request {@link ComponentInfo}.
4505     */
4506    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4507        if (cookie instanceof Intent) {
4508            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4509                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4510            }
4511        }
4512
4513        boolean triaged = true;
4514        // Caller is asking for component details, so they'd better be
4515        // asking for specific encryption matching behavior, or be triaged
4516        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4517                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4518                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4519            triaged = false;
4520        }
4521        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4522            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4523                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4524        }
4525
4526        return updateFlags(flags, userId);
4527    }
4528
4529    /**
4530     * Update given intent when being used to request {@link ResolveInfo}.
4531     */
4532    private Intent updateIntentForResolve(Intent intent) {
4533        if (intent.getSelector() != null) {
4534            intent = intent.getSelector();
4535        }
4536        if (DEBUG_PREFERRED) {
4537            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4538        }
4539        return intent;
4540    }
4541
4542    /**
4543     * Update given flags when being used to request {@link ResolveInfo}.
4544     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4545     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4546     * flag set. However, this flag is only honoured in three circumstances:
4547     * <ul>
4548     * <li>when called from a system process</li>
4549     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4550     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4551     * action and a {@code android.intent.category.BROWSABLE} category</li>
4552     * </ul>
4553     */
4554    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4555        return updateFlagsForResolve(flags, userId, intent, callingUid,
4556                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4557    }
4558    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4559            boolean wantInstantApps) {
4560        return updateFlagsForResolve(flags, userId, intent, callingUid,
4561                wantInstantApps, false /*onlyExposedExplicitly*/);
4562    }
4563    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4564            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4565        // Safe mode means we shouldn't match any third-party components
4566        if (mSafeMode) {
4567            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4568        }
4569        if (getInstantAppPackageName(callingUid) != null) {
4570            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4571            if (onlyExposedExplicitly) {
4572                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4573            }
4574            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4575            flags |= PackageManager.MATCH_INSTANT;
4576        } else {
4577            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4578            final boolean allowMatchInstant =
4579                    (wantInstantApps
4580                            && Intent.ACTION_VIEW.equals(intent.getAction())
4581                            && hasWebURI(intent))
4582                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4583            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4584                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4585            if (!allowMatchInstant) {
4586                flags &= ~PackageManager.MATCH_INSTANT;
4587            }
4588        }
4589        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4590    }
4591
4592    @Override
4593    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4594        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4595    }
4596
4597    /**
4598     * Important: The provided filterCallingUid is used exclusively to filter out activities
4599     * that can be seen based on user state. It's typically the original caller uid prior
4600     * to clearing. Because it can only be provided by trusted code, it's value can be
4601     * trusted and will be used as-is; unlike userId which will be validated by this method.
4602     */
4603    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4604            int filterCallingUid, int userId) {
4605        if (!sUserManager.exists(userId)) return null;
4606        flags = updateFlagsForComponent(flags, userId, component);
4607        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4608                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4609        synchronized (mPackages) {
4610            PackageParser.Activity a = mActivities.mActivities.get(component);
4611
4612            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4613            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4614                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4615                if (ps == null) return null;
4616                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4617                    return null;
4618                }
4619                return PackageParser.generateActivityInfo(
4620                        a, flags, ps.readUserState(userId), userId);
4621            }
4622            if (mResolveComponentName.equals(component)) {
4623                return PackageParser.generateActivityInfo(
4624                        mResolveActivity, flags, new PackageUserState(), userId);
4625            }
4626        }
4627        return null;
4628    }
4629
4630    @Override
4631    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4632            String resolvedType) {
4633        synchronized (mPackages) {
4634            if (component.equals(mResolveComponentName)) {
4635                // The resolver supports EVERYTHING!
4636                return true;
4637            }
4638            final int callingUid = Binder.getCallingUid();
4639            final int callingUserId = UserHandle.getUserId(callingUid);
4640            PackageParser.Activity a = mActivities.mActivities.get(component);
4641            if (a == null) {
4642                return false;
4643            }
4644            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4645            if (ps == null) {
4646                return false;
4647            }
4648            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4649                return false;
4650            }
4651            for (int i=0; i<a.intents.size(); i++) {
4652                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4653                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4654                    return true;
4655                }
4656            }
4657            return false;
4658        }
4659    }
4660
4661    @Override
4662    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4663        if (!sUserManager.exists(userId)) return null;
4664        final int callingUid = Binder.getCallingUid();
4665        flags = updateFlagsForComponent(flags, userId, component);
4666        enforceCrossUserPermission(callingUid, userId,
4667                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4668        synchronized (mPackages) {
4669            PackageParser.Activity a = mReceivers.mActivities.get(component);
4670            if (DEBUG_PACKAGE_INFO) Log.v(
4671                TAG, "getReceiverInfo " + component + ": " + a);
4672            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4673                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4674                if (ps == null) return null;
4675                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4676                    return null;
4677                }
4678                return PackageParser.generateActivityInfo(
4679                        a, flags, ps.readUserState(userId), userId);
4680            }
4681        }
4682        return null;
4683    }
4684
4685    @Override
4686    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4687            int flags, int userId) {
4688        if (!sUserManager.exists(userId)) return null;
4689        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4690        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4691            return null;
4692        }
4693
4694        flags = updateFlagsForPackage(flags, userId, null);
4695
4696        final boolean canSeeStaticLibraries =
4697                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4698                        == PERMISSION_GRANTED
4699                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4700                        == PERMISSION_GRANTED
4701                || canRequestPackageInstallsInternal(packageName,
4702                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4703                        false  /* throwIfPermNotDeclared*/)
4704                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4705                        == PERMISSION_GRANTED;
4706
4707        synchronized (mPackages) {
4708            List<SharedLibraryInfo> result = null;
4709
4710            final int libCount = mSharedLibraries.size();
4711            for (int i = 0; i < libCount; i++) {
4712                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4713                if (versionedLib == null) {
4714                    continue;
4715                }
4716
4717                final int versionCount = versionedLib.size();
4718                for (int j = 0; j < versionCount; j++) {
4719                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4720                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4721                        break;
4722                    }
4723                    final long identity = Binder.clearCallingIdentity();
4724                    try {
4725                        PackageInfo packageInfo = getPackageInfoVersioned(
4726                                libInfo.getDeclaringPackage(), flags
4727                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4728                        if (packageInfo == null) {
4729                            continue;
4730                        }
4731                    } finally {
4732                        Binder.restoreCallingIdentity(identity);
4733                    }
4734
4735                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4736                            libInfo.getVersion(), libInfo.getType(),
4737                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4738                            flags, userId));
4739
4740                    if (result == null) {
4741                        result = new ArrayList<>();
4742                    }
4743                    result.add(resLibInfo);
4744                }
4745            }
4746
4747            return result != null ? new ParceledListSlice<>(result) : null;
4748        }
4749    }
4750
4751    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4752            SharedLibraryInfo libInfo, int flags, int userId) {
4753        List<VersionedPackage> versionedPackages = null;
4754        final int packageCount = mSettings.mPackages.size();
4755        for (int i = 0; i < packageCount; i++) {
4756            PackageSetting ps = mSettings.mPackages.valueAt(i);
4757
4758            if (ps == null) {
4759                continue;
4760            }
4761
4762            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4763                continue;
4764            }
4765
4766            final String libName = libInfo.getName();
4767            if (libInfo.isStatic()) {
4768                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4769                if (libIdx < 0) {
4770                    continue;
4771                }
4772                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4773                    continue;
4774                }
4775                if (versionedPackages == null) {
4776                    versionedPackages = new ArrayList<>();
4777                }
4778                // If the dependent is a static shared lib, use the public package name
4779                String dependentPackageName = ps.name;
4780                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4781                    dependentPackageName = ps.pkg.manifestPackageName;
4782                }
4783                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4784            } else if (ps.pkg != null) {
4785                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4786                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4787                    if (versionedPackages == null) {
4788                        versionedPackages = new ArrayList<>();
4789                    }
4790                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4791                }
4792            }
4793        }
4794
4795        return versionedPackages;
4796    }
4797
4798    @Override
4799    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4800        if (!sUserManager.exists(userId)) return null;
4801        final int callingUid = Binder.getCallingUid();
4802        flags = updateFlagsForComponent(flags, userId, component);
4803        enforceCrossUserPermission(callingUid, userId,
4804                false /* requireFullPermission */, false /* checkShell */, "get service info");
4805        synchronized (mPackages) {
4806            PackageParser.Service s = mServices.mServices.get(component);
4807            if (DEBUG_PACKAGE_INFO) Log.v(
4808                TAG, "getServiceInfo " + component + ": " + s);
4809            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4810                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4811                if (ps == null) return null;
4812                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4813                    return null;
4814                }
4815                return PackageParser.generateServiceInfo(
4816                        s, flags, ps.readUserState(userId), userId);
4817            }
4818        }
4819        return null;
4820    }
4821
4822    @Override
4823    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4824        if (!sUserManager.exists(userId)) return null;
4825        final int callingUid = Binder.getCallingUid();
4826        flags = updateFlagsForComponent(flags, userId, component);
4827        enforceCrossUserPermission(callingUid, userId,
4828                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4829        synchronized (mPackages) {
4830            PackageParser.Provider p = mProviders.mProviders.get(component);
4831            if (DEBUG_PACKAGE_INFO) Log.v(
4832                TAG, "getProviderInfo " + component + ": " + p);
4833            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4834                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4835                if (ps == null) return null;
4836                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4837                    return null;
4838                }
4839                return PackageParser.generateProviderInfo(
4840                        p, flags, ps.readUserState(userId), userId);
4841            }
4842        }
4843        return null;
4844    }
4845
4846    @Override
4847    public String[] getSystemSharedLibraryNames() {
4848        // allow instant applications
4849        synchronized (mPackages) {
4850            Set<String> libs = null;
4851            final int libCount = mSharedLibraries.size();
4852            for (int i = 0; i < libCount; i++) {
4853                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4854                if (versionedLib == null) {
4855                    continue;
4856                }
4857                final int versionCount = versionedLib.size();
4858                for (int j = 0; j < versionCount; j++) {
4859                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4860                    if (!libEntry.info.isStatic()) {
4861                        if (libs == null) {
4862                            libs = new ArraySet<>();
4863                        }
4864                        libs.add(libEntry.info.getName());
4865                        break;
4866                    }
4867                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4868                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4869                            UserHandle.getUserId(Binder.getCallingUid()),
4870                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4871                        if (libs == null) {
4872                            libs = new ArraySet<>();
4873                        }
4874                        libs.add(libEntry.info.getName());
4875                        break;
4876                    }
4877                }
4878            }
4879
4880            if (libs != null) {
4881                String[] libsArray = new String[libs.size()];
4882                libs.toArray(libsArray);
4883                return libsArray;
4884            }
4885
4886            return null;
4887        }
4888    }
4889
4890    @Override
4891    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4892        // allow instant applications
4893        synchronized (mPackages) {
4894            return mServicesSystemSharedLibraryPackageName;
4895        }
4896    }
4897
4898    @Override
4899    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4900        // allow instant applications
4901        synchronized (mPackages) {
4902            return mSharedSystemSharedLibraryPackageName;
4903        }
4904    }
4905
4906    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4907        for (int i = userList.length - 1; i >= 0; --i) {
4908            final int userId = userList[i];
4909            // don't add instant app to the list of updates
4910            if (pkgSetting.getInstantApp(userId)) {
4911                continue;
4912            }
4913            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4914            if (changedPackages == null) {
4915                changedPackages = new SparseArray<>();
4916                mChangedPackages.put(userId, changedPackages);
4917            }
4918            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4919            if (sequenceNumbers == null) {
4920                sequenceNumbers = new HashMap<>();
4921                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4922            }
4923            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4924            if (sequenceNumber != null) {
4925                changedPackages.remove(sequenceNumber);
4926            }
4927            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4928            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4929        }
4930        mChangedPackagesSequenceNumber++;
4931    }
4932
4933    @Override
4934    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4935        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4936            return null;
4937        }
4938        synchronized (mPackages) {
4939            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4940                return null;
4941            }
4942            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4943            if (changedPackages == null) {
4944                return null;
4945            }
4946            final List<String> packageNames =
4947                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4948            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4949                final String packageName = changedPackages.get(i);
4950                if (packageName != null) {
4951                    packageNames.add(packageName);
4952                }
4953            }
4954            return packageNames.isEmpty()
4955                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4956        }
4957    }
4958
4959    @Override
4960    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4961        // allow instant applications
4962        ArrayList<FeatureInfo> res;
4963        synchronized (mAvailableFeatures) {
4964            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4965            res.addAll(mAvailableFeatures.values());
4966        }
4967        final FeatureInfo fi = new FeatureInfo();
4968        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4969                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4970        res.add(fi);
4971
4972        return new ParceledListSlice<>(res);
4973    }
4974
4975    @Override
4976    public boolean hasSystemFeature(String name, int version) {
4977        // allow instant applications
4978        synchronized (mAvailableFeatures) {
4979            final FeatureInfo feat = mAvailableFeatures.get(name);
4980            if (feat == null) {
4981                return false;
4982            } else {
4983                return feat.version >= version;
4984            }
4985        }
4986    }
4987
4988    @Override
4989    public int checkPermission(String permName, String pkgName, int userId) {
4990        if (!sUserManager.exists(userId)) {
4991            return PackageManager.PERMISSION_DENIED;
4992        }
4993        final int callingUid = Binder.getCallingUid();
4994
4995        synchronized (mPackages) {
4996            final PackageParser.Package p = mPackages.get(pkgName);
4997            if (p != null && p.mExtras != null) {
4998                final PackageSetting ps = (PackageSetting) p.mExtras;
4999                if (filterAppAccessLPr(ps, callingUid, userId)) {
5000                    return PackageManager.PERMISSION_DENIED;
5001                }
5002                final boolean instantApp = ps.getInstantApp(userId);
5003                final PermissionsState permissionsState = ps.getPermissionsState();
5004                if (permissionsState.hasPermission(permName, userId)) {
5005                    if (instantApp) {
5006                        BasePermission bp = mSettings.mPermissions.get(permName);
5007                        if (bp != null && bp.isInstant()) {
5008                            return PackageManager.PERMISSION_GRANTED;
5009                        }
5010                    } else {
5011                        return PackageManager.PERMISSION_GRANTED;
5012                    }
5013                }
5014                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5015                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5016                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5017                    return PackageManager.PERMISSION_GRANTED;
5018                }
5019            }
5020        }
5021
5022        return PackageManager.PERMISSION_DENIED;
5023    }
5024
5025    @Override
5026    public int checkUidPermission(String permName, int uid) {
5027        final int callingUid = Binder.getCallingUid();
5028        final int callingUserId = UserHandle.getUserId(callingUid);
5029        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5030        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5031        final int userId = UserHandle.getUserId(uid);
5032        if (!sUserManager.exists(userId)) {
5033            return PackageManager.PERMISSION_DENIED;
5034        }
5035
5036        synchronized (mPackages) {
5037            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5038            if (obj != null) {
5039                if (obj instanceof SharedUserSetting) {
5040                    if (isCallerInstantApp) {
5041                        return PackageManager.PERMISSION_DENIED;
5042                    }
5043                } else if (obj instanceof PackageSetting) {
5044                    final PackageSetting ps = (PackageSetting) obj;
5045                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5046                        return PackageManager.PERMISSION_DENIED;
5047                    }
5048                }
5049                final SettingBase settingBase = (SettingBase) obj;
5050                final PermissionsState permissionsState = settingBase.getPermissionsState();
5051                if (permissionsState.hasPermission(permName, userId)) {
5052                    if (isUidInstantApp) {
5053                        BasePermission bp = mSettings.mPermissions.get(permName);
5054                        if (bp != null && bp.isInstant()) {
5055                            return PackageManager.PERMISSION_GRANTED;
5056                        }
5057                    } else {
5058                        return PackageManager.PERMISSION_GRANTED;
5059                    }
5060                }
5061                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5062                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5063                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5064                    return PackageManager.PERMISSION_GRANTED;
5065                }
5066            } else {
5067                ArraySet<String> perms = mSystemPermissions.get(uid);
5068                if (perms != null) {
5069                    if (perms.contains(permName)) {
5070                        return PackageManager.PERMISSION_GRANTED;
5071                    }
5072                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5073                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5074                        return PackageManager.PERMISSION_GRANTED;
5075                    }
5076                }
5077            }
5078        }
5079
5080        return PackageManager.PERMISSION_DENIED;
5081    }
5082
5083    @Override
5084    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5085        if (UserHandle.getCallingUserId() != userId) {
5086            mContext.enforceCallingPermission(
5087                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5088                    "isPermissionRevokedByPolicy for user " + userId);
5089        }
5090
5091        if (checkPermission(permission, packageName, userId)
5092                == PackageManager.PERMISSION_GRANTED) {
5093            return false;
5094        }
5095
5096        final int callingUid = Binder.getCallingUid();
5097        if (getInstantAppPackageName(callingUid) != null) {
5098            if (!isCallerSameApp(packageName, callingUid)) {
5099                return false;
5100            }
5101        } else {
5102            if (isInstantApp(packageName, userId)) {
5103                return false;
5104            }
5105        }
5106
5107        final long identity = Binder.clearCallingIdentity();
5108        try {
5109            final int flags = getPermissionFlags(permission, packageName, userId);
5110            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5111        } finally {
5112            Binder.restoreCallingIdentity(identity);
5113        }
5114    }
5115
5116    @Override
5117    public String getPermissionControllerPackageName() {
5118        synchronized (mPackages) {
5119            return mRequiredInstallerPackage;
5120        }
5121    }
5122
5123    /**
5124     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5125     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5126     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5127     * @param message the message to log on security exception
5128     */
5129    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5130            boolean checkShell, String message) {
5131        if (userId < 0) {
5132            throw new IllegalArgumentException("Invalid userId " + userId);
5133        }
5134        if (checkShell) {
5135            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5136        }
5137        if (userId == UserHandle.getUserId(callingUid)) return;
5138        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5139            if (requireFullPermission) {
5140                mContext.enforceCallingOrSelfPermission(
5141                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5142            } else {
5143                try {
5144                    mContext.enforceCallingOrSelfPermission(
5145                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5146                } catch (SecurityException se) {
5147                    mContext.enforceCallingOrSelfPermission(
5148                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5149                }
5150            }
5151        }
5152    }
5153
5154    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5155        if (callingUid == Process.SHELL_UID) {
5156            if (userHandle >= 0
5157                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5158                throw new SecurityException("Shell does not have permission to access user "
5159                        + userHandle);
5160            } else if (userHandle < 0) {
5161                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5162                        + Debug.getCallers(3));
5163            }
5164        }
5165    }
5166
5167    private BasePermission findPermissionTreeLP(String permName) {
5168        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5169            if (permName.startsWith(bp.name) &&
5170                    permName.length() > bp.name.length() &&
5171                    permName.charAt(bp.name.length()) == '.') {
5172                return bp;
5173            }
5174        }
5175        return null;
5176    }
5177
5178    private BasePermission checkPermissionTreeLP(String permName) {
5179        if (permName != null) {
5180            BasePermission bp = findPermissionTreeLP(permName);
5181            if (bp != null) {
5182                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5183                    return bp;
5184                }
5185                throw new SecurityException("Calling uid "
5186                        + Binder.getCallingUid()
5187                        + " is not allowed to add to permission tree "
5188                        + bp.name + " owned by uid " + bp.uid);
5189            }
5190        }
5191        throw new SecurityException("No permission tree found for " + permName);
5192    }
5193
5194    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5195        if (s1 == null) {
5196            return s2 == null;
5197        }
5198        if (s2 == null) {
5199            return false;
5200        }
5201        if (s1.getClass() != s2.getClass()) {
5202            return false;
5203        }
5204        return s1.equals(s2);
5205    }
5206
5207    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5208        if (pi1.icon != pi2.icon) return false;
5209        if (pi1.logo != pi2.logo) return false;
5210        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5211        if (!compareStrings(pi1.name, pi2.name)) return false;
5212        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5213        // We'll take care of setting this one.
5214        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5215        // These are not currently stored in settings.
5216        //if (!compareStrings(pi1.group, pi2.group)) return false;
5217        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5218        //if (pi1.labelRes != pi2.labelRes) return false;
5219        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5220        return true;
5221    }
5222
5223    int permissionInfoFootprint(PermissionInfo info) {
5224        int size = info.name.length();
5225        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5226        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5227        return size;
5228    }
5229
5230    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5231        int size = 0;
5232        for (BasePermission perm : mSettings.mPermissions.values()) {
5233            if (perm.uid == tree.uid) {
5234                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5235            }
5236        }
5237        return size;
5238    }
5239
5240    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5241        // We calculate the max size of permissions defined by this uid and throw
5242        // if that plus the size of 'info' would exceed our stated maximum.
5243        if (tree.uid != Process.SYSTEM_UID) {
5244            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5245            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5246                throw new SecurityException("Permission tree size cap exceeded");
5247            }
5248        }
5249    }
5250
5251    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5252        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5253            throw new SecurityException("Instant apps can't add permissions");
5254        }
5255        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5256            throw new SecurityException("Label must be specified in permission");
5257        }
5258        BasePermission tree = checkPermissionTreeLP(info.name);
5259        BasePermission bp = mSettings.mPermissions.get(info.name);
5260        boolean added = bp == null;
5261        boolean changed = true;
5262        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5263        if (added) {
5264            enforcePermissionCapLocked(info, tree);
5265            bp = new BasePermission(info.name, tree.sourcePackage,
5266                    BasePermission.TYPE_DYNAMIC);
5267        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5268            throw new SecurityException(
5269                    "Not allowed to modify non-dynamic permission "
5270                    + info.name);
5271        } else {
5272            if (bp.protectionLevel == fixedLevel
5273                    && bp.perm.owner.equals(tree.perm.owner)
5274                    && bp.uid == tree.uid
5275                    && comparePermissionInfos(bp.perm.info, info)) {
5276                changed = false;
5277            }
5278        }
5279        bp.protectionLevel = fixedLevel;
5280        info = new PermissionInfo(info);
5281        info.protectionLevel = fixedLevel;
5282        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5283        bp.perm.info.packageName = tree.perm.info.packageName;
5284        bp.uid = tree.uid;
5285        if (added) {
5286            mSettings.mPermissions.put(info.name, bp);
5287        }
5288        if (changed) {
5289            if (!async) {
5290                mSettings.writeLPr();
5291            } else {
5292                scheduleWriteSettingsLocked();
5293            }
5294        }
5295        return added;
5296    }
5297
5298    @Override
5299    public boolean addPermission(PermissionInfo info) {
5300        synchronized (mPackages) {
5301            return addPermissionLocked(info, false);
5302        }
5303    }
5304
5305    @Override
5306    public boolean addPermissionAsync(PermissionInfo info) {
5307        synchronized (mPackages) {
5308            return addPermissionLocked(info, true);
5309        }
5310    }
5311
5312    @Override
5313    public void removePermission(String name) {
5314        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5315            throw new SecurityException("Instant applications don't have access to this method");
5316        }
5317        synchronized (mPackages) {
5318            checkPermissionTreeLP(name);
5319            BasePermission bp = mSettings.mPermissions.get(name);
5320            if (bp != null) {
5321                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5322                    throw new SecurityException(
5323                            "Not allowed to modify non-dynamic permission "
5324                            + name);
5325                }
5326                mSettings.mPermissions.remove(name);
5327                mSettings.writeLPr();
5328            }
5329        }
5330    }
5331
5332    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5333            PackageParser.Package pkg, BasePermission bp) {
5334        int index = pkg.requestedPermissions.indexOf(bp.name);
5335        if (index == -1) {
5336            throw new SecurityException("Package " + pkg.packageName
5337                    + " has not requested permission " + bp.name);
5338        }
5339        if (!bp.isRuntime() && !bp.isDevelopment()) {
5340            throw new SecurityException("Permission " + bp.name
5341                    + " is not a changeable permission type");
5342        }
5343    }
5344
5345    @Override
5346    public void grantRuntimePermission(String packageName, String name, final int userId) {
5347        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5348    }
5349
5350    private void grantRuntimePermission(String packageName, String name, final int userId,
5351            boolean overridePolicy) {
5352        if (!sUserManager.exists(userId)) {
5353            Log.e(TAG, "No such user:" + userId);
5354            return;
5355        }
5356        final int callingUid = Binder.getCallingUid();
5357
5358        mContext.enforceCallingOrSelfPermission(
5359                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5360                "grantRuntimePermission");
5361
5362        enforceCrossUserPermission(callingUid, userId,
5363                true /* requireFullPermission */, true /* checkShell */,
5364                "grantRuntimePermission");
5365
5366        final int uid;
5367        final PackageSetting ps;
5368
5369        synchronized (mPackages) {
5370            final PackageParser.Package pkg = mPackages.get(packageName);
5371            if (pkg == null) {
5372                throw new IllegalArgumentException("Unknown package: " + packageName);
5373            }
5374            final BasePermission bp = mSettings.mPermissions.get(name);
5375            if (bp == null) {
5376                throw new IllegalArgumentException("Unknown permission: " + name);
5377            }
5378            ps = (PackageSetting) pkg.mExtras;
5379            if (ps == null
5380                    || filterAppAccessLPr(ps, callingUid, userId)) {
5381                throw new IllegalArgumentException("Unknown package: " + packageName);
5382            }
5383
5384            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5385
5386            // If a permission review is required for legacy apps we represent
5387            // their permissions as always granted runtime ones since we need
5388            // to keep the review required permission flag per user while an
5389            // install permission's state is shared across all users.
5390            if (mPermissionReviewRequired
5391                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5392                    && bp.isRuntime()) {
5393                return;
5394            }
5395
5396            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5397
5398            final PermissionsState permissionsState = ps.getPermissionsState();
5399
5400            final int flags = permissionsState.getPermissionFlags(name, userId);
5401            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5402                throw new SecurityException("Cannot grant system fixed permission "
5403                        + name + " for package " + packageName);
5404            }
5405            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5406                throw new SecurityException("Cannot grant policy fixed permission "
5407                        + name + " for package " + packageName);
5408            }
5409
5410            if (bp.isDevelopment()) {
5411                // Development permissions must be handled specially, since they are not
5412                // normal runtime permissions.  For now they apply to all users.
5413                if (permissionsState.grantInstallPermission(bp) !=
5414                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5415                    scheduleWriteSettingsLocked();
5416                }
5417                return;
5418            }
5419
5420            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5421                throw new SecurityException("Cannot grant non-ephemeral permission"
5422                        + name + " for package " + packageName);
5423            }
5424
5425            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5426                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5427                return;
5428            }
5429
5430            final int result = permissionsState.grantRuntimePermission(bp, userId);
5431            switch (result) {
5432                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5433                    return;
5434                }
5435
5436                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5437                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5438                    mHandler.post(new Runnable() {
5439                        @Override
5440                        public void run() {
5441                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5442                        }
5443                    });
5444                }
5445                break;
5446            }
5447
5448            if (bp.isRuntime()) {
5449                logPermissionGranted(mContext, name, packageName);
5450            }
5451
5452            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5453
5454            // Not critical if that is lost - app has to request again.
5455            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5456        }
5457
5458        // Only need to do this if user is initialized. Otherwise it's a new user
5459        // and there are no processes running as the user yet and there's no need
5460        // to make an expensive call to remount processes for the changed permissions.
5461        if (READ_EXTERNAL_STORAGE.equals(name)
5462                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5463            final long token = Binder.clearCallingIdentity();
5464            try {
5465                if (sUserManager.isInitialized(userId)) {
5466                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5467                            StorageManagerInternal.class);
5468                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5469                }
5470            } finally {
5471                Binder.restoreCallingIdentity(token);
5472            }
5473        }
5474    }
5475
5476    @Override
5477    public void revokeRuntimePermission(String packageName, String name, int userId) {
5478        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5479    }
5480
5481    private void revokeRuntimePermission(String packageName, String name, int userId,
5482            boolean overridePolicy) {
5483        if (!sUserManager.exists(userId)) {
5484            Log.e(TAG, "No such user:" + userId);
5485            return;
5486        }
5487
5488        mContext.enforceCallingOrSelfPermission(
5489                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5490                "revokeRuntimePermission");
5491
5492        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5493                true /* requireFullPermission */, true /* checkShell */,
5494                "revokeRuntimePermission");
5495
5496        final int appId;
5497
5498        synchronized (mPackages) {
5499            final PackageParser.Package pkg = mPackages.get(packageName);
5500            if (pkg == null) {
5501                throw new IllegalArgumentException("Unknown package: " + packageName);
5502            }
5503            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5504            if (ps == null
5505                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5506                throw new IllegalArgumentException("Unknown package: " + packageName);
5507            }
5508            final BasePermission bp = mSettings.mPermissions.get(name);
5509            if (bp == null) {
5510                throw new IllegalArgumentException("Unknown permission: " + name);
5511            }
5512
5513            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5514
5515            // If a permission review is required for legacy apps we represent
5516            // their permissions as always granted runtime ones since we need
5517            // to keep the review required permission flag per user while an
5518            // install permission's state is shared across all users.
5519            if (mPermissionReviewRequired
5520                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5521                    && bp.isRuntime()) {
5522                return;
5523            }
5524
5525            final PermissionsState permissionsState = ps.getPermissionsState();
5526
5527            final int flags = permissionsState.getPermissionFlags(name, userId);
5528            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5529                throw new SecurityException("Cannot revoke system fixed permission "
5530                        + name + " for package " + packageName);
5531            }
5532            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5533                throw new SecurityException("Cannot revoke policy fixed permission "
5534                        + name + " for package " + packageName);
5535            }
5536
5537            if (bp.isDevelopment()) {
5538                // Development permissions must be handled specially, since they are not
5539                // normal runtime permissions.  For now they apply to all users.
5540                if (permissionsState.revokeInstallPermission(bp) !=
5541                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5542                    scheduleWriteSettingsLocked();
5543                }
5544                return;
5545            }
5546
5547            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5548                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5549                return;
5550            }
5551
5552            if (bp.isRuntime()) {
5553                logPermissionRevoked(mContext, name, packageName);
5554            }
5555
5556            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5557
5558            // Critical, after this call app should never have the permission.
5559            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5560
5561            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5562        }
5563
5564        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5565    }
5566
5567    /**
5568     * Get the first event id for the permission.
5569     *
5570     * <p>There are four events for each permission: <ul>
5571     *     <li>Request permission: first id + 0</li>
5572     *     <li>Grant permission: first id + 1</li>
5573     *     <li>Request for permission denied: first id + 2</li>
5574     *     <li>Revoke permission: first id + 3</li>
5575     * </ul></p>
5576     *
5577     * @param name name of the permission
5578     *
5579     * @return The first event id for the permission
5580     */
5581    private static int getBaseEventId(@NonNull String name) {
5582        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5583
5584        if (eventIdIndex == -1) {
5585            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5586                    || "user".equals(Build.TYPE)) {
5587                Log.i(TAG, "Unknown permission " + name);
5588
5589                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5590            } else {
5591                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5592                //
5593                // Also update
5594                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5595                // - metrics_constants.proto
5596                throw new IllegalStateException("Unknown permission " + name);
5597            }
5598        }
5599
5600        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5601    }
5602
5603    /**
5604     * Log that a permission was revoked.
5605     *
5606     * @param context Context of the caller
5607     * @param name name of the permission
5608     * @param packageName package permission if for
5609     */
5610    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5611            @NonNull String packageName) {
5612        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5613    }
5614
5615    /**
5616     * Log that a permission request was granted.
5617     *
5618     * @param context Context of the caller
5619     * @param name name of the permission
5620     * @param packageName package permission if for
5621     */
5622    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5623            @NonNull String packageName) {
5624        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5625    }
5626
5627    @Override
5628    public void resetRuntimePermissions() {
5629        mContext.enforceCallingOrSelfPermission(
5630                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5631                "revokeRuntimePermission");
5632
5633        int callingUid = Binder.getCallingUid();
5634        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5635            mContext.enforceCallingOrSelfPermission(
5636                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5637                    "resetRuntimePermissions");
5638        }
5639
5640        synchronized (mPackages) {
5641            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5642            for (int userId : UserManagerService.getInstance().getUserIds()) {
5643                final int packageCount = mPackages.size();
5644                for (int i = 0; i < packageCount; i++) {
5645                    PackageParser.Package pkg = mPackages.valueAt(i);
5646                    if (!(pkg.mExtras instanceof PackageSetting)) {
5647                        continue;
5648                    }
5649                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5650                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5651                }
5652            }
5653        }
5654    }
5655
5656    @Override
5657    public int getPermissionFlags(String name, String packageName, int userId) {
5658        if (!sUserManager.exists(userId)) {
5659            return 0;
5660        }
5661
5662        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5663
5664        final int callingUid = Binder.getCallingUid();
5665        enforceCrossUserPermission(callingUid, userId,
5666                true /* requireFullPermission */, false /* checkShell */,
5667                "getPermissionFlags");
5668
5669        synchronized (mPackages) {
5670            final PackageParser.Package pkg = mPackages.get(packageName);
5671            if (pkg == null) {
5672                return 0;
5673            }
5674            final BasePermission bp = mSettings.mPermissions.get(name);
5675            if (bp == null) {
5676                return 0;
5677            }
5678            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5679            if (ps == null
5680                    || filterAppAccessLPr(ps, callingUid, userId)) {
5681                return 0;
5682            }
5683            PermissionsState permissionsState = ps.getPermissionsState();
5684            return permissionsState.getPermissionFlags(name, userId);
5685        }
5686    }
5687
5688    @Override
5689    public void updatePermissionFlags(String name, String packageName, int flagMask,
5690            int flagValues, int userId) {
5691        if (!sUserManager.exists(userId)) {
5692            return;
5693        }
5694
5695        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5696
5697        final int callingUid = Binder.getCallingUid();
5698        enforceCrossUserPermission(callingUid, userId,
5699                true /* requireFullPermission */, true /* checkShell */,
5700                "updatePermissionFlags");
5701
5702        // Only the system can change these flags and nothing else.
5703        if (getCallingUid() != Process.SYSTEM_UID) {
5704            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5705            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5706            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5707            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5708            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5709        }
5710
5711        synchronized (mPackages) {
5712            final PackageParser.Package pkg = mPackages.get(packageName);
5713            if (pkg == null) {
5714                throw new IllegalArgumentException("Unknown package: " + packageName);
5715            }
5716            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5717            if (ps == null
5718                    || filterAppAccessLPr(ps, callingUid, userId)) {
5719                throw new IllegalArgumentException("Unknown package: " + packageName);
5720            }
5721
5722            final BasePermission bp = mSettings.mPermissions.get(name);
5723            if (bp == null) {
5724                throw new IllegalArgumentException("Unknown permission: " + name);
5725            }
5726
5727            PermissionsState permissionsState = ps.getPermissionsState();
5728
5729            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5730
5731            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5732                // Install and runtime permissions are stored in different places,
5733                // so figure out what permission changed and persist the change.
5734                if (permissionsState.getInstallPermissionState(name) != null) {
5735                    scheduleWriteSettingsLocked();
5736                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5737                        || hadState) {
5738                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5739                }
5740            }
5741        }
5742    }
5743
5744    /**
5745     * Update the permission flags for all packages and runtime permissions of a user in order
5746     * to allow device or profile owner to remove POLICY_FIXED.
5747     */
5748    @Override
5749    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5750        if (!sUserManager.exists(userId)) {
5751            return;
5752        }
5753
5754        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5755
5756        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5757                true /* requireFullPermission */, true /* checkShell */,
5758                "updatePermissionFlagsForAllApps");
5759
5760        // Only the system can change system fixed flags.
5761        if (getCallingUid() != Process.SYSTEM_UID) {
5762            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5763            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5764        }
5765
5766        synchronized (mPackages) {
5767            boolean changed = false;
5768            final int packageCount = mPackages.size();
5769            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5770                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5771                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5772                if (ps == null) {
5773                    continue;
5774                }
5775                PermissionsState permissionsState = ps.getPermissionsState();
5776                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5777                        userId, flagMask, flagValues);
5778            }
5779            if (changed) {
5780                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5781            }
5782        }
5783    }
5784
5785    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5786        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5787                != PackageManager.PERMISSION_GRANTED
5788            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5789                != PackageManager.PERMISSION_GRANTED) {
5790            throw new SecurityException(message + " requires "
5791                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5792                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5793        }
5794    }
5795
5796    @Override
5797    public boolean shouldShowRequestPermissionRationale(String permissionName,
5798            String packageName, int userId) {
5799        if (UserHandle.getCallingUserId() != userId) {
5800            mContext.enforceCallingPermission(
5801                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5802                    "canShowRequestPermissionRationale for user " + userId);
5803        }
5804
5805        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5806        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5807            return false;
5808        }
5809
5810        if (checkPermission(permissionName, packageName, userId)
5811                == PackageManager.PERMISSION_GRANTED) {
5812            return false;
5813        }
5814
5815        final int flags;
5816
5817        final long identity = Binder.clearCallingIdentity();
5818        try {
5819            flags = getPermissionFlags(permissionName,
5820                    packageName, userId);
5821        } finally {
5822            Binder.restoreCallingIdentity(identity);
5823        }
5824
5825        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5826                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5827                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5828
5829        if ((flags & fixedFlags) != 0) {
5830            return false;
5831        }
5832
5833        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5834    }
5835
5836    @Override
5837    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5838        mContext.enforceCallingOrSelfPermission(
5839                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5840                "addOnPermissionsChangeListener");
5841
5842        synchronized (mPackages) {
5843            mOnPermissionChangeListeners.addListenerLocked(listener);
5844        }
5845    }
5846
5847    @Override
5848    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5849        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5850            throw new SecurityException("Instant applications don't have access to this method");
5851        }
5852        synchronized (mPackages) {
5853            mOnPermissionChangeListeners.removeListenerLocked(listener);
5854        }
5855    }
5856
5857    @Override
5858    public boolean isProtectedBroadcast(String actionName) {
5859        // allow instant applications
5860        synchronized (mPackages) {
5861            if (mProtectedBroadcasts.contains(actionName)) {
5862                return true;
5863            } else if (actionName != null) {
5864                // TODO: remove these terrible hacks
5865                if (actionName.startsWith("android.net.netmon.lingerExpired")
5866                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5867                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5868                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5869                    return true;
5870                }
5871            }
5872        }
5873        return false;
5874    }
5875
5876    @Override
5877    public int checkSignatures(String pkg1, String pkg2) {
5878        synchronized (mPackages) {
5879            final PackageParser.Package p1 = mPackages.get(pkg1);
5880            final PackageParser.Package p2 = mPackages.get(pkg2);
5881            if (p1 == null || p1.mExtras == null
5882                    || p2 == null || p2.mExtras == null) {
5883                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5884            }
5885            final int callingUid = Binder.getCallingUid();
5886            final int callingUserId = UserHandle.getUserId(callingUid);
5887            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5888            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5889            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5890                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5891                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5892            }
5893            return compareSignatures(p1.mSignatures, p2.mSignatures);
5894        }
5895    }
5896
5897    @Override
5898    public int checkUidSignatures(int uid1, int uid2) {
5899        final int callingUid = Binder.getCallingUid();
5900        final int callingUserId = UserHandle.getUserId(callingUid);
5901        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5902        // Map to base uids.
5903        uid1 = UserHandle.getAppId(uid1);
5904        uid2 = UserHandle.getAppId(uid2);
5905        // reader
5906        synchronized (mPackages) {
5907            Signature[] s1;
5908            Signature[] s2;
5909            Object obj = mSettings.getUserIdLPr(uid1);
5910            if (obj != null) {
5911                if (obj instanceof SharedUserSetting) {
5912                    if (isCallerInstantApp) {
5913                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5914                    }
5915                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5916                } else if (obj instanceof PackageSetting) {
5917                    final PackageSetting ps = (PackageSetting) obj;
5918                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5919                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5920                    }
5921                    s1 = ps.signatures.mSignatures;
5922                } else {
5923                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5924                }
5925            } else {
5926                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5927            }
5928            obj = mSettings.getUserIdLPr(uid2);
5929            if (obj != null) {
5930                if (obj instanceof SharedUserSetting) {
5931                    if (isCallerInstantApp) {
5932                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5933                    }
5934                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5935                } else if (obj instanceof PackageSetting) {
5936                    final PackageSetting ps = (PackageSetting) obj;
5937                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5938                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5939                    }
5940                    s2 = ps.signatures.mSignatures;
5941                } else {
5942                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5943                }
5944            } else {
5945                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5946            }
5947            return compareSignatures(s1, s2);
5948        }
5949    }
5950
5951    /**
5952     * This method should typically only be used when granting or revoking
5953     * permissions, since the app may immediately restart after this call.
5954     * <p>
5955     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5956     * guard your work against the app being relaunched.
5957     */
5958    private void killUid(int appId, int userId, String reason) {
5959        final long identity = Binder.clearCallingIdentity();
5960        try {
5961            IActivityManager am = ActivityManager.getService();
5962            if (am != null) {
5963                try {
5964                    am.killUid(appId, userId, reason);
5965                } catch (RemoteException e) {
5966                    /* ignore - same process */
5967                }
5968            }
5969        } finally {
5970            Binder.restoreCallingIdentity(identity);
5971        }
5972    }
5973
5974    /**
5975     * Compares two sets of signatures. Returns:
5976     * <br />
5977     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5978     * <br />
5979     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5980     * <br />
5981     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5982     * <br />
5983     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5984     * <br />
5985     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5986     */
5987    static int compareSignatures(Signature[] s1, Signature[] s2) {
5988        if (s1 == null) {
5989            return s2 == null
5990                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5991                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5992        }
5993
5994        if (s2 == null) {
5995            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5996        }
5997
5998        if (s1.length != s2.length) {
5999            return PackageManager.SIGNATURE_NO_MATCH;
6000        }
6001
6002        // Since both signature sets are of size 1, we can compare without HashSets.
6003        if (s1.length == 1) {
6004            return s1[0].equals(s2[0]) ?
6005                    PackageManager.SIGNATURE_MATCH :
6006                    PackageManager.SIGNATURE_NO_MATCH;
6007        }
6008
6009        ArraySet<Signature> set1 = new ArraySet<Signature>();
6010        for (Signature sig : s1) {
6011            set1.add(sig);
6012        }
6013        ArraySet<Signature> set2 = new ArraySet<Signature>();
6014        for (Signature sig : s2) {
6015            set2.add(sig);
6016        }
6017        // Make sure s2 contains all signatures in s1.
6018        if (set1.equals(set2)) {
6019            return PackageManager.SIGNATURE_MATCH;
6020        }
6021        return PackageManager.SIGNATURE_NO_MATCH;
6022    }
6023
6024    /**
6025     * If the database version for this type of package (internal storage or
6026     * external storage) is less than the version where package signatures
6027     * were updated, return true.
6028     */
6029    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6030        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6031        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6032    }
6033
6034    /**
6035     * Used for backward compatibility to make sure any packages with
6036     * certificate chains get upgraded to the new style. {@code existingSigs}
6037     * will be in the old format (since they were stored on disk from before the
6038     * system upgrade) and {@code scannedSigs} will be in the newer format.
6039     */
6040    private int compareSignaturesCompat(PackageSignatures existingSigs,
6041            PackageParser.Package scannedPkg) {
6042        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6043            return PackageManager.SIGNATURE_NO_MATCH;
6044        }
6045
6046        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6047        for (Signature sig : existingSigs.mSignatures) {
6048            existingSet.add(sig);
6049        }
6050        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6051        for (Signature sig : scannedPkg.mSignatures) {
6052            try {
6053                Signature[] chainSignatures = sig.getChainSignatures();
6054                for (Signature chainSig : chainSignatures) {
6055                    scannedCompatSet.add(chainSig);
6056                }
6057            } catch (CertificateEncodingException e) {
6058                scannedCompatSet.add(sig);
6059            }
6060        }
6061        /*
6062         * Make sure the expanded scanned set contains all signatures in the
6063         * existing one.
6064         */
6065        if (scannedCompatSet.equals(existingSet)) {
6066            // Migrate the old signatures to the new scheme.
6067            existingSigs.assignSignatures(scannedPkg.mSignatures);
6068            // The new KeySets will be re-added later in the scanning process.
6069            synchronized (mPackages) {
6070                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6071            }
6072            return PackageManager.SIGNATURE_MATCH;
6073        }
6074        return PackageManager.SIGNATURE_NO_MATCH;
6075    }
6076
6077    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6078        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6079        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6080    }
6081
6082    private int compareSignaturesRecover(PackageSignatures existingSigs,
6083            PackageParser.Package scannedPkg) {
6084        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6085            return PackageManager.SIGNATURE_NO_MATCH;
6086        }
6087
6088        String msg = null;
6089        try {
6090            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6091                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6092                        + scannedPkg.packageName);
6093                return PackageManager.SIGNATURE_MATCH;
6094            }
6095        } catch (CertificateException e) {
6096            msg = e.getMessage();
6097        }
6098
6099        logCriticalInfo(Log.INFO,
6100                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6101        return PackageManager.SIGNATURE_NO_MATCH;
6102    }
6103
6104    @Override
6105    public List<String> getAllPackages() {
6106        final int callingUid = Binder.getCallingUid();
6107        final int callingUserId = UserHandle.getUserId(callingUid);
6108        synchronized (mPackages) {
6109            if (canViewInstantApps(callingUid, callingUserId)) {
6110                return new ArrayList<String>(mPackages.keySet());
6111            }
6112            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6113            final List<String> result = new ArrayList<>();
6114            if (instantAppPkgName != null) {
6115                // caller is an instant application; filter unexposed applications
6116                for (PackageParser.Package pkg : mPackages.values()) {
6117                    if (!pkg.visibleToInstantApps) {
6118                        continue;
6119                    }
6120                    result.add(pkg.packageName);
6121                }
6122            } else {
6123                // caller is a normal application; filter instant applications
6124                for (PackageParser.Package pkg : mPackages.values()) {
6125                    final PackageSetting ps =
6126                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6127                    if (ps != null
6128                            && ps.getInstantApp(callingUserId)
6129                            && !mInstantAppRegistry.isInstantAccessGranted(
6130                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6131                        continue;
6132                    }
6133                    result.add(pkg.packageName);
6134                }
6135            }
6136            return result;
6137        }
6138    }
6139
6140    @Override
6141    public String[] getPackagesForUid(int uid) {
6142        final int callingUid = Binder.getCallingUid();
6143        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6144        final int userId = UserHandle.getUserId(uid);
6145        uid = UserHandle.getAppId(uid);
6146        // reader
6147        synchronized (mPackages) {
6148            Object obj = mSettings.getUserIdLPr(uid);
6149            if (obj instanceof SharedUserSetting) {
6150                if (isCallerInstantApp) {
6151                    return null;
6152                }
6153                final SharedUserSetting sus = (SharedUserSetting) obj;
6154                final int N = sus.packages.size();
6155                String[] res = new String[N];
6156                final Iterator<PackageSetting> it = sus.packages.iterator();
6157                int i = 0;
6158                while (it.hasNext()) {
6159                    PackageSetting ps = it.next();
6160                    if (ps.getInstalled(userId)) {
6161                        res[i++] = ps.name;
6162                    } else {
6163                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6164                    }
6165                }
6166                return res;
6167            } else if (obj instanceof PackageSetting) {
6168                final PackageSetting ps = (PackageSetting) obj;
6169                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6170                    return new String[]{ps.name};
6171                }
6172            }
6173        }
6174        return null;
6175    }
6176
6177    @Override
6178    public String getNameForUid(int uid) {
6179        final int callingUid = Binder.getCallingUid();
6180        if (getInstantAppPackageName(callingUid) != null) {
6181            return null;
6182        }
6183        synchronized (mPackages) {
6184            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6185            if (obj instanceof SharedUserSetting) {
6186                final SharedUserSetting sus = (SharedUserSetting) obj;
6187                return sus.name + ":" + sus.userId;
6188            } else if (obj instanceof PackageSetting) {
6189                final PackageSetting ps = (PackageSetting) obj;
6190                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6191                    return null;
6192                }
6193                return ps.name;
6194            }
6195        }
6196        return null;
6197    }
6198
6199    @Override
6200    public int getUidForSharedUser(String sharedUserName) {
6201        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6202            return -1;
6203        }
6204        if (sharedUserName == null) {
6205            return -1;
6206        }
6207        // reader
6208        synchronized (mPackages) {
6209            SharedUserSetting suid;
6210            try {
6211                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6212                if (suid != null) {
6213                    return suid.userId;
6214                }
6215            } catch (PackageManagerException ignore) {
6216                // can't happen, but, still need to catch it
6217            }
6218            return -1;
6219        }
6220    }
6221
6222    @Override
6223    public int getFlagsForUid(int uid) {
6224        final int callingUid = Binder.getCallingUid();
6225        if (getInstantAppPackageName(callingUid) != null) {
6226            return 0;
6227        }
6228        synchronized (mPackages) {
6229            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6230            if (obj instanceof SharedUserSetting) {
6231                final SharedUserSetting sus = (SharedUserSetting) obj;
6232                return sus.pkgFlags;
6233            } else if (obj instanceof PackageSetting) {
6234                final PackageSetting ps = (PackageSetting) obj;
6235                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6236                    return 0;
6237                }
6238                return ps.pkgFlags;
6239            }
6240        }
6241        return 0;
6242    }
6243
6244    @Override
6245    public int getPrivateFlagsForUid(int uid) {
6246        final int callingUid = Binder.getCallingUid();
6247        if (getInstantAppPackageName(callingUid) != null) {
6248            return 0;
6249        }
6250        synchronized (mPackages) {
6251            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6252            if (obj instanceof SharedUserSetting) {
6253                final SharedUserSetting sus = (SharedUserSetting) obj;
6254                return sus.pkgPrivateFlags;
6255            } else if (obj instanceof PackageSetting) {
6256                final PackageSetting ps = (PackageSetting) obj;
6257                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6258                    return 0;
6259                }
6260                return ps.pkgPrivateFlags;
6261            }
6262        }
6263        return 0;
6264    }
6265
6266    @Override
6267    public boolean isUidPrivileged(int uid) {
6268        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6269            return false;
6270        }
6271        uid = UserHandle.getAppId(uid);
6272        // reader
6273        synchronized (mPackages) {
6274            Object obj = mSettings.getUserIdLPr(uid);
6275            if (obj instanceof SharedUserSetting) {
6276                final SharedUserSetting sus = (SharedUserSetting) obj;
6277                final Iterator<PackageSetting> it = sus.packages.iterator();
6278                while (it.hasNext()) {
6279                    if (it.next().isPrivileged()) {
6280                        return true;
6281                    }
6282                }
6283            } else if (obj instanceof PackageSetting) {
6284                final PackageSetting ps = (PackageSetting) obj;
6285                return ps.isPrivileged();
6286            }
6287        }
6288        return false;
6289    }
6290
6291    @Override
6292    public String[] getAppOpPermissionPackages(String permissionName) {
6293        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6294            return null;
6295        }
6296        synchronized (mPackages) {
6297            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6298            if (pkgs == null) {
6299                return null;
6300            }
6301            return pkgs.toArray(new String[pkgs.size()]);
6302        }
6303    }
6304
6305    @Override
6306    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6307            int flags, int userId) {
6308        return resolveIntentInternal(
6309                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6310    }
6311
6312    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6313            int flags, int userId, boolean resolveForStart) {
6314        try {
6315            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6316
6317            if (!sUserManager.exists(userId)) return null;
6318            final int callingUid = Binder.getCallingUid();
6319            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6320            enforceCrossUserPermission(callingUid, userId,
6321                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6322
6323            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6324            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6325                    flags, callingUid, userId, resolveForStart);
6326            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6327
6328            final ResolveInfo bestChoice =
6329                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6330            return bestChoice;
6331        } finally {
6332            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6333        }
6334    }
6335
6336    @Override
6337    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6338        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6339            throw new SecurityException(
6340                    "findPersistentPreferredActivity can only be run by the system");
6341        }
6342        if (!sUserManager.exists(userId)) {
6343            return null;
6344        }
6345        final int callingUid = Binder.getCallingUid();
6346        intent = updateIntentForResolve(intent);
6347        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6348        final int flags = updateFlagsForResolve(
6349                0, userId, intent, callingUid, false /*includeInstantApps*/);
6350        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6351                userId);
6352        synchronized (mPackages) {
6353            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6354                    userId);
6355        }
6356    }
6357
6358    @Override
6359    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6360            IntentFilter filter, int match, ComponentName activity) {
6361        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6362            return;
6363        }
6364        final int userId = UserHandle.getCallingUserId();
6365        if (DEBUG_PREFERRED) {
6366            Log.v(TAG, "setLastChosenActivity intent=" + intent
6367                + " resolvedType=" + resolvedType
6368                + " flags=" + flags
6369                + " filter=" + filter
6370                + " match=" + match
6371                + " activity=" + activity);
6372            filter.dump(new PrintStreamPrinter(System.out), "    ");
6373        }
6374        intent.setComponent(null);
6375        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6376                userId);
6377        // Find any earlier preferred or last chosen entries and nuke them
6378        findPreferredActivity(intent, resolvedType,
6379                flags, query, 0, false, true, false, userId);
6380        // Add the new activity as the last chosen for this filter
6381        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6382                "Setting last chosen");
6383    }
6384
6385    @Override
6386    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6387        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6388            return null;
6389        }
6390        final int userId = UserHandle.getCallingUserId();
6391        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6392        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6393                userId);
6394        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6395                false, false, false, userId);
6396    }
6397
6398    /**
6399     * Returns whether or not instant apps have been disabled remotely.
6400     */
6401    private boolean isEphemeralDisabled() {
6402        return mEphemeralAppsDisabled;
6403    }
6404
6405    private boolean isInstantAppAllowed(
6406            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6407            boolean skipPackageCheck) {
6408        if (mInstantAppResolverConnection == null) {
6409            return false;
6410        }
6411        if (mInstantAppInstallerActivity == null) {
6412            return false;
6413        }
6414        if (intent.getComponent() != null) {
6415            return false;
6416        }
6417        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6418            return false;
6419        }
6420        if (!skipPackageCheck && intent.getPackage() != null) {
6421            return false;
6422        }
6423        final boolean isWebUri = hasWebURI(intent);
6424        if (!isWebUri || intent.getData().getHost() == null) {
6425            return false;
6426        }
6427        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6428        // Or if there's already an ephemeral app installed that handles the action
6429        synchronized (mPackages) {
6430            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6431            for (int n = 0; n < count; n++) {
6432                final ResolveInfo info = resolvedActivities.get(n);
6433                final String packageName = info.activityInfo.packageName;
6434                final PackageSetting ps = mSettings.mPackages.get(packageName);
6435                if (ps != null) {
6436                    // only check domain verification status if the app is not a browser
6437                    if (!info.handleAllWebDataURI) {
6438                        // Try to get the status from User settings first
6439                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6440                        final int status = (int) (packedStatus >> 32);
6441                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6442                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6443                            if (DEBUG_EPHEMERAL) {
6444                                Slog.v(TAG, "DENY instant app;"
6445                                    + " pkg: " + packageName + ", status: " + status);
6446                            }
6447                            return false;
6448                        }
6449                    }
6450                    if (ps.getInstantApp(userId)) {
6451                        if (DEBUG_EPHEMERAL) {
6452                            Slog.v(TAG, "DENY instant app installed;"
6453                                    + " pkg: " + packageName);
6454                        }
6455                        return false;
6456                    }
6457                }
6458            }
6459        }
6460        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6461        return true;
6462    }
6463
6464    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6465            Intent origIntent, String resolvedType, String callingPackage,
6466            Bundle verificationBundle, int userId) {
6467        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6468                new InstantAppRequest(responseObj, origIntent, resolvedType,
6469                        callingPackage, userId, verificationBundle));
6470        mHandler.sendMessage(msg);
6471    }
6472
6473    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6474            int flags, List<ResolveInfo> query, int userId) {
6475        if (query != null) {
6476            final int N = query.size();
6477            if (N == 1) {
6478                return query.get(0);
6479            } else if (N > 1) {
6480                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6481                // If there is more than one activity with the same priority,
6482                // then let the user decide between them.
6483                ResolveInfo r0 = query.get(0);
6484                ResolveInfo r1 = query.get(1);
6485                if (DEBUG_INTENT_MATCHING || debug) {
6486                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6487                            + r1.activityInfo.name + "=" + r1.priority);
6488                }
6489                // If the first activity has a higher priority, or a different
6490                // default, then it is always desirable to pick it.
6491                if (r0.priority != r1.priority
6492                        || r0.preferredOrder != r1.preferredOrder
6493                        || r0.isDefault != r1.isDefault) {
6494                    return query.get(0);
6495                }
6496                // If we have saved a preference for a preferred activity for
6497                // this Intent, use that.
6498                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6499                        flags, query, r0.priority, true, false, debug, userId);
6500                if (ri != null) {
6501                    return ri;
6502                }
6503                // If we have an ephemeral app, use it
6504                for (int i = 0; i < N; i++) {
6505                    ri = query.get(i);
6506                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6507                        final String packageName = ri.activityInfo.packageName;
6508                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6509                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6510                        final int status = (int)(packedStatus >> 32);
6511                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6512                            return ri;
6513                        }
6514                    }
6515                }
6516                ri = new ResolveInfo(mResolveInfo);
6517                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6518                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6519                // If all of the options come from the same package, show the application's
6520                // label and icon instead of the generic resolver's.
6521                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6522                // and then throw away the ResolveInfo itself, meaning that the caller loses
6523                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6524                // a fallback for this case; we only set the target package's resources on
6525                // the ResolveInfo, not the ActivityInfo.
6526                final String intentPackage = intent.getPackage();
6527                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6528                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6529                    ri.resolvePackageName = intentPackage;
6530                    if (userNeedsBadging(userId)) {
6531                        ri.noResourceId = true;
6532                    } else {
6533                        ri.icon = appi.icon;
6534                    }
6535                    ri.iconResourceId = appi.icon;
6536                    ri.labelRes = appi.labelRes;
6537                }
6538                ri.activityInfo.applicationInfo = new ApplicationInfo(
6539                        ri.activityInfo.applicationInfo);
6540                if (userId != 0) {
6541                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6542                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6543                }
6544                // Make sure that the resolver is displayable in car mode
6545                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6546                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6547                return ri;
6548            }
6549        }
6550        return null;
6551    }
6552
6553    /**
6554     * Return true if the given list is not empty and all of its contents have
6555     * an activityInfo with the given package name.
6556     */
6557    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6558        if (ArrayUtils.isEmpty(list)) {
6559            return false;
6560        }
6561        for (int i = 0, N = list.size(); i < N; i++) {
6562            final ResolveInfo ri = list.get(i);
6563            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6564            if (ai == null || !packageName.equals(ai.packageName)) {
6565                return false;
6566            }
6567        }
6568        return true;
6569    }
6570
6571    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6572            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6573        final int N = query.size();
6574        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6575                .get(userId);
6576        // Get the list of persistent preferred activities that handle the intent
6577        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6578        List<PersistentPreferredActivity> pprefs = ppir != null
6579                ? ppir.queryIntent(intent, resolvedType,
6580                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6581                        userId)
6582                : null;
6583        if (pprefs != null && pprefs.size() > 0) {
6584            final int M = pprefs.size();
6585            for (int i=0; i<M; i++) {
6586                final PersistentPreferredActivity ppa = pprefs.get(i);
6587                if (DEBUG_PREFERRED || debug) {
6588                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6589                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6590                            + "\n  component=" + ppa.mComponent);
6591                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6592                }
6593                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6594                        flags | MATCH_DISABLED_COMPONENTS, userId);
6595                if (DEBUG_PREFERRED || debug) {
6596                    Slog.v(TAG, "Found persistent preferred activity:");
6597                    if (ai != null) {
6598                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6599                    } else {
6600                        Slog.v(TAG, "  null");
6601                    }
6602                }
6603                if (ai == null) {
6604                    // This previously registered persistent preferred activity
6605                    // component is no longer known. Ignore it and do NOT remove it.
6606                    continue;
6607                }
6608                for (int j=0; j<N; j++) {
6609                    final ResolveInfo ri = query.get(j);
6610                    if (!ri.activityInfo.applicationInfo.packageName
6611                            .equals(ai.applicationInfo.packageName)) {
6612                        continue;
6613                    }
6614                    if (!ri.activityInfo.name.equals(ai.name)) {
6615                        continue;
6616                    }
6617                    //  Found a persistent preference that can handle the intent.
6618                    if (DEBUG_PREFERRED || debug) {
6619                        Slog.v(TAG, "Returning persistent preferred activity: " +
6620                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6621                    }
6622                    return ri;
6623                }
6624            }
6625        }
6626        return null;
6627    }
6628
6629    // TODO: handle preferred activities missing while user has amnesia
6630    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6631            List<ResolveInfo> query, int priority, boolean always,
6632            boolean removeMatches, boolean debug, int userId) {
6633        if (!sUserManager.exists(userId)) return null;
6634        final int callingUid = Binder.getCallingUid();
6635        flags = updateFlagsForResolve(
6636                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6637        intent = updateIntentForResolve(intent);
6638        // writer
6639        synchronized (mPackages) {
6640            // Try to find a matching persistent preferred activity.
6641            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6642                    debug, userId);
6643
6644            // If a persistent preferred activity matched, use it.
6645            if (pri != null) {
6646                return pri;
6647            }
6648
6649            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6650            // Get the list of preferred activities that handle the intent
6651            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6652            List<PreferredActivity> prefs = pir != null
6653                    ? pir.queryIntent(intent, resolvedType,
6654                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6655                            userId)
6656                    : null;
6657            if (prefs != null && prefs.size() > 0) {
6658                boolean changed = false;
6659                try {
6660                    // First figure out how good the original match set is.
6661                    // We will only allow preferred activities that came
6662                    // from the same match quality.
6663                    int match = 0;
6664
6665                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6666
6667                    final int N = query.size();
6668                    for (int j=0; j<N; j++) {
6669                        final ResolveInfo ri = query.get(j);
6670                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6671                                + ": 0x" + Integer.toHexString(match));
6672                        if (ri.match > match) {
6673                            match = ri.match;
6674                        }
6675                    }
6676
6677                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6678                            + Integer.toHexString(match));
6679
6680                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6681                    final int M = prefs.size();
6682                    for (int i=0; i<M; i++) {
6683                        final PreferredActivity pa = prefs.get(i);
6684                        if (DEBUG_PREFERRED || debug) {
6685                            Slog.v(TAG, "Checking PreferredActivity ds="
6686                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6687                                    + "\n  component=" + pa.mPref.mComponent);
6688                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6689                        }
6690                        if (pa.mPref.mMatch != match) {
6691                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6692                                    + Integer.toHexString(pa.mPref.mMatch));
6693                            continue;
6694                        }
6695                        // If it's not an "always" type preferred activity and that's what we're
6696                        // looking for, skip it.
6697                        if (always && !pa.mPref.mAlways) {
6698                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6699                            continue;
6700                        }
6701                        final ActivityInfo ai = getActivityInfo(
6702                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6703                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6704                                userId);
6705                        if (DEBUG_PREFERRED || debug) {
6706                            Slog.v(TAG, "Found preferred activity:");
6707                            if (ai != null) {
6708                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6709                            } else {
6710                                Slog.v(TAG, "  null");
6711                            }
6712                        }
6713                        if (ai == null) {
6714                            // This previously registered preferred activity
6715                            // component is no longer known.  Most likely an update
6716                            // to the app was installed and in the new version this
6717                            // component no longer exists.  Clean it up by removing
6718                            // it from the preferred activities list, and skip it.
6719                            Slog.w(TAG, "Removing dangling preferred activity: "
6720                                    + pa.mPref.mComponent);
6721                            pir.removeFilter(pa);
6722                            changed = true;
6723                            continue;
6724                        }
6725                        for (int j=0; j<N; j++) {
6726                            final ResolveInfo ri = query.get(j);
6727                            if (!ri.activityInfo.applicationInfo.packageName
6728                                    .equals(ai.applicationInfo.packageName)) {
6729                                continue;
6730                            }
6731                            if (!ri.activityInfo.name.equals(ai.name)) {
6732                                continue;
6733                            }
6734
6735                            if (removeMatches) {
6736                                pir.removeFilter(pa);
6737                                changed = true;
6738                                if (DEBUG_PREFERRED) {
6739                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6740                                }
6741                                break;
6742                            }
6743
6744                            // Okay we found a previously set preferred or last chosen app.
6745                            // If the result set is different from when this
6746                            // was created, we need to clear it and re-ask the
6747                            // user their preference, if we're looking for an "always" type entry.
6748                            if (always && !pa.mPref.sameSet(query)) {
6749                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6750                                        + intent + " type " + resolvedType);
6751                                if (DEBUG_PREFERRED) {
6752                                    Slog.v(TAG, "Removing preferred activity since set changed "
6753                                            + pa.mPref.mComponent);
6754                                }
6755                                pir.removeFilter(pa);
6756                                // Re-add the filter as a "last chosen" entry (!always)
6757                                PreferredActivity lastChosen = new PreferredActivity(
6758                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6759                                pir.addFilter(lastChosen);
6760                                changed = true;
6761                                return null;
6762                            }
6763
6764                            // Yay! Either the set matched or we're looking for the last chosen
6765                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6766                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6767                            return ri;
6768                        }
6769                    }
6770                } finally {
6771                    if (changed) {
6772                        if (DEBUG_PREFERRED) {
6773                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6774                        }
6775                        scheduleWritePackageRestrictionsLocked(userId);
6776                    }
6777                }
6778            }
6779        }
6780        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6781        return null;
6782    }
6783
6784    /*
6785     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6786     */
6787    @Override
6788    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6789            int targetUserId) {
6790        mContext.enforceCallingOrSelfPermission(
6791                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6792        List<CrossProfileIntentFilter> matches =
6793                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6794        if (matches != null) {
6795            int size = matches.size();
6796            for (int i = 0; i < size; i++) {
6797                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6798            }
6799        }
6800        if (hasWebURI(intent)) {
6801            // cross-profile app linking works only towards the parent.
6802            final int callingUid = Binder.getCallingUid();
6803            final UserInfo parent = getProfileParent(sourceUserId);
6804            synchronized(mPackages) {
6805                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6806                        false /*includeInstantApps*/);
6807                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6808                        intent, resolvedType, flags, sourceUserId, parent.id);
6809                return xpDomainInfo != null;
6810            }
6811        }
6812        return false;
6813    }
6814
6815    private UserInfo getProfileParent(int userId) {
6816        final long identity = Binder.clearCallingIdentity();
6817        try {
6818            return sUserManager.getProfileParent(userId);
6819        } finally {
6820            Binder.restoreCallingIdentity(identity);
6821        }
6822    }
6823
6824    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6825            String resolvedType, int userId) {
6826        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6827        if (resolver != null) {
6828            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6829        }
6830        return null;
6831    }
6832
6833    @Override
6834    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6835            String resolvedType, int flags, int userId) {
6836        try {
6837            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6838
6839            return new ParceledListSlice<>(
6840                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6841        } finally {
6842            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6843        }
6844    }
6845
6846    /**
6847     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6848     * instant, returns {@code null}.
6849     */
6850    private String getInstantAppPackageName(int callingUid) {
6851        synchronized (mPackages) {
6852            // If the caller is an isolated app use the owner's uid for the lookup.
6853            if (Process.isIsolated(callingUid)) {
6854                callingUid = mIsolatedOwners.get(callingUid);
6855            }
6856            final int appId = UserHandle.getAppId(callingUid);
6857            final Object obj = mSettings.getUserIdLPr(appId);
6858            if (obj instanceof PackageSetting) {
6859                final PackageSetting ps = (PackageSetting) obj;
6860                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6861                return isInstantApp ? ps.pkg.packageName : null;
6862            }
6863        }
6864        return null;
6865    }
6866
6867    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6868            String resolvedType, int flags, int userId) {
6869        return queryIntentActivitiesInternal(
6870                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6871    }
6872
6873    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6874            String resolvedType, int flags, int filterCallingUid, int userId,
6875            boolean resolveForStart) {
6876        if (!sUserManager.exists(userId)) return Collections.emptyList();
6877        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6878        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6879                false /* requireFullPermission */, false /* checkShell */,
6880                "query intent activities");
6881        final String pkgName = intent.getPackage();
6882        ComponentName comp = intent.getComponent();
6883        if (comp == null) {
6884            if (intent.getSelector() != null) {
6885                intent = intent.getSelector();
6886                comp = intent.getComponent();
6887            }
6888        }
6889
6890        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6891                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6892        if (comp != null) {
6893            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6894            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6895            if (ai != null) {
6896                // When specifying an explicit component, we prevent the activity from being
6897                // used when either 1) the calling package is normal and the activity is within
6898                // an ephemeral application or 2) the calling package is ephemeral and the
6899                // activity is not visible to ephemeral applications.
6900                final boolean matchInstantApp =
6901                        (flags & PackageManager.MATCH_INSTANT) != 0;
6902                final boolean matchVisibleToInstantAppOnly =
6903                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6904                final boolean matchExplicitlyVisibleOnly =
6905                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6906                final boolean isCallerInstantApp =
6907                        instantAppPkgName != null;
6908                final boolean isTargetSameInstantApp =
6909                        comp.getPackageName().equals(instantAppPkgName);
6910                final boolean isTargetInstantApp =
6911                        (ai.applicationInfo.privateFlags
6912                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6913                final boolean isTargetVisibleToInstantApp =
6914                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6915                final boolean isTargetExplicitlyVisibleToInstantApp =
6916                        isTargetVisibleToInstantApp
6917                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6918                final boolean isTargetHiddenFromInstantApp =
6919                        !isTargetVisibleToInstantApp
6920                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6921                final boolean blockResolution =
6922                        !isTargetSameInstantApp
6923                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6924                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6925                                        && isTargetHiddenFromInstantApp));
6926                if (!blockResolution) {
6927                    final ResolveInfo ri = new ResolveInfo();
6928                    ri.activityInfo = ai;
6929                    list.add(ri);
6930                }
6931            }
6932            return applyPostResolutionFilter(list, instantAppPkgName);
6933        }
6934
6935        // reader
6936        boolean sortResult = false;
6937        boolean addEphemeral = false;
6938        List<ResolveInfo> result;
6939        final boolean ephemeralDisabled = isEphemeralDisabled();
6940        synchronized (mPackages) {
6941            if (pkgName == null) {
6942                List<CrossProfileIntentFilter> matchingFilters =
6943                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6944                // Check for results that need to skip the current profile.
6945                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6946                        resolvedType, flags, userId);
6947                if (xpResolveInfo != null) {
6948                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6949                    xpResult.add(xpResolveInfo);
6950                    return applyPostResolutionFilter(
6951                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6952                }
6953
6954                // Check for results in the current profile.
6955                result = filterIfNotSystemUser(mActivities.queryIntent(
6956                        intent, resolvedType, flags, userId), userId);
6957                addEphemeral = !ephemeralDisabled
6958                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6959                // Check for cross profile results.
6960                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6961                xpResolveInfo = queryCrossProfileIntents(
6962                        matchingFilters, intent, resolvedType, flags, userId,
6963                        hasNonNegativePriorityResult);
6964                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6965                    boolean isVisibleToUser = filterIfNotSystemUser(
6966                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6967                    if (isVisibleToUser) {
6968                        result.add(xpResolveInfo);
6969                        sortResult = true;
6970                    }
6971                }
6972                if (hasWebURI(intent)) {
6973                    CrossProfileDomainInfo xpDomainInfo = null;
6974                    final UserInfo parent = getProfileParent(userId);
6975                    if (parent != null) {
6976                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6977                                flags, userId, parent.id);
6978                    }
6979                    if (xpDomainInfo != null) {
6980                        if (xpResolveInfo != null) {
6981                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6982                            // in the result.
6983                            result.remove(xpResolveInfo);
6984                        }
6985                        if (result.size() == 0 && !addEphemeral) {
6986                            // No result in current profile, but found candidate in parent user.
6987                            // And we are not going to add emphemeral app, so we can return the
6988                            // result straight away.
6989                            result.add(xpDomainInfo.resolveInfo);
6990                            return applyPostResolutionFilter(result, instantAppPkgName);
6991                        }
6992                    } else if (result.size() <= 1 && !addEphemeral) {
6993                        // No result in parent user and <= 1 result in current profile, and we
6994                        // are not going to add emphemeral app, so we can return the result without
6995                        // further processing.
6996                        return applyPostResolutionFilter(result, instantAppPkgName);
6997                    }
6998                    // We have more than one candidate (combining results from current and parent
6999                    // profile), so we need filtering and sorting.
7000                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7001                            intent, flags, result, xpDomainInfo, userId);
7002                    sortResult = true;
7003                }
7004            } else {
7005                final PackageParser.Package pkg = mPackages.get(pkgName);
7006                result = null;
7007                if (pkg != null) {
7008                    result = filterIfNotSystemUser(
7009                            mActivities.queryIntentForPackage(
7010                                    intent, resolvedType, flags, pkg.activities, userId),
7011                            userId);
7012                }
7013                if (result == null || result.size() == 0) {
7014                    // the caller wants to resolve for a particular package; however, there
7015                    // were no installed results, so, try to find an ephemeral result
7016                    addEphemeral = !ephemeralDisabled
7017                            && isInstantAppAllowed(
7018                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7019                    if (result == null) {
7020                        result = new ArrayList<>();
7021                    }
7022                }
7023            }
7024        }
7025        if (addEphemeral) {
7026            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7027        }
7028        if (sortResult) {
7029            Collections.sort(result, mResolvePrioritySorter);
7030        }
7031        return applyPostResolutionFilter(result, instantAppPkgName);
7032    }
7033
7034    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7035            String resolvedType, int flags, int userId) {
7036        // first, check to see if we've got an instant app already installed
7037        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7038        ResolveInfo localInstantApp = null;
7039        boolean blockResolution = false;
7040        if (!alreadyResolvedLocally) {
7041            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7042                    flags
7043                        | PackageManager.GET_RESOLVED_FILTER
7044                        | PackageManager.MATCH_INSTANT
7045                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7046                    userId);
7047            for (int i = instantApps.size() - 1; i >= 0; --i) {
7048                final ResolveInfo info = instantApps.get(i);
7049                final String packageName = info.activityInfo.packageName;
7050                final PackageSetting ps = mSettings.mPackages.get(packageName);
7051                if (ps.getInstantApp(userId)) {
7052                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7053                    final int status = (int)(packedStatus >> 32);
7054                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7055                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7056                        // there's a local instant application installed, but, the user has
7057                        // chosen to never use it; skip resolution and don't acknowledge
7058                        // an instant application is even available
7059                        if (DEBUG_EPHEMERAL) {
7060                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7061                        }
7062                        blockResolution = true;
7063                        break;
7064                    } else {
7065                        // we have a locally installed instant application; skip resolution
7066                        // but acknowledge there's an instant application available
7067                        if (DEBUG_EPHEMERAL) {
7068                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7069                        }
7070                        localInstantApp = info;
7071                        break;
7072                    }
7073                }
7074            }
7075        }
7076        // no app installed, let's see if one's available
7077        AuxiliaryResolveInfo auxiliaryResponse = null;
7078        if (!blockResolution) {
7079            if (localInstantApp == null) {
7080                // we don't have an instant app locally, resolve externally
7081                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7082                final InstantAppRequest requestObject = new InstantAppRequest(
7083                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7084                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7085                auxiliaryResponse =
7086                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7087                                mContext, mInstantAppResolverConnection, requestObject);
7088                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7089            } else {
7090                // we have an instant application locally, but, we can't admit that since
7091                // callers shouldn't be able to determine prior browsing. create a dummy
7092                // auxiliary response so the downstream code behaves as if there's an
7093                // instant application available externally. when it comes time to start
7094                // the instant application, we'll do the right thing.
7095                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7096                auxiliaryResponse = new AuxiliaryResolveInfo(
7097                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7098            }
7099        }
7100        if (auxiliaryResponse != null) {
7101            if (DEBUG_EPHEMERAL) {
7102                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7103            }
7104            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7105            final PackageSetting ps =
7106                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7107            if (ps != null) {
7108                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7109                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7110                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7111                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7112                // make sure this resolver is the default
7113                ephemeralInstaller.isDefault = true;
7114                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7115                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7116                // add a non-generic filter
7117                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7118                ephemeralInstaller.filter.addDataPath(
7119                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7120                ephemeralInstaller.isInstantAppAvailable = true;
7121                result.add(ephemeralInstaller);
7122            }
7123        }
7124        return result;
7125    }
7126
7127    private static class CrossProfileDomainInfo {
7128        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7129        ResolveInfo resolveInfo;
7130        /* Best domain verification status of the activities found in the other profile */
7131        int bestDomainVerificationStatus;
7132    }
7133
7134    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7135            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7136        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7137                sourceUserId)) {
7138            return null;
7139        }
7140        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7141                resolvedType, flags, parentUserId);
7142
7143        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7144            return null;
7145        }
7146        CrossProfileDomainInfo result = null;
7147        int size = resultTargetUser.size();
7148        for (int i = 0; i < size; i++) {
7149            ResolveInfo riTargetUser = resultTargetUser.get(i);
7150            // Intent filter verification is only for filters that specify a host. So don't return
7151            // those that handle all web uris.
7152            if (riTargetUser.handleAllWebDataURI) {
7153                continue;
7154            }
7155            String packageName = riTargetUser.activityInfo.packageName;
7156            PackageSetting ps = mSettings.mPackages.get(packageName);
7157            if (ps == null) {
7158                continue;
7159            }
7160            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7161            int status = (int)(verificationState >> 32);
7162            if (result == null) {
7163                result = new CrossProfileDomainInfo();
7164                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7165                        sourceUserId, parentUserId);
7166                result.bestDomainVerificationStatus = status;
7167            } else {
7168                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7169                        result.bestDomainVerificationStatus);
7170            }
7171        }
7172        // Don't consider matches with status NEVER across profiles.
7173        if (result != null && result.bestDomainVerificationStatus
7174                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7175            return null;
7176        }
7177        return result;
7178    }
7179
7180    /**
7181     * Verification statuses are ordered from the worse to the best, except for
7182     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7183     */
7184    private int bestDomainVerificationStatus(int status1, int status2) {
7185        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7186            return status2;
7187        }
7188        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7189            return status1;
7190        }
7191        return (int) MathUtils.max(status1, status2);
7192    }
7193
7194    private boolean isUserEnabled(int userId) {
7195        long callingId = Binder.clearCallingIdentity();
7196        try {
7197            UserInfo userInfo = sUserManager.getUserInfo(userId);
7198            return userInfo != null && userInfo.isEnabled();
7199        } finally {
7200            Binder.restoreCallingIdentity(callingId);
7201        }
7202    }
7203
7204    /**
7205     * Filter out activities with systemUserOnly flag set, when current user is not System.
7206     *
7207     * @return filtered list
7208     */
7209    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7210        if (userId == UserHandle.USER_SYSTEM) {
7211            return resolveInfos;
7212        }
7213        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7214            ResolveInfo info = resolveInfos.get(i);
7215            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7216                resolveInfos.remove(i);
7217            }
7218        }
7219        return resolveInfos;
7220    }
7221
7222    /**
7223     * Filters out ephemeral activities.
7224     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7225     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7226     *
7227     * @param resolveInfos The pre-filtered list of resolved activities
7228     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7229     *          is performed.
7230     * @return A filtered list of resolved activities.
7231     */
7232    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7233            String ephemeralPkgName) {
7234        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7235            final ResolveInfo info = resolveInfos.get(i);
7236            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7237            // TODO: When adding on-demand split support for non-instant apps, remove this check
7238            // and always apply post filtering
7239            // allow activities that are defined in the provided package
7240            if (isEphemeralApp) {
7241                if (info.activityInfo.splitName != null
7242                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7243                                info.activityInfo.splitName)) {
7244                    // requested activity is defined in a split that hasn't been installed yet.
7245                    // add the installer to the resolve list
7246                    if (DEBUG_EPHEMERAL) {
7247                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7248                    }
7249                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7250                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7251                            info.activityInfo.packageName, info.activityInfo.splitName,
7252                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7253                    // make sure this resolver is the default
7254                    installerInfo.isDefault = true;
7255                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7256                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7257                    // add a non-generic filter
7258                    installerInfo.filter = new IntentFilter();
7259                    // load resources from the correct package
7260                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7261                    resolveInfos.set(i, installerInfo);
7262                    continue;
7263                }
7264            }
7265            // caller is a full app, don't need to apply any other filtering
7266            if (ephemeralPkgName == null) {
7267                continue;
7268            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7269                // caller is same app; don't need to apply any other filtering
7270                continue;
7271            }
7272            // allow activities that have been explicitly exposed to ephemeral apps
7273            if (!isEphemeralApp
7274                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7275                continue;
7276            }
7277            resolveInfos.remove(i);
7278        }
7279        return resolveInfos;
7280    }
7281
7282    /**
7283     * @param resolveInfos list of resolve infos in descending priority order
7284     * @return if the list contains a resolve info with non-negative priority
7285     */
7286    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7287        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7288    }
7289
7290    private static boolean hasWebURI(Intent intent) {
7291        if (intent.getData() == null) {
7292            return false;
7293        }
7294        final String scheme = intent.getScheme();
7295        if (TextUtils.isEmpty(scheme)) {
7296            return false;
7297        }
7298        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7299    }
7300
7301    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7302            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7303            int userId) {
7304        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7305
7306        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7307            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7308                    candidates.size());
7309        }
7310
7311        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7312        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7313        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7314        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7315        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7316        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7317
7318        synchronized (mPackages) {
7319            final int count = candidates.size();
7320            // First, try to use linked apps. Partition the candidates into four lists:
7321            // one for the final results, one for the "do not use ever", one for "undefined status"
7322            // and finally one for "browser app type".
7323            for (int n=0; n<count; n++) {
7324                ResolveInfo info = candidates.get(n);
7325                String packageName = info.activityInfo.packageName;
7326                PackageSetting ps = mSettings.mPackages.get(packageName);
7327                if (ps != null) {
7328                    // Add to the special match all list (Browser use case)
7329                    if (info.handleAllWebDataURI) {
7330                        matchAllList.add(info);
7331                        continue;
7332                    }
7333                    // Try to get the status from User settings first
7334                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7335                    int status = (int)(packedStatus >> 32);
7336                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7337                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7338                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7339                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7340                                    + " : linkgen=" + linkGeneration);
7341                        }
7342                        // Use link-enabled generation as preferredOrder, i.e.
7343                        // prefer newly-enabled over earlier-enabled.
7344                        info.preferredOrder = linkGeneration;
7345                        alwaysList.add(info);
7346                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7347                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7348                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7349                        }
7350                        neverList.add(info);
7351                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7352                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7353                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7354                        }
7355                        alwaysAskList.add(info);
7356                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7357                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7358                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7359                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7360                        }
7361                        undefinedList.add(info);
7362                    }
7363                }
7364            }
7365
7366            // We'll want to include browser possibilities in a few cases
7367            boolean includeBrowser = false;
7368
7369            // First try to add the "always" resolution(s) for the current user, if any
7370            if (alwaysList.size() > 0) {
7371                result.addAll(alwaysList);
7372            } else {
7373                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7374                result.addAll(undefinedList);
7375                // Maybe add one for the other profile.
7376                if (xpDomainInfo != null && (
7377                        xpDomainInfo.bestDomainVerificationStatus
7378                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7379                    result.add(xpDomainInfo.resolveInfo);
7380                }
7381                includeBrowser = true;
7382            }
7383
7384            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7385            // If there were 'always' entries their preferred order has been set, so we also
7386            // back that off to make the alternatives equivalent
7387            if (alwaysAskList.size() > 0) {
7388                for (ResolveInfo i : result) {
7389                    i.preferredOrder = 0;
7390                }
7391                result.addAll(alwaysAskList);
7392                includeBrowser = true;
7393            }
7394
7395            if (includeBrowser) {
7396                // Also add browsers (all of them or only the default one)
7397                if (DEBUG_DOMAIN_VERIFICATION) {
7398                    Slog.v(TAG, "   ...including browsers in candidate set");
7399                }
7400                if ((matchFlags & MATCH_ALL) != 0) {
7401                    result.addAll(matchAllList);
7402                } else {
7403                    // Browser/generic handling case.  If there's a default browser, go straight
7404                    // to that (but only if there is no other higher-priority match).
7405                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7406                    int maxMatchPrio = 0;
7407                    ResolveInfo defaultBrowserMatch = null;
7408                    final int numCandidates = matchAllList.size();
7409                    for (int n = 0; n < numCandidates; n++) {
7410                        ResolveInfo info = matchAllList.get(n);
7411                        // track the highest overall match priority...
7412                        if (info.priority > maxMatchPrio) {
7413                            maxMatchPrio = info.priority;
7414                        }
7415                        // ...and the highest-priority default browser match
7416                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7417                            if (defaultBrowserMatch == null
7418                                    || (defaultBrowserMatch.priority < info.priority)) {
7419                                if (debug) {
7420                                    Slog.v(TAG, "Considering default browser match " + info);
7421                                }
7422                                defaultBrowserMatch = info;
7423                            }
7424                        }
7425                    }
7426                    if (defaultBrowserMatch != null
7427                            && defaultBrowserMatch.priority >= maxMatchPrio
7428                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7429                    {
7430                        if (debug) {
7431                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7432                        }
7433                        result.add(defaultBrowserMatch);
7434                    } else {
7435                        result.addAll(matchAllList);
7436                    }
7437                }
7438
7439                // If there is nothing selected, add all candidates and remove the ones that the user
7440                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7441                if (result.size() == 0) {
7442                    result.addAll(candidates);
7443                    result.removeAll(neverList);
7444                }
7445            }
7446        }
7447        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7448            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7449                    result.size());
7450            for (ResolveInfo info : result) {
7451                Slog.v(TAG, "  + " + info.activityInfo);
7452            }
7453        }
7454        return result;
7455    }
7456
7457    // Returns a packed value as a long:
7458    //
7459    // high 'int'-sized word: link status: undefined/ask/never/always.
7460    // low 'int'-sized word: relative priority among 'always' results.
7461    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7462        long result = ps.getDomainVerificationStatusForUser(userId);
7463        // if none available, get the master status
7464        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7465            if (ps.getIntentFilterVerificationInfo() != null) {
7466                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7467            }
7468        }
7469        return result;
7470    }
7471
7472    private ResolveInfo querySkipCurrentProfileIntents(
7473            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7474            int flags, int sourceUserId) {
7475        if (matchingFilters != null) {
7476            int size = matchingFilters.size();
7477            for (int i = 0; i < size; i ++) {
7478                CrossProfileIntentFilter filter = matchingFilters.get(i);
7479                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7480                    // Checking if there are activities in the target user that can handle the
7481                    // intent.
7482                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7483                            resolvedType, flags, sourceUserId);
7484                    if (resolveInfo != null) {
7485                        return resolveInfo;
7486                    }
7487                }
7488            }
7489        }
7490        return null;
7491    }
7492
7493    // Return matching ResolveInfo in target user if any.
7494    private ResolveInfo queryCrossProfileIntents(
7495            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7496            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7497        if (matchingFilters != null) {
7498            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7499            // match the same intent. For performance reasons, it is better not to
7500            // run queryIntent twice for the same userId
7501            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7502            int size = matchingFilters.size();
7503            for (int i = 0; i < size; i++) {
7504                CrossProfileIntentFilter filter = matchingFilters.get(i);
7505                int targetUserId = filter.getTargetUserId();
7506                boolean skipCurrentProfile =
7507                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7508                boolean skipCurrentProfileIfNoMatchFound =
7509                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7510                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7511                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7512                    // Checking if there are activities in the target user that can handle the
7513                    // intent.
7514                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7515                            resolvedType, flags, sourceUserId);
7516                    if (resolveInfo != null) return resolveInfo;
7517                    alreadyTriedUserIds.put(targetUserId, true);
7518                }
7519            }
7520        }
7521        return null;
7522    }
7523
7524    /**
7525     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7526     * will forward the intent to the filter's target user.
7527     * Otherwise, returns null.
7528     */
7529    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7530            String resolvedType, int flags, int sourceUserId) {
7531        int targetUserId = filter.getTargetUserId();
7532        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7533                resolvedType, flags, targetUserId);
7534        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7535            // If all the matches in the target profile are suspended, return null.
7536            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7537                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7538                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7539                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7540                            targetUserId);
7541                }
7542            }
7543        }
7544        return null;
7545    }
7546
7547    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7548            int sourceUserId, int targetUserId) {
7549        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7550        long ident = Binder.clearCallingIdentity();
7551        boolean targetIsProfile;
7552        try {
7553            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7554        } finally {
7555            Binder.restoreCallingIdentity(ident);
7556        }
7557        String className;
7558        if (targetIsProfile) {
7559            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7560        } else {
7561            className = FORWARD_INTENT_TO_PARENT;
7562        }
7563        ComponentName forwardingActivityComponentName = new ComponentName(
7564                mAndroidApplication.packageName, className);
7565        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7566                sourceUserId);
7567        if (!targetIsProfile) {
7568            forwardingActivityInfo.showUserIcon = targetUserId;
7569            forwardingResolveInfo.noResourceId = true;
7570        }
7571        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7572        forwardingResolveInfo.priority = 0;
7573        forwardingResolveInfo.preferredOrder = 0;
7574        forwardingResolveInfo.match = 0;
7575        forwardingResolveInfo.isDefault = true;
7576        forwardingResolveInfo.filter = filter;
7577        forwardingResolveInfo.targetUserId = targetUserId;
7578        return forwardingResolveInfo;
7579    }
7580
7581    @Override
7582    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7583            Intent[] specifics, String[] specificTypes, Intent intent,
7584            String resolvedType, int flags, int userId) {
7585        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7586                specificTypes, intent, resolvedType, flags, userId));
7587    }
7588
7589    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7590            Intent[] specifics, String[] specificTypes, Intent intent,
7591            String resolvedType, int flags, int userId) {
7592        if (!sUserManager.exists(userId)) return Collections.emptyList();
7593        final int callingUid = Binder.getCallingUid();
7594        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7595                false /*includeInstantApps*/);
7596        enforceCrossUserPermission(callingUid, userId,
7597                false /*requireFullPermission*/, false /*checkShell*/,
7598                "query intent activity options");
7599        final String resultsAction = intent.getAction();
7600
7601        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7602                | PackageManager.GET_RESOLVED_FILTER, userId);
7603
7604        if (DEBUG_INTENT_MATCHING) {
7605            Log.v(TAG, "Query " + intent + ": " + results);
7606        }
7607
7608        int specificsPos = 0;
7609        int N;
7610
7611        // todo: note that the algorithm used here is O(N^2).  This
7612        // isn't a problem in our current environment, but if we start running
7613        // into situations where we have more than 5 or 10 matches then this
7614        // should probably be changed to something smarter...
7615
7616        // First we go through and resolve each of the specific items
7617        // that were supplied, taking care of removing any corresponding
7618        // duplicate items in the generic resolve list.
7619        if (specifics != null) {
7620            for (int i=0; i<specifics.length; i++) {
7621                final Intent sintent = specifics[i];
7622                if (sintent == null) {
7623                    continue;
7624                }
7625
7626                if (DEBUG_INTENT_MATCHING) {
7627                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7628                }
7629
7630                String action = sintent.getAction();
7631                if (resultsAction != null && resultsAction.equals(action)) {
7632                    // If this action was explicitly requested, then don't
7633                    // remove things that have it.
7634                    action = null;
7635                }
7636
7637                ResolveInfo ri = null;
7638                ActivityInfo ai = null;
7639
7640                ComponentName comp = sintent.getComponent();
7641                if (comp == null) {
7642                    ri = resolveIntent(
7643                        sintent,
7644                        specificTypes != null ? specificTypes[i] : null,
7645                            flags, userId);
7646                    if (ri == null) {
7647                        continue;
7648                    }
7649                    if (ri == mResolveInfo) {
7650                        // ACK!  Must do something better with this.
7651                    }
7652                    ai = ri.activityInfo;
7653                    comp = new ComponentName(ai.applicationInfo.packageName,
7654                            ai.name);
7655                } else {
7656                    ai = getActivityInfo(comp, flags, userId);
7657                    if (ai == null) {
7658                        continue;
7659                    }
7660                }
7661
7662                // Look for any generic query activities that are duplicates
7663                // of this specific one, and remove them from the results.
7664                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7665                N = results.size();
7666                int j;
7667                for (j=specificsPos; j<N; j++) {
7668                    ResolveInfo sri = results.get(j);
7669                    if ((sri.activityInfo.name.equals(comp.getClassName())
7670                            && sri.activityInfo.applicationInfo.packageName.equals(
7671                                    comp.getPackageName()))
7672                        || (action != null && sri.filter.matchAction(action))) {
7673                        results.remove(j);
7674                        if (DEBUG_INTENT_MATCHING) Log.v(
7675                            TAG, "Removing duplicate item from " + j
7676                            + " due to specific " + specificsPos);
7677                        if (ri == null) {
7678                            ri = sri;
7679                        }
7680                        j--;
7681                        N--;
7682                    }
7683                }
7684
7685                // Add this specific item to its proper place.
7686                if (ri == null) {
7687                    ri = new ResolveInfo();
7688                    ri.activityInfo = ai;
7689                }
7690                results.add(specificsPos, ri);
7691                ri.specificIndex = i;
7692                specificsPos++;
7693            }
7694        }
7695
7696        // Now we go through the remaining generic results and remove any
7697        // duplicate actions that are found here.
7698        N = results.size();
7699        for (int i=specificsPos; i<N-1; i++) {
7700            final ResolveInfo rii = results.get(i);
7701            if (rii.filter == null) {
7702                continue;
7703            }
7704
7705            // Iterate over all of the actions of this result's intent
7706            // filter...  typically this should be just one.
7707            final Iterator<String> it = rii.filter.actionsIterator();
7708            if (it == null) {
7709                continue;
7710            }
7711            while (it.hasNext()) {
7712                final String action = it.next();
7713                if (resultsAction != null && resultsAction.equals(action)) {
7714                    // If this action was explicitly requested, then don't
7715                    // remove things that have it.
7716                    continue;
7717                }
7718                for (int j=i+1; j<N; j++) {
7719                    final ResolveInfo rij = results.get(j);
7720                    if (rij.filter != null && rij.filter.hasAction(action)) {
7721                        results.remove(j);
7722                        if (DEBUG_INTENT_MATCHING) Log.v(
7723                            TAG, "Removing duplicate item from " + j
7724                            + " due to action " + action + " at " + i);
7725                        j--;
7726                        N--;
7727                    }
7728                }
7729            }
7730
7731            // If the caller didn't request filter information, drop it now
7732            // so we don't have to marshall/unmarshall it.
7733            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7734                rii.filter = null;
7735            }
7736        }
7737
7738        // Filter out the caller activity if so requested.
7739        if (caller != null) {
7740            N = results.size();
7741            for (int i=0; i<N; i++) {
7742                ActivityInfo ainfo = results.get(i).activityInfo;
7743                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7744                        && caller.getClassName().equals(ainfo.name)) {
7745                    results.remove(i);
7746                    break;
7747                }
7748            }
7749        }
7750
7751        // If the caller didn't request filter information,
7752        // drop them now so we don't have to
7753        // marshall/unmarshall it.
7754        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7755            N = results.size();
7756            for (int i=0; i<N; i++) {
7757                results.get(i).filter = null;
7758            }
7759        }
7760
7761        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7762        return results;
7763    }
7764
7765    @Override
7766    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7767            String resolvedType, int flags, int userId) {
7768        return new ParceledListSlice<>(
7769                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7770    }
7771
7772    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7773            String resolvedType, int flags, int userId) {
7774        if (!sUserManager.exists(userId)) return Collections.emptyList();
7775        final int callingUid = Binder.getCallingUid();
7776        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7777        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7778                false /*includeInstantApps*/);
7779        ComponentName comp = intent.getComponent();
7780        if (comp == null) {
7781            if (intent.getSelector() != null) {
7782                intent = intent.getSelector();
7783                comp = intent.getComponent();
7784            }
7785        }
7786        if (comp != null) {
7787            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7788            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7789            if (ai != null) {
7790                // When specifying an explicit component, we prevent the activity from being
7791                // used when either 1) the calling package is normal and the activity is within
7792                // an instant application or 2) the calling package is ephemeral and the
7793                // activity is not visible to instant applications.
7794                final boolean matchInstantApp =
7795                        (flags & PackageManager.MATCH_INSTANT) != 0;
7796                final boolean matchVisibleToInstantAppOnly =
7797                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7798                final boolean matchExplicitlyVisibleOnly =
7799                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7800                final boolean isCallerInstantApp =
7801                        instantAppPkgName != null;
7802                final boolean isTargetSameInstantApp =
7803                        comp.getPackageName().equals(instantAppPkgName);
7804                final boolean isTargetInstantApp =
7805                        (ai.applicationInfo.privateFlags
7806                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7807                final boolean isTargetVisibleToInstantApp =
7808                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7809                final boolean isTargetExplicitlyVisibleToInstantApp =
7810                        isTargetVisibleToInstantApp
7811                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7812                final boolean isTargetHiddenFromInstantApp =
7813                        !isTargetVisibleToInstantApp
7814                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7815                final boolean blockResolution =
7816                        !isTargetSameInstantApp
7817                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7818                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7819                                        && isTargetHiddenFromInstantApp));
7820                if (!blockResolution) {
7821                    ResolveInfo ri = new ResolveInfo();
7822                    ri.activityInfo = ai;
7823                    list.add(ri);
7824                }
7825            }
7826            return applyPostResolutionFilter(list, instantAppPkgName);
7827        }
7828
7829        // reader
7830        synchronized (mPackages) {
7831            String pkgName = intent.getPackage();
7832            if (pkgName == null) {
7833                final List<ResolveInfo> result =
7834                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7835                return applyPostResolutionFilter(result, instantAppPkgName);
7836            }
7837            final PackageParser.Package pkg = mPackages.get(pkgName);
7838            if (pkg != null) {
7839                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7840                        intent, resolvedType, flags, pkg.receivers, userId);
7841                return applyPostResolutionFilter(result, instantAppPkgName);
7842            }
7843            return Collections.emptyList();
7844        }
7845    }
7846
7847    @Override
7848    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7849        final int callingUid = Binder.getCallingUid();
7850        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7851    }
7852
7853    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7854            int userId, int callingUid) {
7855        if (!sUserManager.exists(userId)) return null;
7856        flags = updateFlagsForResolve(
7857                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7858        List<ResolveInfo> query = queryIntentServicesInternal(
7859                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7860        if (query != null) {
7861            if (query.size() >= 1) {
7862                // If there is more than one service with the same priority,
7863                // just arbitrarily pick the first one.
7864                return query.get(0);
7865            }
7866        }
7867        return null;
7868    }
7869
7870    @Override
7871    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7872            String resolvedType, int flags, int userId) {
7873        final int callingUid = Binder.getCallingUid();
7874        return new ParceledListSlice<>(queryIntentServicesInternal(
7875                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7876    }
7877
7878    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7879            String resolvedType, int flags, int userId, int callingUid,
7880            boolean includeInstantApps) {
7881        if (!sUserManager.exists(userId)) return Collections.emptyList();
7882        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7883        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7884        ComponentName comp = intent.getComponent();
7885        if (comp == null) {
7886            if (intent.getSelector() != null) {
7887                intent = intent.getSelector();
7888                comp = intent.getComponent();
7889            }
7890        }
7891        if (comp != null) {
7892            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7893            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7894            if (si != null) {
7895                // When specifying an explicit component, we prevent the service from being
7896                // used when either 1) the service is in an instant application and the
7897                // caller is not the same instant application or 2) the calling package is
7898                // ephemeral and the activity is not visible to ephemeral applications.
7899                final boolean matchInstantApp =
7900                        (flags & PackageManager.MATCH_INSTANT) != 0;
7901                final boolean matchVisibleToInstantAppOnly =
7902                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7903                final boolean isCallerInstantApp =
7904                        instantAppPkgName != null;
7905                final boolean isTargetSameInstantApp =
7906                        comp.getPackageName().equals(instantAppPkgName);
7907                final boolean isTargetInstantApp =
7908                        (si.applicationInfo.privateFlags
7909                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7910                final boolean isTargetHiddenFromInstantApp =
7911                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7912                final boolean blockResolution =
7913                        !isTargetSameInstantApp
7914                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7915                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7916                                        && isTargetHiddenFromInstantApp));
7917                if (!blockResolution) {
7918                    final ResolveInfo ri = new ResolveInfo();
7919                    ri.serviceInfo = si;
7920                    list.add(ri);
7921                }
7922            }
7923            return list;
7924        }
7925
7926        // reader
7927        synchronized (mPackages) {
7928            String pkgName = intent.getPackage();
7929            if (pkgName == null) {
7930                return applyPostServiceResolutionFilter(
7931                        mServices.queryIntent(intent, resolvedType, flags, userId),
7932                        instantAppPkgName);
7933            }
7934            final PackageParser.Package pkg = mPackages.get(pkgName);
7935            if (pkg != null) {
7936                return applyPostServiceResolutionFilter(
7937                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7938                                userId),
7939                        instantAppPkgName);
7940            }
7941            return Collections.emptyList();
7942        }
7943    }
7944
7945    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7946            String instantAppPkgName) {
7947        // TODO: When adding on-demand split support for non-instant apps, remove this check
7948        // and always apply post filtering
7949        if (instantAppPkgName == null) {
7950            return resolveInfos;
7951        }
7952        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7953            final ResolveInfo info = resolveInfos.get(i);
7954            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7955            // allow services that are defined in the provided package
7956            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7957                if (info.serviceInfo.splitName != null
7958                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7959                                info.serviceInfo.splitName)) {
7960                    // requested service is defined in a split that hasn't been installed yet.
7961                    // add the installer to the resolve list
7962                    if (DEBUG_EPHEMERAL) {
7963                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7964                    }
7965                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7966                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7967                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7968                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7969                    // make sure this resolver is the default
7970                    installerInfo.isDefault = true;
7971                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7972                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7973                    // add a non-generic filter
7974                    installerInfo.filter = new IntentFilter();
7975                    // load resources from the correct package
7976                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7977                    resolveInfos.set(i, installerInfo);
7978                }
7979                continue;
7980            }
7981            // allow services that have been explicitly exposed to ephemeral apps
7982            if (!isEphemeralApp
7983                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7984                continue;
7985            }
7986            resolveInfos.remove(i);
7987        }
7988        return resolveInfos;
7989    }
7990
7991    @Override
7992    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7993            String resolvedType, int flags, int userId) {
7994        return new ParceledListSlice<>(
7995                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7996    }
7997
7998    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7999            Intent intent, String resolvedType, int flags, int userId) {
8000        if (!sUserManager.exists(userId)) return Collections.emptyList();
8001        final int callingUid = Binder.getCallingUid();
8002        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8003        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8004                false /*includeInstantApps*/);
8005        ComponentName comp = intent.getComponent();
8006        if (comp == null) {
8007            if (intent.getSelector() != null) {
8008                intent = intent.getSelector();
8009                comp = intent.getComponent();
8010            }
8011        }
8012        if (comp != null) {
8013            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8014            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8015            if (pi != null) {
8016                // When specifying an explicit component, we prevent the provider from being
8017                // used when either 1) the provider is in an instant application and the
8018                // caller is not the same instant application or 2) the calling package is an
8019                // instant application and the provider is not visible to instant applications.
8020                final boolean matchInstantApp =
8021                        (flags & PackageManager.MATCH_INSTANT) != 0;
8022                final boolean matchVisibleToInstantAppOnly =
8023                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8024                final boolean isCallerInstantApp =
8025                        instantAppPkgName != null;
8026                final boolean isTargetSameInstantApp =
8027                        comp.getPackageName().equals(instantAppPkgName);
8028                final boolean isTargetInstantApp =
8029                        (pi.applicationInfo.privateFlags
8030                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8031                final boolean isTargetHiddenFromInstantApp =
8032                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8033                final boolean blockResolution =
8034                        !isTargetSameInstantApp
8035                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8036                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8037                                        && isTargetHiddenFromInstantApp));
8038                if (!blockResolution) {
8039                    final ResolveInfo ri = new ResolveInfo();
8040                    ri.providerInfo = pi;
8041                    list.add(ri);
8042                }
8043            }
8044            return list;
8045        }
8046
8047        // reader
8048        synchronized (mPackages) {
8049            String pkgName = intent.getPackage();
8050            if (pkgName == null) {
8051                return applyPostContentProviderResolutionFilter(
8052                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8053                        instantAppPkgName);
8054            }
8055            final PackageParser.Package pkg = mPackages.get(pkgName);
8056            if (pkg != null) {
8057                return applyPostContentProviderResolutionFilter(
8058                        mProviders.queryIntentForPackage(
8059                        intent, resolvedType, flags, pkg.providers, userId),
8060                        instantAppPkgName);
8061            }
8062            return Collections.emptyList();
8063        }
8064    }
8065
8066    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8067            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8068        // TODO: When adding on-demand split support for non-instant applications, remove
8069        // this check and always apply post filtering
8070        if (instantAppPkgName == null) {
8071            return resolveInfos;
8072        }
8073        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8074            final ResolveInfo info = resolveInfos.get(i);
8075            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8076            // allow providers that are defined in the provided package
8077            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8078                if (info.providerInfo.splitName != null
8079                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8080                                info.providerInfo.splitName)) {
8081                    // requested provider is defined in a split that hasn't been installed yet.
8082                    // add the installer to the resolve list
8083                    if (DEBUG_EPHEMERAL) {
8084                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8085                    }
8086                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8087                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8088                            info.providerInfo.packageName, info.providerInfo.splitName,
8089                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8090                    // make sure this resolver is the default
8091                    installerInfo.isDefault = true;
8092                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8093                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8094                    // add a non-generic filter
8095                    installerInfo.filter = new IntentFilter();
8096                    // load resources from the correct package
8097                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8098                    resolveInfos.set(i, installerInfo);
8099                }
8100                continue;
8101            }
8102            // allow providers that have been explicitly exposed to instant applications
8103            if (!isEphemeralApp
8104                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8105                continue;
8106            }
8107            resolveInfos.remove(i);
8108        }
8109        return resolveInfos;
8110    }
8111
8112    @Override
8113    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8114        final int callingUid = Binder.getCallingUid();
8115        if (getInstantAppPackageName(callingUid) != null) {
8116            return ParceledListSlice.emptyList();
8117        }
8118        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8119        flags = updateFlagsForPackage(flags, userId, null);
8120        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8121        enforceCrossUserPermission(callingUid, userId,
8122                true /* requireFullPermission */, false /* checkShell */,
8123                "get installed packages");
8124
8125        // writer
8126        synchronized (mPackages) {
8127            ArrayList<PackageInfo> list;
8128            if (listUninstalled) {
8129                list = new ArrayList<>(mSettings.mPackages.size());
8130                for (PackageSetting ps : mSettings.mPackages.values()) {
8131                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8132                        continue;
8133                    }
8134                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8135                        return null;
8136                    }
8137                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8138                    if (pi != null) {
8139                        list.add(pi);
8140                    }
8141                }
8142            } else {
8143                list = new ArrayList<>(mPackages.size());
8144                for (PackageParser.Package p : mPackages.values()) {
8145                    final PackageSetting ps = (PackageSetting) p.mExtras;
8146                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8147                        continue;
8148                    }
8149                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8150                        return null;
8151                    }
8152                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8153                            p.mExtras, flags, userId);
8154                    if (pi != null) {
8155                        list.add(pi);
8156                    }
8157                }
8158            }
8159
8160            return new ParceledListSlice<>(list);
8161        }
8162    }
8163
8164    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8165            String[] permissions, boolean[] tmp, int flags, int userId) {
8166        int numMatch = 0;
8167        final PermissionsState permissionsState = ps.getPermissionsState();
8168        for (int i=0; i<permissions.length; i++) {
8169            final String permission = permissions[i];
8170            if (permissionsState.hasPermission(permission, userId)) {
8171                tmp[i] = true;
8172                numMatch++;
8173            } else {
8174                tmp[i] = false;
8175            }
8176        }
8177        if (numMatch == 0) {
8178            return;
8179        }
8180        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8181
8182        // The above might return null in cases of uninstalled apps or install-state
8183        // skew across users/profiles.
8184        if (pi != null) {
8185            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8186                if (numMatch == permissions.length) {
8187                    pi.requestedPermissions = permissions;
8188                } else {
8189                    pi.requestedPermissions = new String[numMatch];
8190                    numMatch = 0;
8191                    for (int i=0; i<permissions.length; i++) {
8192                        if (tmp[i]) {
8193                            pi.requestedPermissions[numMatch] = permissions[i];
8194                            numMatch++;
8195                        }
8196                    }
8197                }
8198            }
8199            list.add(pi);
8200        }
8201    }
8202
8203    @Override
8204    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8205            String[] permissions, int flags, int userId) {
8206        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8207        flags = updateFlagsForPackage(flags, userId, permissions);
8208        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8209                true /* requireFullPermission */, false /* checkShell */,
8210                "get packages holding permissions");
8211        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8212
8213        // writer
8214        synchronized (mPackages) {
8215            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8216            boolean[] tmpBools = new boolean[permissions.length];
8217            if (listUninstalled) {
8218                for (PackageSetting ps : mSettings.mPackages.values()) {
8219                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8220                            userId);
8221                }
8222            } else {
8223                for (PackageParser.Package pkg : mPackages.values()) {
8224                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8225                    if (ps != null) {
8226                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8227                                userId);
8228                    }
8229                }
8230            }
8231
8232            return new ParceledListSlice<PackageInfo>(list);
8233        }
8234    }
8235
8236    @Override
8237    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8238        final int callingUid = Binder.getCallingUid();
8239        if (getInstantAppPackageName(callingUid) != null) {
8240            return ParceledListSlice.emptyList();
8241        }
8242        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8243        flags = updateFlagsForApplication(flags, userId, null);
8244        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8245
8246        // writer
8247        synchronized (mPackages) {
8248            ArrayList<ApplicationInfo> list;
8249            if (listUninstalled) {
8250                list = new ArrayList<>(mSettings.mPackages.size());
8251                for (PackageSetting ps : mSettings.mPackages.values()) {
8252                    ApplicationInfo ai;
8253                    int effectiveFlags = flags;
8254                    if (ps.isSystem()) {
8255                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8256                    }
8257                    if (ps.pkg != null) {
8258                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8259                            continue;
8260                        }
8261                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8262                            return null;
8263                        }
8264                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8265                                ps.readUserState(userId), userId);
8266                        if (ai != null) {
8267                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8268                        }
8269                    } else {
8270                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8271                        // and already converts to externally visible package name
8272                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8273                                callingUid, effectiveFlags, userId);
8274                    }
8275                    if (ai != null) {
8276                        list.add(ai);
8277                    }
8278                }
8279            } else {
8280                list = new ArrayList<>(mPackages.size());
8281                for (PackageParser.Package p : mPackages.values()) {
8282                    if (p.mExtras != null) {
8283                        PackageSetting ps = (PackageSetting) p.mExtras;
8284                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8285                            continue;
8286                        }
8287                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8288                            return null;
8289                        }
8290                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8291                                ps.readUserState(userId), userId);
8292                        if (ai != null) {
8293                            ai.packageName = resolveExternalPackageNameLPr(p);
8294                            list.add(ai);
8295                        }
8296                    }
8297                }
8298            }
8299
8300            return new ParceledListSlice<>(list);
8301        }
8302    }
8303
8304    @Override
8305    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8306        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8307            return null;
8308        }
8309        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8310                "getEphemeralApplications");
8311        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8312                true /* requireFullPermission */, false /* checkShell */,
8313                "getEphemeralApplications");
8314        synchronized (mPackages) {
8315            List<InstantAppInfo> instantApps = mInstantAppRegistry
8316                    .getInstantAppsLPr(userId);
8317            if (instantApps != null) {
8318                return new ParceledListSlice<>(instantApps);
8319            }
8320        }
8321        return null;
8322    }
8323
8324    @Override
8325    public boolean isInstantApp(String packageName, int userId) {
8326        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8327                true /* requireFullPermission */, false /* checkShell */,
8328                "isInstantApp");
8329        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8330            return false;
8331        }
8332        int callingUid = Binder.getCallingUid();
8333        if (Process.isIsolated(callingUid)) {
8334            callingUid = mIsolatedOwners.get(callingUid);
8335        }
8336
8337        synchronized (mPackages) {
8338            final PackageSetting ps = mSettings.mPackages.get(packageName);
8339            PackageParser.Package pkg = mPackages.get(packageName);
8340            final boolean returnAllowed =
8341                    ps != null
8342                    && (isCallerSameApp(packageName, callingUid)
8343                            || canViewInstantApps(callingUid, userId)
8344                            || mInstantAppRegistry.isInstantAccessGranted(
8345                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8346            if (returnAllowed) {
8347                return ps.getInstantApp(userId);
8348            }
8349        }
8350        return false;
8351    }
8352
8353    @Override
8354    public byte[] getInstantAppCookie(String packageName, int userId) {
8355        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8356            return null;
8357        }
8358
8359        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8360                true /* requireFullPermission */, false /* checkShell */,
8361                "getInstantAppCookie");
8362        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8363            return null;
8364        }
8365        synchronized (mPackages) {
8366            return mInstantAppRegistry.getInstantAppCookieLPw(
8367                    packageName, userId);
8368        }
8369    }
8370
8371    @Override
8372    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8373        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8374            return true;
8375        }
8376
8377        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8378                true /* requireFullPermission */, true /* checkShell */,
8379                "setInstantAppCookie");
8380        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8381            return false;
8382        }
8383        synchronized (mPackages) {
8384            return mInstantAppRegistry.setInstantAppCookieLPw(
8385                    packageName, cookie, userId);
8386        }
8387    }
8388
8389    @Override
8390    public Bitmap getInstantAppIcon(String packageName, int userId) {
8391        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8392            return null;
8393        }
8394
8395        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8396                "getInstantAppIcon");
8397
8398        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8399                true /* requireFullPermission */, false /* checkShell */,
8400                "getInstantAppIcon");
8401
8402        synchronized (mPackages) {
8403            return mInstantAppRegistry.getInstantAppIconLPw(
8404                    packageName, userId);
8405        }
8406    }
8407
8408    private boolean isCallerSameApp(String packageName, int uid) {
8409        PackageParser.Package pkg = mPackages.get(packageName);
8410        return pkg != null
8411                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8412    }
8413
8414    @Override
8415    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8416        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8417            return ParceledListSlice.emptyList();
8418        }
8419        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8420    }
8421
8422    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8423        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8424
8425        // reader
8426        synchronized (mPackages) {
8427            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8428            final int userId = UserHandle.getCallingUserId();
8429            while (i.hasNext()) {
8430                final PackageParser.Package p = i.next();
8431                if (p.applicationInfo == null) continue;
8432
8433                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8434                        && !p.applicationInfo.isDirectBootAware();
8435                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8436                        && p.applicationInfo.isDirectBootAware();
8437
8438                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8439                        && (!mSafeMode || isSystemApp(p))
8440                        && (matchesUnaware || matchesAware)) {
8441                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8442                    if (ps != null) {
8443                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8444                                ps.readUserState(userId), userId);
8445                        if (ai != null) {
8446                            finalList.add(ai);
8447                        }
8448                    }
8449                }
8450            }
8451        }
8452
8453        return finalList;
8454    }
8455
8456    @Override
8457    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8458        if (!sUserManager.exists(userId)) return null;
8459        flags = updateFlagsForComponent(flags, userId, name);
8460        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8461        // reader
8462        synchronized (mPackages) {
8463            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8464            PackageSetting ps = provider != null
8465                    ? mSettings.mPackages.get(provider.owner.packageName)
8466                    : null;
8467            if (ps != null) {
8468                final boolean isInstantApp = ps.getInstantApp(userId);
8469                // normal application; filter out instant application provider
8470                if (instantAppPkgName == null && isInstantApp) {
8471                    return null;
8472                }
8473                // instant application; filter out other instant applications
8474                if (instantAppPkgName != null
8475                        && isInstantApp
8476                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8477                    return null;
8478                }
8479                // instant application; filter out non-exposed provider
8480                if (instantAppPkgName != null
8481                        && !isInstantApp
8482                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8483                    return null;
8484                }
8485                // provider not enabled
8486                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8487                    return null;
8488                }
8489                return PackageParser.generateProviderInfo(
8490                        provider, flags, ps.readUserState(userId), userId);
8491            }
8492            return null;
8493        }
8494    }
8495
8496    /**
8497     * @deprecated
8498     */
8499    @Deprecated
8500    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8501        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8502            return;
8503        }
8504        // reader
8505        synchronized (mPackages) {
8506            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8507                    .entrySet().iterator();
8508            final int userId = UserHandle.getCallingUserId();
8509            while (i.hasNext()) {
8510                Map.Entry<String, PackageParser.Provider> entry = i.next();
8511                PackageParser.Provider p = entry.getValue();
8512                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8513
8514                if (ps != null && p.syncable
8515                        && (!mSafeMode || (p.info.applicationInfo.flags
8516                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8517                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8518                            ps.readUserState(userId), userId);
8519                    if (info != null) {
8520                        outNames.add(entry.getKey());
8521                        outInfo.add(info);
8522                    }
8523                }
8524            }
8525        }
8526    }
8527
8528    @Override
8529    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8530            int uid, int flags, String metaDataKey) {
8531        final int callingUid = Binder.getCallingUid();
8532        final int userId = processName != null ? UserHandle.getUserId(uid)
8533                : UserHandle.getCallingUserId();
8534        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8535        flags = updateFlagsForComponent(flags, userId, processName);
8536        ArrayList<ProviderInfo> finalList = null;
8537        // reader
8538        synchronized (mPackages) {
8539            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8540            while (i.hasNext()) {
8541                final PackageParser.Provider p = i.next();
8542                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8543                if (ps != null && p.info.authority != null
8544                        && (processName == null
8545                                || (p.info.processName.equals(processName)
8546                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8547                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8548
8549                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8550                    // parameter.
8551                    if (metaDataKey != null
8552                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8553                        continue;
8554                    }
8555                    final ComponentName component =
8556                            new ComponentName(p.info.packageName, p.info.name);
8557                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8558                        continue;
8559                    }
8560                    if (finalList == null) {
8561                        finalList = new ArrayList<ProviderInfo>(3);
8562                    }
8563                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8564                            ps.readUserState(userId), userId);
8565                    if (info != null) {
8566                        finalList.add(info);
8567                    }
8568                }
8569            }
8570        }
8571
8572        if (finalList != null) {
8573            Collections.sort(finalList, mProviderInitOrderSorter);
8574            return new ParceledListSlice<ProviderInfo>(finalList);
8575        }
8576
8577        return ParceledListSlice.emptyList();
8578    }
8579
8580    @Override
8581    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8582        // reader
8583        synchronized (mPackages) {
8584            final int callingUid = Binder.getCallingUid();
8585            final int callingUserId = UserHandle.getUserId(callingUid);
8586            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8587            if (ps == null) return null;
8588            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8589                return null;
8590            }
8591            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8592            return PackageParser.generateInstrumentationInfo(i, flags);
8593        }
8594    }
8595
8596    @Override
8597    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8598            String targetPackage, int flags) {
8599        final int callingUid = Binder.getCallingUid();
8600        final int callingUserId = UserHandle.getUserId(callingUid);
8601        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8602        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8603            return ParceledListSlice.emptyList();
8604        }
8605        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8606    }
8607
8608    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8609            int flags) {
8610        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8611
8612        // reader
8613        synchronized (mPackages) {
8614            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8615            while (i.hasNext()) {
8616                final PackageParser.Instrumentation p = i.next();
8617                if (targetPackage == null
8618                        || targetPackage.equals(p.info.targetPackage)) {
8619                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8620                            flags);
8621                    if (ii != null) {
8622                        finalList.add(ii);
8623                    }
8624                }
8625            }
8626        }
8627
8628        return finalList;
8629    }
8630
8631    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8632        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8633        try {
8634            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8635        } finally {
8636            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8637        }
8638    }
8639
8640    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8641        final File[] files = dir.listFiles();
8642        if (ArrayUtils.isEmpty(files)) {
8643            Log.d(TAG, "No files in app dir " + dir);
8644            return;
8645        }
8646
8647        if (DEBUG_PACKAGE_SCANNING) {
8648            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8649                    + " flags=0x" + Integer.toHexString(parseFlags));
8650        }
8651        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8652                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8653                mParallelPackageParserCallback);
8654
8655        // Submit files for parsing in parallel
8656        int fileCount = 0;
8657        for (File file : files) {
8658            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8659                    && !PackageInstallerService.isStageName(file.getName());
8660            if (!isPackage) {
8661                // Ignore entries which are not packages
8662                continue;
8663            }
8664            parallelPackageParser.submit(file, parseFlags);
8665            fileCount++;
8666        }
8667
8668        // Process results one by one
8669        for (; fileCount > 0; fileCount--) {
8670            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8671            Throwable throwable = parseResult.throwable;
8672            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8673
8674            if (throwable == null) {
8675                // Static shared libraries have synthetic package names
8676                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8677                    renameStaticSharedLibraryPackage(parseResult.pkg);
8678                }
8679                try {
8680                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8681                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8682                                currentTime, null);
8683                    }
8684                } catch (PackageManagerException e) {
8685                    errorCode = e.error;
8686                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8687                }
8688            } else if (throwable instanceof PackageParser.PackageParserException) {
8689                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8690                        throwable;
8691                errorCode = e.error;
8692                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8693            } else {
8694                throw new IllegalStateException("Unexpected exception occurred while parsing "
8695                        + parseResult.scanFile, throwable);
8696            }
8697
8698            // Delete invalid userdata apps
8699            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8700                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8701                logCriticalInfo(Log.WARN,
8702                        "Deleting invalid package at " + parseResult.scanFile);
8703                removeCodePathLI(parseResult.scanFile);
8704            }
8705        }
8706        parallelPackageParser.close();
8707    }
8708
8709    private static File getSettingsProblemFile() {
8710        File dataDir = Environment.getDataDirectory();
8711        File systemDir = new File(dataDir, "system");
8712        File fname = new File(systemDir, "uiderrors.txt");
8713        return fname;
8714    }
8715
8716    static void reportSettingsProblem(int priority, String msg) {
8717        logCriticalInfo(priority, msg);
8718    }
8719
8720    public static void logCriticalInfo(int priority, String msg) {
8721        Slog.println(priority, TAG, msg);
8722        EventLogTags.writePmCriticalInfo(msg);
8723        try {
8724            File fname = getSettingsProblemFile();
8725            FileOutputStream out = new FileOutputStream(fname, true);
8726            PrintWriter pw = new FastPrintWriter(out);
8727            SimpleDateFormat formatter = new SimpleDateFormat();
8728            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8729            pw.println(dateString + ": " + msg);
8730            pw.close();
8731            FileUtils.setPermissions(
8732                    fname.toString(),
8733                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8734                    -1, -1);
8735        } catch (java.io.IOException e) {
8736        }
8737    }
8738
8739    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8740        if (srcFile.isDirectory()) {
8741            final File baseFile = new File(pkg.baseCodePath);
8742            long maxModifiedTime = baseFile.lastModified();
8743            if (pkg.splitCodePaths != null) {
8744                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8745                    final File splitFile = new File(pkg.splitCodePaths[i]);
8746                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8747                }
8748            }
8749            return maxModifiedTime;
8750        }
8751        return srcFile.lastModified();
8752    }
8753
8754    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8755            final int policyFlags) throws PackageManagerException {
8756        // When upgrading from pre-N MR1, verify the package time stamp using the package
8757        // directory and not the APK file.
8758        final long lastModifiedTime = mIsPreNMR1Upgrade
8759                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8760        if (ps != null
8761                && ps.codePath.equals(srcFile)
8762                && ps.timeStamp == lastModifiedTime
8763                && !isCompatSignatureUpdateNeeded(pkg)
8764                && !isRecoverSignatureUpdateNeeded(pkg)) {
8765            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8766            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8767            ArraySet<PublicKey> signingKs;
8768            synchronized (mPackages) {
8769                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8770            }
8771            if (ps.signatures.mSignatures != null
8772                    && ps.signatures.mSignatures.length != 0
8773                    && signingKs != null) {
8774                // Optimization: reuse the existing cached certificates
8775                // if the package appears to be unchanged.
8776                pkg.mSignatures = ps.signatures.mSignatures;
8777                pkg.mSigningKeys = signingKs;
8778                return;
8779            }
8780
8781            Slog.w(TAG, "PackageSetting for " + ps.name
8782                    + " is missing signatures.  Collecting certs again to recover them.");
8783        } else {
8784            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8785        }
8786
8787        try {
8788            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8789            PackageParser.collectCertificates(pkg, policyFlags);
8790        } catch (PackageParserException e) {
8791            throw PackageManagerException.from(e);
8792        } finally {
8793            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8794        }
8795    }
8796
8797    /**
8798     *  Traces a package scan.
8799     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8800     */
8801    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8802            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8803        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8804        try {
8805            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8806        } finally {
8807            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8808        }
8809    }
8810
8811    /**
8812     *  Scans a package and returns the newly parsed package.
8813     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8814     */
8815    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8816            long currentTime, UserHandle user) throws PackageManagerException {
8817        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8818        PackageParser pp = new PackageParser();
8819        pp.setSeparateProcesses(mSeparateProcesses);
8820        pp.setOnlyCoreApps(mOnlyCore);
8821        pp.setDisplayMetrics(mMetrics);
8822        pp.setCallback(mPackageParserCallback);
8823
8824        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8825            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8826        }
8827
8828        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8829        final PackageParser.Package pkg;
8830        try {
8831            pkg = pp.parsePackage(scanFile, parseFlags);
8832        } catch (PackageParserException e) {
8833            throw PackageManagerException.from(e);
8834        } finally {
8835            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8836        }
8837
8838        // Static shared libraries have synthetic package names
8839        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8840            renameStaticSharedLibraryPackage(pkg);
8841        }
8842
8843        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8844    }
8845
8846    /**
8847     *  Scans a package and returns the newly parsed package.
8848     *  @throws PackageManagerException on a parse error.
8849     */
8850    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8851            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8852            throws PackageManagerException {
8853        // If the package has children and this is the first dive in the function
8854        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8855        // packages (parent and children) would be successfully scanned before the
8856        // actual scan since scanning mutates internal state and we want to atomically
8857        // install the package and its children.
8858        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8859            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8860                scanFlags |= SCAN_CHECK_ONLY;
8861            }
8862        } else {
8863            scanFlags &= ~SCAN_CHECK_ONLY;
8864        }
8865
8866        // Scan the parent
8867        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8868                scanFlags, currentTime, user);
8869
8870        // Scan the children
8871        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8872        for (int i = 0; i < childCount; i++) {
8873            PackageParser.Package childPackage = pkg.childPackages.get(i);
8874            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8875                    currentTime, user);
8876        }
8877
8878
8879        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8880            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8881        }
8882
8883        return scannedPkg;
8884    }
8885
8886    /**
8887     *  Scans a package and returns the newly parsed package.
8888     *  @throws PackageManagerException on a parse error.
8889     */
8890    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8891            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8892            throws PackageManagerException {
8893        PackageSetting ps = null;
8894        PackageSetting updatedPkg;
8895        // reader
8896        synchronized (mPackages) {
8897            // Look to see if we already know about this package.
8898            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8899            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8900                // This package has been renamed to its original name.  Let's
8901                // use that.
8902                ps = mSettings.getPackageLPr(oldName);
8903            }
8904            // If there was no original package, see one for the real package name.
8905            if (ps == null) {
8906                ps = mSettings.getPackageLPr(pkg.packageName);
8907            }
8908            // Check to see if this package could be hiding/updating a system
8909            // package.  Must look for it either under the original or real
8910            // package name depending on our state.
8911            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8912            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8913
8914            // If this is a package we don't know about on the system partition, we
8915            // may need to remove disabled child packages on the system partition
8916            // or may need to not add child packages if the parent apk is updated
8917            // on the data partition and no longer defines this child package.
8918            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8919                // If this is a parent package for an updated system app and this system
8920                // app got an OTA update which no longer defines some of the child packages
8921                // we have to prune them from the disabled system packages.
8922                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8923                if (disabledPs != null) {
8924                    final int scannedChildCount = (pkg.childPackages != null)
8925                            ? pkg.childPackages.size() : 0;
8926                    final int disabledChildCount = disabledPs.childPackageNames != null
8927                            ? disabledPs.childPackageNames.size() : 0;
8928                    for (int i = 0; i < disabledChildCount; i++) {
8929                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8930                        boolean disabledPackageAvailable = false;
8931                        for (int j = 0; j < scannedChildCount; j++) {
8932                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8933                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8934                                disabledPackageAvailable = true;
8935                                break;
8936                            }
8937                         }
8938                         if (!disabledPackageAvailable) {
8939                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8940                         }
8941                    }
8942                }
8943            }
8944        }
8945
8946        final boolean isUpdatedPkg = updatedPkg != null;
8947        final boolean isUpdatedSystemPkg = isUpdatedPkg
8948                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
8949        boolean isUpdatedPkgBetter = false;
8950        // First check if this is a system package that may involve an update
8951        if (isUpdatedSystemPkg) {
8952            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8953            // it needs to drop FLAG_PRIVILEGED.
8954            if (locationIsPrivileged(scanFile)) {
8955                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8956            } else {
8957                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8958            }
8959
8960            if (ps != null && !ps.codePath.equals(scanFile)) {
8961                // The path has changed from what was last scanned...  check the
8962                // version of the new path against what we have stored to determine
8963                // what to do.
8964                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8965                if (pkg.mVersionCode <= ps.versionCode) {
8966                    // The system package has been updated and the code path does not match
8967                    // Ignore entry. Skip it.
8968                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8969                            + " ignored: updated version " + ps.versionCode
8970                            + " better than this " + pkg.mVersionCode);
8971                    if (!updatedPkg.codePath.equals(scanFile)) {
8972                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8973                                + ps.name + " changing from " + updatedPkg.codePathString
8974                                + " to " + scanFile);
8975                        updatedPkg.codePath = scanFile;
8976                        updatedPkg.codePathString = scanFile.toString();
8977                        updatedPkg.resourcePath = scanFile;
8978                        updatedPkg.resourcePathString = scanFile.toString();
8979                    }
8980                    updatedPkg.pkg = pkg;
8981                    updatedPkg.versionCode = pkg.mVersionCode;
8982
8983                    // Update the disabled system child packages to point to the package too.
8984                    final int childCount = updatedPkg.childPackageNames != null
8985                            ? updatedPkg.childPackageNames.size() : 0;
8986                    for (int i = 0; i < childCount; i++) {
8987                        String childPackageName = updatedPkg.childPackageNames.get(i);
8988                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8989                                childPackageName);
8990                        if (updatedChildPkg != null) {
8991                            updatedChildPkg.pkg = pkg;
8992                            updatedChildPkg.versionCode = pkg.mVersionCode;
8993                        }
8994                    }
8995                } else {
8996                    // The current app on the system partition is better than
8997                    // what we have updated to on the data partition; switch
8998                    // back to the system partition version.
8999                    // At this point, its safely assumed that package installation for
9000                    // apps in system partition will go through. If not there won't be a working
9001                    // version of the app
9002                    // writer
9003                    synchronized (mPackages) {
9004                        // Just remove the loaded entries from package lists.
9005                        mPackages.remove(ps.name);
9006                    }
9007
9008                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9009                            + " reverting from " + ps.codePathString
9010                            + ": new version " + pkg.mVersionCode
9011                            + " better than installed " + ps.versionCode);
9012
9013                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9014                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9015                    synchronized (mInstallLock) {
9016                        args.cleanUpResourcesLI();
9017                    }
9018                    synchronized (mPackages) {
9019                        mSettings.enableSystemPackageLPw(ps.name);
9020                    }
9021                    isUpdatedPkgBetter = true;
9022                }
9023            }
9024        }
9025
9026        String resourcePath = null;
9027        String baseResourcePath = null;
9028        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9029            if (ps != null && ps.resourcePathString != null) {
9030                resourcePath = ps.resourcePathString;
9031                baseResourcePath = ps.resourcePathString;
9032            } else {
9033                // Should not happen at all. Just log an error.
9034                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9035            }
9036        } else {
9037            resourcePath = pkg.codePath;
9038            baseResourcePath = pkg.baseCodePath;
9039        }
9040
9041        // Set application objects path explicitly.
9042        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9043        pkg.setApplicationInfoCodePath(pkg.codePath);
9044        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9045        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9046        pkg.setApplicationInfoResourcePath(resourcePath);
9047        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9048        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9049
9050        // throw an exception if we have an update to a system application, but, it's not more
9051        // recent than the package we've already scanned
9052        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9053            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9054                    + scanFile + " ignored: updated version " + ps.versionCode
9055                    + " better than this " + pkg.mVersionCode);
9056        }
9057
9058        if (isUpdatedPkg) {
9059            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9060            // initially
9061            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9062
9063            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9064            // flag set initially
9065            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9066                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9067            }
9068        }
9069
9070        // Verify certificates against what was last scanned
9071        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9072
9073        /*
9074         * A new system app appeared, but we already had a non-system one of the
9075         * same name installed earlier.
9076         */
9077        boolean shouldHideSystemApp = false;
9078        if (!isUpdatedPkg && ps != null
9079                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9080            /*
9081             * Check to make sure the signatures match first. If they don't,
9082             * wipe the installed application and its data.
9083             */
9084            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9085                    != PackageManager.SIGNATURE_MATCH) {
9086                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9087                        + " signatures don't match existing userdata copy; removing");
9088                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9089                        "scanPackageInternalLI")) {
9090                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9091                }
9092                ps = null;
9093            } else {
9094                /*
9095                 * If the newly-added system app is an older version than the
9096                 * already installed version, hide it. It will be scanned later
9097                 * and re-added like an update.
9098                 */
9099                if (pkg.mVersionCode <= ps.versionCode) {
9100                    shouldHideSystemApp = true;
9101                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9102                            + " but new version " + pkg.mVersionCode + " better than installed "
9103                            + ps.versionCode + "; hiding system");
9104                } else {
9105                    /*
9106                     * The newly found system app is a newer version that the
9107                     * one previously installed. Simply remove the
9108                     * already-installed application and replace it with our own
9109                     * while keeping the application data.
9110                     */
9111                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9112                            + " reverting from " + ps.codePathString + ": new version "
9113                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9114                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9115                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9116                    synchronized (mInstallLock) {
9117                        args.cleanUpResourcesLI();
9118                    }
9119                }
9120            }
9121        }
9122
9123        // The apk is forward locked (not public) if its code and resources
9124        // are kept in different files. (except for app in either system or
9125        // vendor path).
9126        // TODO grab this value from PackageSettings
9127        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9128            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9129                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9130            }
9131        }
9132
9133        final int userId = ((user == null) ? 0 : user.getIdentifier());
9134        if (ps != null && ps.getInstantApp(userId)) {
9135            scanFlags |= SCAN_AS_INSTANT_APP;
9136        }
9137
9138        // Note that we invoke the following method only if we are about to unpack an application
9139        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9140                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9141
9142        /*
9143         * If the system app should be overridden by a previously installed
9144         * data, hide the system app now and let the /data/app scan pick it up
9145         * again.
9146         */
9147        if (shouldHideSystemApp) {
9148            synchronized (mPackages) {
9149                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9150            }
9151        }
9152
9153        return scannedPkg;
9154    }
9155
9156    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9157        // Derive the new package synthetic package name
9158        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9159                + pkg.staticSharedLibVersion);
9160    }
9161
9162    private static String fixProcessName(String defProcessName,
9163            String processName) {
9164        if (processName == null) {
9165            return defProcessName;
9166        }
9167        return processName;
9168    }
9169
9170    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9171            throws PackageManagerException {
9172        if (pkgSetting.signatures.mSignatures != null) {
9173            // Already existing package. Make sure signatures match
9174            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9175                    == PackageManager.SIGNATURE_MATCH;
9176            if (!match) {
9177                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9178                        == PackageManager.SIGNATURE_MATCH;
9179            }
9180            if (!match) {
9181                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9182                        == PackageManager.SIGNATURE_MATCH;
9183            }
9184            if (!match) {
9185                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9186                        + pkg.packageName + " signatures do not match the "
9187                        + "previously installed version; ignoring!");
9188            }
9189        }
9190
9191        // Check for shared user signatures
9192        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9193            // Already existing package. Make sure signatures match
9194            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9195                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9196            if (!match) {
9197                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9198                        == PackageManager.SIGNATURE_MATCH;
9199            }
9200            if (!match) {
9201                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9202                        == PackageManager.SIGNATURE_MATCH;
9203            }
9204            if (!match) {
9205                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9206                        "Package " + pkg.packageName
9207                        + " has no signatures that match those in shared user "
9208                        + pkgSetting.sharedUser.name + "; ignoring!");
9209            }
9210        }
9211    }
9212
9213    /**
9214     * Enforces that only the system UID or root's UID can call a method exposed
9215     * via Binder.
9216     *
9217     * @param message used as message if SecurityException is thrown
9218     * @throws SecurityException if the caller is not system or root
9219     */
9220    private static final void enforceSystemOrRoot(String message) {
9221        final int uid = Binder.getCallingUid();
9222        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9223            throw new SecurityException(message);
9224        }
9225    }
9226
9227    @Override
9228    public void performFstrimIfNeeded() {
9229        enforceSystemOrRoot("Only the system can request fstrim");
9230
9231        // Before everything else, see whether we need to fstrim.
9232        try {
9233            IStorageManager sm = PackageHelper.getStorageManager();
9234            if (sm != null) {
9235                boolean doTrim = false;
9236                final long interval = android.provider.Settings.Global.getLong(
9237                        mContext.getContentResolver(),
9238                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9239                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9240                if (interval > 0) {
9241                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9242                    if (timeSinceLast > interval) {
9243                        doTrim = true;
9244                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9245                                + "; running immediately");
9246                    }
9247                }
9248                if (doTrim) {
9249                    final boolean dexOptDialogShown;
9250                    synchronized (mPackages) {
9251                        dexOptDialogShown = mDexOptDialogShown;
9252                    }
9253                    if (!isFirstBoot() && dexOptDialogShown) {
9254                        try {
9255                            ActivityManager.getService().showBootMessage(
9256                                    mContext.getResources().getString(
9257                                            R.string.android_upgrading_fstrim), true);
9258                        } catch (RemoteException e) {
9259                        }
9260                    }
9261                    sm.runMaintenance();
9262                }
9263            } else {
9264                Slog.e(TAG, "storageManager service unavailable!");
9265            }
9266        } catch (RemoteException e) {
9267            // Can't happen; StorageManagerService is local
9268        }
9269    }
9270
9271    @Override
9272    public void updatePackagesIfNeeded() {
9273        enforceSystemOrRoot("Only the system can request package update");
9274
9275        // We need to re-extract after an OTA.
9276        boolean causeUpgrade = isUpgrade();
9277
9278        // First boot or factory reset.
9279        // Note: we also handle devices that are upgrading to N right now as if it is their
9280        //       first boot, as they do not have profile data.
9281        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9282
9283        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9284        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9285
9286        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9287            return;
9288        }
9289
9290        List<PackageParser.Package> pkgs;
9291        synchronized (mPackages) {
9292            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9293        }
9294
9295        final long startTime = System.nanoTime();
9296        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9297                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9298                    false /* bootComplete */);
9299
9300        final int elapsedTimeSeconds =
9301                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9302
9303        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9304        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9305        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9306        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9307        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9308    }
9309
9310    /*
9311     * Return the prebuilt profile path given a package base code path.
9312     */
9313    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9314        return pkg.baseCodePath + ".prof";
9315    }
9316
9317    /**
9318     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9319     * containing statistics about the invocation. The array consists of three elements,
9320     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9321     * and {@code numberOfPackagesFailed}.
9322     */
9323    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9324            String compilerFilter, boolean bootComplete) {
9325
9326        int numberOfPackagesVisited = 0;
9327        int numberOfPackagesOptimized = 0;
9328        int numberOfPackagesSkipped = 0;
9329        int numberOfPackagesFailed = 0;
9330        final int numberOfPackagesToDexopt = pkgs.size();
9331
9332        for (PackageParser.Package pkg : pkgs) {
9333            numberOfPackagesVisited++;
9334
9335            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9336                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9337                // that are already compiled.
9338                File profileFile = new File(getPrebuildProfilePath(pkg));
9339                // Copy profile if it exists.
9340                if (profileFile.exists()) {
9341                    try {
9342                        // We could also do this lazily before calling dexopt in
9343                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9344                        // is that we don't have a good way to say "do this only once".
9345                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9346                                pkg.applicationInfo.uid, pkg.packageName)) {
9347                            Log.e(TAG, "Installer failed to copy system profile!");
9348                        }
9349                    } catch (Exception e) {
9350                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9351                                e);
9352                    }
9353                }
9354            }
9355
9356            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9357                if (DEBUG_DEXOPT) {
9358                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9359                }
9360                numberOfPackagesSkipped++;
9361                continue;
9362            }
9363
9364            if (DEBUG_DEXOPT) {
9365                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9366                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9367            }
9368
9369            if (showDialog) {
9370                try {
9371                    ActivityManager.getService().showBootMessage(
9372                            mContext.getResources().getString(R.string.android_upgrading_apk,
9373                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9374                } catch (RemoteException e) {
9375                }
9376                synchronized (mPackages) {
9377                    mDexOptDialogShown = true;
9378                }
9379            }
9380
9381            // If the OTA updates a system app which was previously preopted to a non-preopted state
9382            // the app might end up being verified at runtime. That's because by default the apps
9383            // are verify-profile but for preopted apps there's no profile.
9384            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9385            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9386            // filter (by default 'quicken').
9387            // Note that at this stage unused apps are already filtered.
9388            if (isSystemApp(pkg) &&
9389                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9390                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9391                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9392            }
9393
9394            // checkProfiles is false to avoid merging profiles during boot which
9395            // might interfere with background compilation (b/28612421).
9396            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9397            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9398            // trade-off worth doing to save boot time work.
9399            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9400            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9401                    pkg.packageName,
9402                    compilerFilter,
9403                    dexoptFlags));
9404
9405            boolean secondaryDexOptStatus = true;
9406            if (pkg.isSystemApp()) {
9407                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9408                // too much boot after an OTA.
9409                int secondaryDexoptFlags = dexoptFlags |
9410                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9411                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9412                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9413                        pkg.packageName,
9414                        compilerFilter,
9415                        secondaryDexoptFlags));
9416            }
9417
9418            if (secondaryDexOptStatus) {
9419                switch (primaryDexOptStaus) {
9420                    case PackageDexOptimizer.DEX_OPT_PERFORMED:
9421                        numberOfPackagesOptimized++;
9422                        break;
9423                    case PackageDexOptimizer.DEX_OPT_SKIPPED:
9424                        numberOfPackagesSkipped++;
9425                        break;
9426                    case PackageDexOptimizer.DEX_OPT_FAILED:
9427                        numberOfPackagesFailed++;
9428                        break;
9429                    default:
9430                        Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9431                        break;
9432                }
9433            } else {
9434                numberOfPackagesFailed++;
9435            }
9436        }
9437
9438        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9439                numberOfPackagesFailed };
9440    }
9441
9442    @Override
9443    public void notifyPackageUse(String packageName, int reason) {
9444        synchronized (mPackages) {
9445            final int callingUid = Binder.getCallingUid();
9446            final int callingUserId = UserHandle.getUserId(callingUid);
9447            if (getInstantAppPackageName(callingUid) != null) {
9448                if (!isCallerSameApp(packageName, callingUid)) {
9449                    return;
9450                }
9451            } else {
9452                if (isInstantApp(packageName, callingUserId)) {
9453                    return;
9454                }
9455            }
9456            final PackageParser.Package p = mPackages.get(packageName);
9457            if (p == null) {
9458                return;
9459            }
9460            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9461        }
9462    }
9463
9464    @Override
9465    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9466            List<String> classPaths, String loaderIsa) {
9467        int userId = UserHandle.getCallingUserId();
9468        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9469        if (ai == null) {
9470            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9471                + loadingPackageName + ", user=" + userId);
9472            return;
9473        }
9474        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9475    }
9476
9477    @Override
9478    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9479            IDexModuleRegisterCallback callback) {
9480        int userId = UserHandle.getCallingUserId();
9481        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9482        DexManager.RegisterDexModuleResult result;
9483        if (ai == null) {
9484            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9485                     " calling user. package=" + packageName + ", user=" + userId);
9486            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9487        } else {
9488            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9489        }
9490
9491        if (callback != null) {
9492            mHandler.post(() -> {
9493                try {
9494                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9495                } catch (RemoteException e) {
9496                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9497                }
9498            });
9499        }
9500    }
9501
9502    /**
9503     * Ask the package manager to perform a dex-opt with the given compiler filter.
9504     *
9505     * Note: exposed only for the shell command to allow moving packages explicitly to a
9506     *       definite state.
9507     */
9508    @Override
9509    public boolean performDexOptMode(String packageName,
9510            boolean checkProfiles, String targetCompilerFilter, boolean force,
9511            boolean bootComplete, String splitName) {
9512        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9513                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9514                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9515        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9516                splitName, flags));
9517    }
9518
9519    /**
9520     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9521     * secondary dex files belonging to the given package.
9522     *
9523     * Note: exposed only for the shell command to allow moving packages explicitly to a
9524     *       definite state.
9525     */
9526    @Override
9527    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9528            boolean force) {
9529        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9530                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9531                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9532                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9533        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9534    }
9535
9536    /*package*/ boolean performDexOpt(DexoptOptions options) {
9537        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9538            return false;
9539        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9540            return false;
9541        }
9542
9543        if (options.isDexoptOnlySecondaryDex()) {
9544            return mDexManager.dexoptSecondaryDex(options);
9545        } else {
9546            int dexoptStatus = performDexOptWithStatus(options);
9547            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9548        }
9549    }
9550
9551    /**
9552     * Perform dexopt on the given package and return one of following result:
9553     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9554     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9555     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9556     */
9557    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9558        return performDexOptTraced(options);
9559    }
9560
9561    private int performDexOptTraced(DexoptOptions options) {
9562        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9563        try {
9564            return performDexOptInternal(options);
9565        } finally {
9566            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9567        }
9568    }
9569
9570    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9571    // if the package can now be considered up to date for the given filter.
9572    private int performDexOptInternal(DexoptOptions options) {
9573        PackageParser.Package p;
9574        synchronized (mPackages) {
9575            p = mPackages.get(options.getPackageName());
9576            if (p == null) {
9577                // Package could not be found. Report failure.
9578                return PackageDexOptimizer.DEX_OPT_FAILED;
9579            }
9580            mPackageUsage.maybeWriteAsync(mPackages);
9581            mCompilerStats.maybeWriteAsync();
9582        }
9583        long callingId = Binder.clearCallingIdentity();
9584        try {
9585            synchronized (mInstallLock) {
9586                return performDexOptInternalWithDependenciesLI(p, options);
9587            }
9588        } finally {
9589            Binder.restoreCallingIdentity(callingId);
9590        }
9591    }
9592
9593    public ArraySet<String> getOptimizablePackages() {
9594        ArraySet<String> pkgs = new ArraySet<String>();
9595        synchronized (mPackages) {
9596            for (PackageParser.Package p : mPackages.values()) {
9597                if (PackageDexOptimizer.canOptimizePackage(p)) {
9598                    pkgs.add(p.packageName);
9599                }
9600            }
9601        }
9602        return pkgs;
9603    }
9604
9605    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9606            DexoptOptions options) {
9607        // Select the dex optimizer based on the force parameter.
9608        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9609        //       allocate an object here.
9610        PackageDexOptimizer pdo = options.isForce()
9611                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9612                : mPackageDexOptimizer;
9613
9614        // Dexopt all dependencies first. Note: we ignore the return value and march on
9615        // on errors.
9616        // Note that we are going to call performDexOpt on those libraries as many times as
9617        // they are referenced in packages. When we do a batch of performDexOpt (for example
9618        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9619        // and the first package that uses the library will dexopt it. The
9620        // others will see that the compiled code for the library is up to date.
9621        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9622        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9623        if (!deps.isEmpty()) {
9624            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9625                    options.getCompilerFilter(), options.getSplitName(),
9626                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9627            for (PackageParser.Package depPackage : deps) {
9628                // TODO: Analyze and investigate if we (should) profile libraries.
9629                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9630                        getOrCreateCompilerPackageStats(depPackage),
9631                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9632            }
9633        }
9634        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9635                getOrCreateCompilerPackageStats(p),
9636                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9637    }
9638
9639    /**
9640     * Reconcile the information we have about the secondary dex files belonging to
9641     * {@code packagName} and the actual dex files. For all dex files that were
9642     * deleted, update the internal records and delete the generated oat files.
9643     */
9644    @Override
9645    public void reconcileSecondaryDexFiles(String packageName) {
9646        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9647            return;
9648        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9649            return;
9650        }
9651        mDexManager.reconcileSecondaryDexFiles(packageName);
9652    }
9653
9654    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9655    // a reference there.
9656    /*package*/ DexManager getDexManager() {
9657        return mDexManager;
9658    }
9659
9660    /**
9661     * Execute the background dexopt job immediately.
9662     */
9663    @Override
9664    public boolean runBackgroundDexoptJob() {
9665        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9666            return false;
9667        }
9668        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9669    }
9670
9671    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9672        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9673                || p.usesStaticLibraries != null) {
9674            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9675            Set<String> collectedNames = new HashSet<>();
9676            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9677
9678            retValue.remove(p);
9679
9680            return retValue;
9681        } else {
9682            return Collections.emptyList();
9683        }
9684    }
9685
9686    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9687            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9688        if (!collectedNames.contains(p.packageName)) {
9689            collectedNames.add(p.packageName);
9690            collected.add(p);
9691
9692            if (p.usesLibraries != null) {
9693                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9694                        null, collected, collectedNames);
9695            }
9696            if (p.usesOptionalLibraries != null) {
9697                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9698                        null, collected, collectedNames);
9699            }
9700            if (p.usesStaticLibraries != null) {
9701                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9702                        p.usesStaticLibrariesVersions, collected, collectedNames);
9703            }
9704        }
9705    }
9706
9707    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9708            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9709        final int libNameCount = libs.size();
9710        for (int i = 0; i < libNameCount; i++) {
9711            String libName = libs.get(i);
9712            int version = (versions != null && versions.length == libNameCount)
9713                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9714            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9715            if (libPkg != null) {
9716                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9717            }
9718        }
9719    }
9720
9721    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9722        synchronized (mPackages) {
9723            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9724            if (libEntry != null) {
9725                return mPackages.get(libEntry.apk);
9726            }
9727            return null;
9728        }
9729    }
9730
9731    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9732        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9733        if (versionedLib == null) {
9734            return null;
9735        }
9736        return versionedLib.get(version);
9737    }
9738
9739    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9740        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9741                pkg.staticSharedLibName);
9742        if (versionedLib == null) {
9743            return null;
9744        }
9745        int previousLibVersion = -1;
9746        final int versionCount = versionedLib.size();
9747        for (int i = 0; i < versionCount; i++) {
9748            final int libVersion = versionedLib.keyAt(i);
9749            if (libVersion < pkg.staticSharedLibVersion) {
9750                previousLibVersion = Math.max(previousLibVersion, libVersion);
9751            }
9752        }
9753        if (previousLibVersion >= 0) {
9754            return versionedLib.get(previousLibVersion);
9755        }
9756        return null;
9757    }
9758
9759    public void shutdown() {
9760        mPackageUsage.writeNow(mPackages);
9761        mCompilerStats.writeNow();
9762        mDexManager.writePackageDexUsageNow();
9763    }
9764
9765    @Override
9766    public void dumpProfiles(String packageName) {
9767        PackageParser.Package pkg;
9768        synchronized (mPackages) {
9769            pkg = mPackages.get(packageName);
9770            if (pkg == null) {
9771                throw new IllegalArgumentException("Unknown package: " + packageName);
9772            }
9773        }
9774        /* Only the shell, root, or the app user should be able to dump profiles. */
9775        int callingUid = Binder.getCallingUid();
9776        if (callingUid != Process.SHELL_UID &&
9777            callingUid != Process.ROOT_UID &&
9778            callingUid != pkg.applicationInfo.uid) {
9779            throw new SecurityException("dumpProfiles");
9780        }
9781
9782        synchronized (mInstallLock) {
9783            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9784            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9785            try {
9786                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9787                String codePaths = TextUtils.join(";", allCodePaths);
9788                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9789            } catch (InstallerException e) {
9790                Slog.w(TAG, "Failed to dump profiles", e);
9791            }
9792            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9793        }
9794    }
9795
9796    @Override
9797    public void forceDexOpt(String packageName) {
9798        enforceSystemOrRoot("forceDexOpt");
9799
9800        PackageParser.Package pkg;
9801        synchronized (mPackages) {
9802            pkg = mPackages.get(packageName);
9803            if (pkg == null) {
9804                throw new IllegalArgumentException("Unknown package: " + packageName);
9805            }
9806        }
9807
9808        synchronized (mInstallLock) {
9809            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9810
9811            // Whoever is calling forceDexOpt wants a compiled package.
9812            // Don't use profiles since that may cause compilation to be skipped.
9813            final int res = performDexOptInternalWithDependenciesLI(
9814                    pkg,
9815                    new DexoptOptions(packageName,
9816                            getDefaultCompilerFilter(),
9817                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9818
9819            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9820            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9821                throw new IllegalStateException("Failed to dexopt: " + res);
9822            }
9823        }
9824    }
9825
9826    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9827        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9828            Slog.w(TAG, "Unable to update from " + oldPkg.name
9829                    + " to " + newPkg.packageName
9830                    + ": old package not in system partition");
9831            return false;
9832        } else if (mPackages.get(oldPkg.name) != null) {
9833            Slog.w(TAG, "Unable to update from " + oldPkg.name
9834                    + " to " + newPkg.packageName
9835                    + ": old package still exists");
9836            return false;
9837        }
9838        return true;
9839    }
9840
9841    void removeCodePathLI(File codePath) {
9842        if (codePath.isDirectory()) {
9843            try {
9844                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9845            } catch (InstallerException e) {
9846                Slog.w(TAG, "Failed to remove code path", e);
9847            }
9848        } else {
9849            codePath.delete();
9850        }
9851    }
9852
9853    private int[] resolveUserIds(int userId) {
9854        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9855    }
9856
9857    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9858        if (pkg == null) {
9859            Slog.wtf(TAG, "Package was null!", new Throwable());
9860            return;
9861        }
9862        clearAppDataLeafLIF(pkg, userId, flags);
9863        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9864        for (int i = 0; i < childCount; i++) {
9865            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9866        }
9867    }
9868
9869    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9870        final PackageSetting ps;
9871        synchronized (mPackages) {
9872            ps = mSettings.mPackages.get(pkg.packageName);
9873        }
9874        for (int realUserId : resolveUserIds(userId)) {
9875            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9876            try {
9877                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9878                        ceDataInode);
9879            } catch (InstallerException e) {
9880                Slog.w(TAG, String.valueOf(e));
9881            }
9882        }
9883    }
9884
9885    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9886        if (pkg == null) {
9887            Slog.wtf(TAG, "Package was null!", new Throwable());
9888            return;
9889        }
9890        destroyAppDataLeafLIF(pkg, userId, flags);
9891        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9892        for (int i = 0; i < childCount; i++) {
9893            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9894        }
9895    }
9896
9897    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9898        final PackageSetting ps;
9899        synchronized (mPackages) {
9900            ps = mSettings.mPackages.get(pkg.packageName);
9901        }
9902        for (int realUserId : resolveUserIds(userId)) {
9903            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9904            try {
9905                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9906                        ceDataInode);
9907            } catch (InstallerException e) {
9908                Slog.w(TAG, String.valueOf(e));
9909            }
9910            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9911        }
9912    }
9913
9914    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9915        if (pkg == null) {
9916            Slog.wtf(TAG, "Package was null!", new Throwable());
9917            return;
9918        }
9919        destroyAppProfilesLeafLIF(pkg);
9920        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9921        for (int i = 0; i < childCount; i++) {
9922            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9923        }
9924    }
9925
9926    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9927        try {
9928            mInstaller.destroyAppProfiles(pkg.packageName);
9929        } catch (InstallerException e) {
9930            Slog.w(TAG, String.valueOf(e));
9931        }
9932    }
9933
9934    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9935        if (pkg == null) {
9936            Slog.wtf(TAG, "Package was null!", new Throwable());
9937            return;
9938        }
9939        clearAppProfilesLeafLIF(pkg);
9940        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9941        for (int i = 0; i < childCount; i++) {
9942            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9943        }
9944    }
9945
9946    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9947        try {
9948            mInstaller.clearAppProfiles(pkg.packageName);
9949        } catch (InstallerException e) {
9950            Slog.w(TAG, String.valueOf(e));
9951        }
9952    }
9953
9954    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9955            long lastUpdateTime) {
9956        // Set parent install/update time
9957        PackageSetting ps = (PackageSetting) pkg.mExtras;
9958        if (ps != null) {
9959            ps.firstInstallTime = firstInstallTime;
9960            ps.lastUpdateTime = lastUpdateTime;
9961        }
9962        // Set children install/update time
9963        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9964        for (int i = 0; i < childCount; i++) {
9965            PackageParser.Package childPkg = pkg.childPackages.get(i);
9966            ps = (PackageSetting) childPkg.mExtras;
9967            if (ps != null) {
9968                ps.firstInstallTime = firstInstallTime;
9969                ps.lastUpdateTime = lastUpdateTime;
9970            }
9971        }
9972    }
9973
9974    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9975            SharedLibraryEntry file,
9976            PackageParser.Package changingLib) {
9977        if (file.path != null) {
9978            usesLibraryFiles.add(file.path);
9979            return;
9980        }
9981        PackageParser.Package p = mPackages.get(file.apk);
9982        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9983            // If we are doing this while in the middle of updating a library apk,
9984            // then we need to make sure to use that new apk for determining the
9985            // dependencies here.  (We haven't yet finished committing the new apk
9986            // to the package manager state.)
9987            if (p == null || p.packageName.equals(changingLib.packageName)) {
9988                p = changingLib;
9989            }
9990        }
9991        if (p != null) {
9992            usesLibraryFiles.addAll(p.getAllCodePaths());
9993            if (p.usesLibraryFiles != null) {
9994                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9995            }
9996        }
9997    }
9998
9999    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10000            PackageParser.Package changingLib) throws PackageManagerException {
10001        if (pkg == null) {
10002            return;
10003        }
10004        // The collection used here must maintain the order of addition (so
10005        // that libraries are searched in the correct order) and must have no
10006        // duplicates.
10007        Set<String> usesLibraryFiles = null;
10008        if (pkg.usesLibraries != null) {
10009            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10010                    null, null, pkg.packageName, changingLib, true, null);
10011        }
10012        if (pkg.usesStaticLibraries != null) {
10013            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10014                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10015                    pkg.packageName, changingLib, true, usesLibraryFiles);
10016        }
10017        if (pkg.usesOptionalLibraries != null) {
10018            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10019                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10020        }
10021        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10022            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10023        } else {
10024            pkg.usesLibraryFiles = null;
10025        }
10026    }
10027
10028    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10029            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10030            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10031            boolean required, @Nullable Set<String> outUsedLibraries)
10032            throws PackageManagerException {
10033        final int libCount = requestedLibraries.size();
10034        for (int i = 0; i < libCount; i++) {
10035            final String libName = requestedLibraries.get(i);
10036            final int libVersion = requiredVersions != null ? requiredVersions[i]
10037                    : SharedLibraryInfo.VERSION_UNDEFINED;
10038            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10039            if (libEntry == null) {
10040                if (required) {
10041                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10042                            "Package " + packageName + " requires unavailable shared library "
10043                                    + libName + "; failing!");
10044                } else if (DEBUG_SHARED_LIBRARIES) {
10045                    Slog.i(TAG, "Package " + packageName
10046                            + " desires unavailable shared library "
10047                            + libName + "; ignoring!");
10048                }
10049            } else {
10050                if (requiredVersions != null && requiredCertDigests != null) {
10051                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10052                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10053                            "Package " + packageName + " requires unavailable static shared"
10054                                    + " library " + libName + " version "
10055                                    + libEntry.info.getVersion() + "; failing!");
10056                    }
10057
10058                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10059                    if (libPkg == null) {
10060                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10061                                "Package " + packageName + " requires unavailable static shared"
10062                                        + " library; failing!");
10063                    }
10064
10065                    String expectedCertDigest = requiredCertDigests[i];
10066                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10067                                libPkg.mSignatures[0]);
10068                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10069                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10070                                "Package " + packageName + " requires differently signed" +
10071                                        " static shared library; failing!");
10072                    }
10073                }
10074
10075                if (outUsedLibraries == null) {
10076                    // Use LinkedHashSet to preserve the order of files added to
10077                    // usesLibraryFiles while eliminating duplicates.
10078                    outUsedLibraries = new LinkedHashSet<>();
10079                }
10080                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10081            }
10082        }
10083        return outUsedLibraries;
10084    }
10085
10086    private static boolean hasString(List<String> list, List<String> which) {
10087        if (list == null) {
10088            return false;
10089        }
10090        for (int i=list.size()-1; i>=0; i--) {
10091            for (int j=which.size()-1; j>=0; j--) {
10092                if (which.get(j).equals(list.get(i))) {
10093                    return true;
10094                }
10095            }
10096        }
10097        return false;
10098    }
10099
10100    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10101            PackageParser.Package changingPkg) {
10102        ArrayList<PackageParser.Package> res = null;
10103        for (PackageParser.Package pkg : mPackages.values()) {
10104            if (changingPkg != null
10105                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10106                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10107                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10108                            changingPkg.staticSharedLibName)) {
10109                return null;
10110            }
10111            if (res == null) {
10112                res = new ArrayList<>();
10113            }
10114            res.add(pkg);
10115            try {
10116                updateSharedLibrariesLPr(pkg, changingPkg);
10117            } catch (PackageManagerException e) {
10118                // If a system app update or an app and a required lib missing we
10119                // delete the package and for updated system apps keep the data as
10120                // it is better for the user to reinstall than to be in an limbo
10121                // state. Also libs disappearing under an app should never happen
10122                // - just in case.
10123                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10124                    final int flags = pkg.isUpdatedSystemApp()
10125                            ? PackageManager.DELETE_KEEP_DATA : 0;
10126                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10127                            flags , null, true, null);
10128                }
10129                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10130            }
10131        }
10132        return res;
10133    }
10134
10135    /**
10136     * Derive the value of the {@code cpuAbiOverride} based on the provided
10137     * value and an optional stored value from the package settings.
10138     */
10139    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10140        String cpuAbiOverride = null;
10141
10142        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10143            cpuAbiOverride = null;
10144        } else if (abiOverride != null) {
10145            cpuAbiOverride = abiOverride;
10146        } else if (settings != null) {
10147            cpuAbiOverride = settings.cpuAbiOverrideString;
10148        }
10149
10150        return cpuAbiOverride;
10151    }
10152
10153    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10154            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10155                    throws PackageManagerException {
10156        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10157        // If the package has children and this is the first dive in the function
10158        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10159        // whether all packages (parent and children) would be successfully scanned
10160        // before the actual scan since scanning mutates internal state and we want
10161        // to atomically install the package and its children.
10162        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10163            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10164                scanFlags |= SCAN_CHECK_ONLY;
10165            }
10166        } else {
10167            scanFlags &= ~SCAN_CHECK_ONLY;
10168        }
10169
10170        final PackageParser.Package scannedPkg;
10171        try {
10172            // Scan the parent
10173            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10174            // Scan the children
10175            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10176            for (int i = 0; i < childCount; i++) {
10177                PackageParser.Package childPkg = pkg.childPackages.get(i);
10178                scanPackageLI(childPkg, policyFlags,
10179                        scanFlags, currentTime, user);
10180            }
10181        } finally {
10182            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10183        }
10184
10185        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10186            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10187        }
10188
10189        return scannedPkg;
10190    }
10191
10192    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10193            int scanFlags, long currentTime, @Nullable UserHandle user)
10194                    throws PackageManagerException {
10195        boolean success = false;
10196        try {
10197            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10198                    currentTime, user);
10199            success = true;
10200            return res;
10201        } finally {
10202            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10203                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10204                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10205                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10206                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10207            }
10208        }
10209    }
10210
10211    /**
10212     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10213     */
10214    private static boolean apkHasCode(String fileName) {
10215        StrictJarFile jarFile = null;
10216        try {
10217            jarFile = new StrictJarFile(fileName,
10218                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10219            return jarFile.findEntry("classes.dex") != null;
10220        } catch (IOException ignore) {
10221        } finally {
10222            try {
10223                if (jarFile != null) {
10224                    jarFile.close();
10225                }
10226            } catch (IOException ignore) {}
10227        }
10228        return false;
10229    }
10230
10231    /**
10232     * Enforces code policy for the package. This ensures that if an APK has
10233     * declared hasCode="true" in its manifest that the APK actually contains
10234     * code.
10235     *
10236     * @throws PackageManagerException If bytecode could not be found when it should exist
10237     */
10238    private static void assertCodePolicy(PackageParser.Package pkg)
10239            throws PackageManagerException {
10240        final boolean shouldHaveCode =
10241                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10242        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10243            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10244                    "Package " + pkg.baseCodePath + " code is missing");
10245        }
10246
10247        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10248            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10249                final boolean splitShouldHaveCode =
10250                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10251                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10252                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10253                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10254                }
10255            }
10256        }
10257    }
10258
10259    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10260            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10261                    throws PackageManagerException {
10262        if (DEBUG_PACKAGE_SCANNING) {
10263            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10264                Log.d(TAG, "Scanning package " + pkg.packageName);
10265        }
10266
10267        applyPolicy(pkg, policyFlags);
10268
10269        assertPackageIsValid(pkg, policyFlags, scanFlags);
10270
10271        if (Build.IS_DEBUGGABLE &&
10272                pkg.isPrivilegedApp() &&
10273                SystemProperties.getBoolean("pm.dexopt.priv-apps-oob", false)) {
10274            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10275        }
10276
10277        // Initialize package source and resource directories
10278        final File scanFile = new File(pkg.codePath);
10279        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10280        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10281
10282        SharedUserSetting suid = null;
10283        PackageSetting pkgSetting = null;
10284
10285        // Getting the package setting may have a side-effect, so if we
10286        // are only checking if scan would succeed, stash a copy of the
10287        // old setting to restore at the end.
10288        PackageSetting nonMutatedPs = null;
10289
10290        // We keep references to the derived CPU Abis from settings in oder to reuse
10291        // them in the case where we're not upgrading or booting for the first time.
10292        String primaryCpuAbiFromSettings = null;
10293        String secondaryCpuAbiFromSettings = null;
10294
10295        // writer
10296        synchronized (mPackages) {
10297            if (pkg.mSharedUserId != null) {
10298                // SIDE EFFECTS; may potentially allocate a new shared user
10299                suid = mSettings.getSharedUserLPw(
10300                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10301                if (DEBUG_PACKAGE_SCANNING) {
10302                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10303                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10304                                + "): packages=" + suid.packages);
10305                }
10306            }
10307
10308            // Check if we are renaming from an original package name.
10309            PackageSetting origPackage = null;
10310            String realName = null;
10311            if (pkg.mOriginalPackages != null) {
10312                // This package may need to be renamed to a previously
10313                // installed name.  Let's check on that...
10314                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10315                if (pkg.mOriginalPackages.contains(renamed)) {
10316                    // This package had originally been installed as the
10317                    // original name, and we have already taken care of
10318                    // transitioning to the new one.  Just update the new
10319                    // one to continue using the old name.
10320                    realName = pkg.mRealPackage;
10321                    if (!pkg.packageName.equals(renamed)) {
10322                        // Callers into this function may have already taken
10323                        // care of renaming the package; only do it here if
10324                        // it is not already done.
10325                        pkg.setPackageName(renamed);
10326                    }
10327                } else {
10328                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10329                        if ((origPackage = mSettings.getPackageLPr(
10330                                pkg.mOriginalPackages.get(i))) != null) {
10331                            // We do have the package already installed under its
10332                            // original name...  should we use it?
10333                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10334                                // New package is not compatible with original.
10335                                origPackage = null;
10336                                continue;
10337                            } else if (origPackage.sharedUser != null) {
10338                                // Make sure uid is compatible between packages.
10339                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10340                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10341                                            + " to " + pkg.packageName + ": old uid "
10342                                            + origPackage.sharedUser.name
10343                                            + " differs from " + pkg.mSharedUserId);
10344                                    origPackage = null;
10345                                    continue;
10346                                }
10347                                // TODO: Add case when shared user id is added [b/28144775]
10348                            } else {
10349                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10350                                        + pkg.packageName + " to old name " + origPackage.name);
10351                            }
10352                            break;
10353                        }
10354                    }
10355                }
10356            }
10357
10358            if (mTransferedPackages.contains(pkg.packageName)) {
10359                Slog.w(TAG, "Package " + pkg.packageName
10360                        + " was transferred to another, but its .apk remains");
10361            }
10362
10363            // See comments in nonMutatedPs declaration
10364            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10365                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10366                if (foundPs != null) {
10367                    nonMutatedPs = new PackageSetting(foundPs);
10368                }
10369            }
10370
10371            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10372                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10373                if (foundPs != null) {
10374                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10375                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10376                }
10377            }
10378
10379            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10380            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10381                PackageManagerService.reportSettingsProblem(Log.WARN,
10382                        "Package " + pkg.packageName + " shared user changed from "
10383                                + (pkgSetting.sharedUser != null
10384                                        ? pkgSetting.sharedUser.name : "<nothing>")
10385                                + " to "
10386                                + (suid != null ? suid.name : "<nothing>")
10387                                + "; replacing with new");
10388                pkgSetting = null;
10389            }
10390            final PackageSetting oldPkgSetting =
10391                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10392            final PackageSetting disabledPkgSetting =
10393                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10394
10395            String[] usesStaticLibraries = null;
10396            if (pkg.usesStaticLibraries != null) {
10397                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10398                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10399            }
10400
10401            if (pkgSetting == null) {
10402                final String parentPackageName = (pkg.parentPackage != null)
10403                        ? pkg.parentPackage.packageName : null;
10404                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10405                // REMOVE SharedUserSetting from method; update in a separate call
10406                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10407                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10408                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10409                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10410                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10411                        true /*allowInstall*/, instantApp, parentPackageName,
10412                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10413                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10414                // SIDE EFFECTS; updates system state; move elsewhere
10415                if (origPackage != null) {
10416                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10417                }
10418                mSettings.addUserToSettingLPw(pkgSetting);
10419            } else {
10420                // REMOVE SharedUserSetting from method; update in a separate call.
10421                //
10422                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10423                // secondaryCpuAbi are not known at this point so we always update them
10424                // to null here, only to reset them at a later point.
10425                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10426                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10427                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10428                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10429                        UserManagerService.getInstance(), usesStaticLibraries,
10430                        pkg.usesStaticLibrariesVersions);
10431            }
10432            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10433            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10434
10435            // SIDE EFFECTS; modifies system state; move elsewhere
10436            if (pkgSetting.origPackage != null) {
10437                // If we are first transitioning from an original package,
10438                // fix up the new package's name now.  We need to do this after
10439                // looking up the package under its new name, so getPackageLP
10440                // can take care of fiddling things correctly.
10441                pkg.setPackageName(origPackage.name);
10442
10443                // File a report about this.
10444                String msg = "New package " + pkgSetting.realName
10445                        + " renamed to replace old package " + pkgSetting.name;
10446                reportSettingsProblem(Log.WARN, msg);
10447
10448                // Make a note of it.
10449                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10450                    mTransferedPackages.add(origPackage.name);
10451                }
10452
10453                // No longer need to retain this.
10454                pkgSetting.origPackage = null;
10455            }
10456
10457            // SIDE EFFECTS; modifies system state; move elsewhere
10458            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10459                // Make a note of it.
10460                mTransferedPackages.add(pkg.packageName);
10461            }
10462
10463            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10464                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10465            }
10466
10467            if ((scanFlags & SCAN_BOOTING) == 0
10468                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10469                // Check all shared libraries and map to their actual file path.
10470                // We only do this here for apps not on a system dir, because those
10471                // are the only ones that can fail an install due to this.  We
10472                // will take care of the system apps by updating all of their
10473                // library paths after the scan is done. Also during the initial
10474                // scan don't update any libs as we do this wholesale after all
10475                // apps are scanned to avoid dependency based scanning.
10476                updateSharedLibrariesLPr(pkg, null);
10477            }
10478
10479            if (mFoundPolicyFile) {
10480                SELinuxMMAC.assignSeInfoValue(pkg);
10481            }
10482            pkg.applicationInfo.uid = pkgSetting.appId;
10483            pkg.mExtras = pkgSetting;
10484
10485
10486            // Static shared libs have same package with different versions where
10487            // we internally use a synthetic package name to allow multiple versions
10488            // of the same package, therefore we need to compare signatures against
10489            // the package setting for the latest library version.
10490            PackageSetting signatureCheckPs = pkgSetting;
10491            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10492                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10493                if (libraryEntry != null) {
10494                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10495                }
10496            }
10497
10498            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10499                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10500                    // We just determined the app is signed correctly, so bring
10501                    // over the latest parsed certs.
10502                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10503                } else {
10504                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10505                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10506                                "Package " + pkg.packageName + " upgrade keys do not match the "
10507                                + "previously installed version");
10508                    } else {
10509                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10510                        String msg = "System package " + pkg.packageName
10511                                + " signature changed; retaining data.";
10512                        reportSettingsProblem(Log.WARN, msg);
10513                    }
10514                }
10515            } else {
10516                try {
10517                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10518                    verifySignaturesLP(signatureCheckPs, pkg);
10519                    // We just determined the app is signed correctly, so bring
10520                    // over the latest parsed certs.
10521                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10522                } catch (PackageManagerException e) {
10523                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10524                        throw e;
10525                    }
10526                    // The signature has changed, but this package is in the system
10527                    // image...  let's recover!
10528                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10529                    // However...  if this package is part of a shared user, but it
10530                    // doesn't match the signature of the shared user, let's fail.
10531                    // What this means is that you can't change the signatures
10532                    // associated with an overall shared user, which doesn't seem all
10533                    // that unreasonable.
10534                    if (signatureCheckPs.sharedUser != null) {
10535                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10536                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10537                            throw new PackageManagerException(
10538                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10539                                    "Signature mismatch for shared user: "
10540                                            + pkgSetting.sharedUser);
10541                        }
10542                    }
10543                    // File a report about this.
10544                    String msg = "System package " + pkg.packageName
10545                            + " signature changed; retaining data.";
10546                    reportSettingsProblem(Log.WARN, msg);
10547                }
10548            }
10549
10550            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10551                // This package wants to adopt ownership of permissions from
10552                // another package.
10553                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10554                    final String origName = pkg.mAdoptPermissions.get(i);
10555                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10556                    if (orig != null) {
10557                        if (verifyPackageUpdateLPr(orig, pkg)) {
10558                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10559                                    + pkg.packageName);
10560                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10561                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10562                        }
10563                    }
10564                }
10565            }
10566        }
10567
10568        pkg.applicationInfo.processName = fixProcessName(
10569                pkg.applicationInfo.packageName,
10570                pkg.applicationInfo.processName);
10571
10572        if (pkg != mPlatformPackage) {
10573            // Get all of our default paths setup
10574            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10575        }
10576
10577        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10578
10579        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10580            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10581                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10582                final boolean extractNativeLibs = !pkg.isLibrary();
10583                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10584                        mAppLib32InstallDir);
10585                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10586
10587                // Some system apps still use directory structure for native libraries
10588                // in which case we might end up not detecting abi solely based on apk
10589                // structure. Try to detect abi based on directory structure.
10590                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10591                        pkg.applicationInfo.primaryCpuAbi == null) {
10592                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10593                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10594                }
10595            } else {
10596                // This is not a first boot or an upgrade, don't bother deriving the
10597                // ABI during the scan. Instead, trust the value that was stored in the
10598                // package setting.
10599                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10600                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10601
10602                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10603
10604                if (DEBUG_ABI_SELECTION) {
10605                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10606                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10607                        pkg.applicationInfo.secondaryCpuAbi);
10608                }
10609            }
10610        } else {
10611            if ((scanFlags & SCAN_MOVE) != 0) {
10612                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10613                // but we already have this packages package info in the PackageSetting. We just
10614                // use that and derive the native library path based on the new codepath.
10615                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10616                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10617            }
10618
10619            // Set native library paths again. For moves, the path will be updated based on the
10620            // ABIs we've determined above. For non-moves, the path will be updated based on the
10621            // ABIs we determined during compilation, but the path will depend on the final
10622            // package path (after the rename away from the stage path).
10623            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10624        }
10625
10626        // This is a special case for the "system" package, where the ABI is
10627        // dictated by the zygote configuration (and init.rc). We should keep track
10628        // of this ABI so that we can deal with "normal" applications that run under
10629        // the same UID correctly.
10630        if (mPlatformPackage == pkg) {
10631            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10632                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10633        }
10634
10635        // If there's a mismatch between the abi-override in the package setting
10636        // and the abiOverride specified for the install. Warn about this because we
10637        // would've already compiled the app without taking the package setting into
10638        // account.
10639        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10640            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10641                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10642                        " for package " + pkg.packageName);
10643            }
10644        }
10645
10646        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10647        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10648        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10649
10650        // Copy the derived override back to the parsed package, so that we can
10651        // update the package settings accordingly.
10652        pkg.cpuAbiOverride = cpuAbiOverride;
10653
10654        if (DEBUG_ABI_SELECTION) {
10655            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10656                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10657                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10658        }
10659
10660        // Push the derived path down into PackageSettings so we know what to
10661        // clean up at uninstall time.
10662        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10663
10664        if (DEBUG_ABI_SELECTION) {
10665            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10666                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10667                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10668        }
10669
10670        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10671        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10672            // We don't do this here during boot because we can do it all
10673            // at once after scanning all existing packages.
10674            //
10675            // We also do this *before* we perform dexopt on this package, so that
10676            // we can avoid redundant dexopts, and also to make sure we've got the
10677            // code and package path correct.
10678            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10679        }
10680
10681        if (mFactoryTest && pkg.requestedPermissions.contains(
10682                android.Manifest.permission.FACTORY_TEST)) {
10683            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10684        }
10685
10686        if (isSystemApp(pkg)) {
10687            pkgSetting.isOrphaned = true;
10688        }
10689
10690        // Take care of first install / last update times.
10691        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10692        if (currentTime != 0) {
10693            if (pkgSetting.firstInstallTime == 0) {
10694                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10695            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10696                pkgSetting.lastUpdateTime = currentTime;
10697            }
10698        } else if (pkgSetting.firstInstallTime == 0) {
10699            // We need *something*.  Take time time stamp of the file.
10700            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10701        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10702            if (scanFileTime != pkgSetting.timeStamp) {
10703                // A package on the system image has changed; consider this
10704                // to be an update.
10705                pkgSetting.lastUpdateTime = scanFileTime;
10706            }
10707        }
10708        pkgSetting.setTimeStamp(scanFileTime);
10709
10710        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10711            if (nonMutatedPs != null) {
10712                synchronized (mPackages) {
10713                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10714                }
10715            }
10716        } else {
10717            final int userId = user == null ? 0 : user.getIdentifier();
10718            // Modify state for the given package setting
10719            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10720                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10721            if (pkgSetting.getInstantApp(userId)) {
10722                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10723            }
10724        }
10725        return pkg;
10726    }
10727
10728    /**
10729     * Applies policy to the parsed package based upon the given policy flags.
10730     * Ensures the package is in a good state.
10731     * <p>
10732     * Implementation detail: This method must NOT have any side effect. It would
10733     * ideally be static, but, it requires locks to read system state.
10734     */
10735    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10736        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10737            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10738            if (pkg.applicationInfo.isDirectBootAware()) {
10739                // we're direct boot aware; set for all components
10740                for (PackageParser.Service s : pkg.services) {
10741                    s.info.encryptionAware = s.info.directBootAware = true;
10742                }
10743                for (PackageParser.Provider p : pkg.providers) {
10744                    p.info.encryptionAware = p.info.directBootAware = true;
10745                }
10746                for (PackageParser.Activity a : pkg.activities) {
10747                    a.info.encryptionAware = a.info.directBootAware = true;
10748                }
10749                for (PackageParser.Activity r : pkg.receivers) {
10750                    r.info.encryptionAware = r.info.directBootAware = true;
10751                }
10752            }
10753        } else {
10754            // Only allow system apps to be flagged as core apps.
10755            pkg.coreApp = false;
10756            // clear flags not applicable to regular apps
10757            pkg.applicationInfo.privateFlags &=
10758                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10759            pkg.applicationInfo.privateFlags &=
10760                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10761        }
10762        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10763
10764        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10765            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10766        }
10767
10768        if (!isSystemApp(pkg)) {
10769            // Only system apps can use these features.
10770            pkg.mOriginalPackages = null;
10771            pkg.mRealPackage = null;
10772            pkg.mAdoptPermissions = null;
10773        }
10774    }
10775
10776    /**
10777     * Asserts the parsed package is valid according to the given policy. If the
10778     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10779     * <p>
10780     * Implementation detail: This method must NOT have any side effects. It would
10781     * ideally be static, but, it requires locks to read system state.
10782     *
10783     * @throws PackageManagerException If the package fails any of the validation checks
10784     */
10785    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10786            throws PackageManagerException {
10787        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10788            assertCodePolicy(pkg);
10789        }
10790
10791        if (pkg.applicationInfo.getCodePath() == null ||
10792                pkg.applicationInfo.getResourcePath() == null) {
10793            // Bail out. The resource and code paths haven't been set.
10794            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10795                    "Code and resource paths haven't been set correctly");
10796        }
10797
10798        // Make sure we're not adding any bogus keyset info
10799        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10800        ksms.assertScannedPackageValid(pkg);
10801
10802        synchronized (mPackages) {
10803            // The special "android" package can only be defined once
10804            if (pkg.packageName.equals("android")) {
10805                if (mAndroidApplication != null) {
10806                    Slog.w(TAG, "*************************************************");
10807                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10808                    Slog.w(TAG, " codePath=" + pkg.codePath);
10809                    Slog.w(TAG, "*************************************************");
10810                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10811                            "Core android package being redefined.  Skipping.");
10812                }
10813            }
10814
10815            // A package name must be unique; don't allow duplicates
10816            if (mPackages.containsKey(pkg.packageName)) {
10817                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10818                        "Application package " + pkg.packageName
10819                        + " already installed.  Skipping duplicate.");
10820            }
10821
10822            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10823                // Static libs have a synthetic package name containing the version
10824                // but we still want the base name to be unique.
10825                if (mPackages.containsKey(pkg.manifestPackageName)) {
10826                    throw new PackageManagerException(
10827                            "Duplicate static shared lib provider package");
10828                }
10829
10830                // Static shared libraries should have at least O target SDK
10831                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10832                    throw new PackageManagerException(
10833                            "Packages declaring static-shared libs must target O SDK or higher");
10834                }
10835
10836                // Package declaring static a shared lib cannot be instant apps
10837                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10838                    throw new PackageManagerException(
10839                            "Packages declaring static-shared libs cannot be instant apps");
10840                }
10841
10842                // Package declaring static a shared lib cannot be renamed since the package
10843                // name is synthetic and apps can't code around package manager internals.
10844                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10845                    throw new PackageManagerException(
10846                            "Packages declaring static-shared libs cannot be renamed");
10847                }
10848
10849                // Package declaring static a shared lib cannot declare child packages
10850                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10851                    throw new PackageManagerException(
10852                            "Packages declaring static-shared libs cannot have child packages");
10853                }
10854
10855                // Package declaring static a shared lib cannot declare dynamic libs
10856                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10857                    throw new PackageManagerException(
10858                            "Packages declaring static-shared libs cannot declare dynamic libs");
10859                }
10860
10861                // Package declaring static a shared lib cannot declare shared users
10862                if (pkg.mSharedUserId != null) {
10863                    throw new PackageManagerException(
10864                            "Packages declaring static-shared libs cannot declare shared users");
10865                }
10866
10867                // Static shared libs cannot declare activities
10868                if (!pkg.activities.isEmpty()) {
10869                    throw new PackageManagerException(
10870                            "Static shared libs cannot declare activities");
10871                }
10872
10873                // Static shared libs cannot declare services
10874                if (!pkg.services.isEmpty()) {
10875                    throw new PackageManagerException(
10876                            "Static shared libs cannot declare services");
10877                }
10878
10879                // Static shared libs cannot declare providers
10880                if (!pkg.providers.isEmpty()) {
10881                    throw new PackageManagerException(
10882                            "Static shared libs cannot declare content providers");
10883                }
10884
10885                // Static shared libs cannot declare receivers
10886                if (!pkg.receivers.isEmpty()) {
10887                    throw new PackageManagerException(
10888                            "Static shared libs cannot declare broadcast receivers");
10889                }
10890
10891                // Static shared libs cannot declare permission groups
10892                if (!pkg.permissionGroups.isEmpty()) {
10893                    throw new PackageManagerException(
10894                            "Static shared libs cannot declare permission groups");
10895                }
10896
10897                // Static shared libs cannot declare permissions
10898                if (!pkg.permissions.isEmpty()) {
10899                    throw new PackageManagerException(
10900                            "Static shared libs cannot declare permissions");
10901                }
10902
10903                // Static shared libs cannot declare protected broadcasts
10904                if (pkg.protectedBroadcasts != null) {
10905                    throw new PackageManagerException(
10906                            "Static shared libs cannot declare protected broadcasts");
10907                }
10908
10909                // Static shared libs cannot be overlay targets
10910                if (pkg.mOverlayTarget != null) {
10911                    throw new PackageManagerException(
10912                            "Static shared libs cannot be overlay targets");
10913                }
10914
10915                // The version codes must be ordered as lib versions
10916                int minVersionCode = Integer.MIN_VALUE;
10917                int maxVersionCode = Integer.MAX_VALUE;
10918
10919                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10920                        pkg.staticSharedLibName);
10921                if (versionedLib != null) {
10922                    final int versionCount = versionedLib.size();
10923                    for (int i = 0; i < versionCount; i++) {
10924                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10925                        final int libVersionCode = libInfo.getDeclaringPackage()
10926                                .getVersionCode();
10927                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10928                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10929                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10930                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10931                        } else {
10932                            minVersionCode = maxVersionCode = libVersionCode;
10933                            break;
10934                        }
10935                    }
10936                }
10937                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10938                    throw new PackageManagerException("Static shared"
10939                            + " lib version codes must be ordered as lib versions");
10940                }
10941            }
10942
10943            // Only privileged apps and updated privileged apps can add child packages.
10944            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10945                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10946                    throw new PackageManagerException("Only privileged apps can add child "
10947                            + "packages. Ignoring package " + pkg.packageName);
10948                }
10949                final int childCount = pkg.childPackages.size();
10950                for (int i = 0; i < childCount; i++) {
10951                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10952                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10953                            childPkg.packageName)) {
10954                        throw new PackageManagerException("Can't override child of "
10955                                + "another disabled app. Ignoring package " + pkg.packageName);
10956                    }
10957                }
10958            }
10959
10960            // If we're only installing presumed-existing packages, require that the
10961            // scanned APK is both already known and at the path previously established
10962            // for it.  Previously unknown packages we pick up normally, but if we have an
10963            // a priori expectation about this package's install presence, enforce it.
10964            // With a singular exception for new system packages. When an OTA contains
10965            // a new system package, we allow the codepath to change from a system location
10966            // to the user-installed location. If we don't allow this change, any newer,
10967            // user-installed version of the application will be ignored.
10968            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10969                if (mExpectingBetter.containsKey(pkg.packageName)) {
10970                    logCriticalInfo(Log.WARN,
10971                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10972                } else {
10973                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10974                    if (known != null) {
10975                        if (DEBUG_PACKAGE_SCANNING) {
10976                            Log.d(TAG, "Examining " + pkg.codePath
10977                                    + " and requiring known paths " + known.codePathString
10978                                    + " & " + known.resourcePathString);
10979                        }
10980                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10981                                || !pkg.applicationInfo.getResourcePath().equals(
10982                                        known.resourcePathString)) {
10983                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10984                                    "Application package " + pkg.packageName
10985                                    + " found at " + pkg.applicationInfo.getCodePath()
10986                                    + " but expected at " + known.codePathString
10987                                    + "; ignoring.");
10988                        }
10989                    }
10990                }
10991            }
10992
10993            // Verify that this new package doesn't have any content providers
10994            // that conflict with existing packages.  Only do this if the
10995            // package isn't already installed, since we don't want to break
10996            // things that are installed.
10997            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10998                final int N = pkg.providers.size();
10999                int i;
11000                for (i=0; i<N; i++) {
11001                    PackageParser.Provider p = pkg.providers.get(i);
11002                    if (p.info.authority != null) {
11003                        String names[] = p.info.authority.split(";");
11004                        for (int j = 0; j < names.length; j++) {
11005                            if (mProvidersByAuthority.containsKey(names[j])) {
11006                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11007                                final String otherPackageName =
11008                                        ((other != null && other.getComponentName() != null) ?
11009                                                other.getComponentName().getPackageName() : "?");
11010                                throw new PackageManagerException(
11011                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11012                                        "Can't install because provider name " + names[j]
11013                                                + " (in package " + pkg.applicationInfo.packageName
11014                                                + ") is already used by " + otherPackageName);
11015                            }
11016                        }
11017                    }
11018                }
11019            }
11020        }
11021    }
11022
11023    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11024            int type, String declaringPackageName, int declaringVersionCode) {
11025        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11026        if (versionedLib == null) {
11027            versionedLib = new SparseArray<>();
11028            mSharedLibraries.put(name, versionedLib);
11029            if (type == SharedLibraryInfo.TYPE_STATIC) {
11030                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11031            }
11032        } else if (versionedLib.indexOfKey(version) >= 0) {
11033            return false;
11034        }
11035        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11036                version, type, declaringPackageName, declaringVersionCode);
11037        versionedLib.put(version, libEntry);
11038        return true;
11039    }
11040
11041    private boolean removeSharedLibraryLPw(String name, int version) {
11042        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11043        if (versionedLib == null) {
11044            return false;
11045        }
11046        final int libIdx = versionedLib.indexOfKey(version);
11047        if (libIdx < 0) {
11048            return false;
11049        }
11050        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11051        versionedLib.remove(version);
11052        if (versionedLib.size() <= 0) {
11053            mSharedLibraries.remove(name);
11054            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11055                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11056                        .getPackageName());
11057            }
11058        }
11059        return true;
11060    }
11061
11062    /**
11063     * Adds a scanned package to the system. When this method is finished, the package will
11064     * be available for query, resolution, etc...
11065     */
11066    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11067            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11068        final String pkgName = pkg.packageName;
11069        if (mCustomResolverComponentName != null &&
11070                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11071            setUpCustomResolverActivity(pkg);
11072        }
11073
11074        if (pkg.packageName.equals("android")) {
11075            synchronized (mPackages) {
11076                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11077                    // Set up information for our fall-back user intent resolution activity.
11078                    mPlatformPackage = pkg;
11079                    pkg.mVersionCode = mSdkVersion;
11080                    mAndroidApplication = pkg.applicationInfo;
11081                    if (!mResolverReplaced) {
11082                        mResolveActivity.applicationInfo = mAndroidApplication;
11083                        mResolveActivity.name = ResolverActivity.class.getName();
11084                        mResolveActivity.packageName = mAndroidApplication.packageName;
11085                        mResolveActivity.processName = "system:ui";
11086                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11087                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11088                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11089                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11090                        mResolveActivity.exported = true;
11091                        mResolveActivity.enabled = true;
11092                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11093                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11094                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11095                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11096                                | ActivityInfo.CONFIG_ORIENTATION
11097                                | ActivityInfo.CONFIG_KEYBOARD
11098                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11099                        mResolveInfo.activityInfo = mResolveActivity;
11100                        mResolveInfo.priority = 0;
11101                        mResolveInfo.preferredOrder = 0;
11102                        mResolveInfo.match = 0;
11103                        mResolveComponentName = new ComponentName(
11104                                mAndroidApplication.packageName, mResolveActivity.name);
11105                    }
11106                }
11107            }
11108        }
11109
11110        ArrayList<PackageParser.Package> clientLibPkgs = null;
11111        // writer
11112        synchronized (mPackages) {
11113            boolean hasStaticSharedLibs = false;
11114
11115            // Any app can add new static shared libraries
11116            if (pkg.staticSharedLibName != null) {
11117                // Static shared libs don't allow renaming as they have synthetic package
11118                // names to allow install of multiple versions, so use name from manifest.
11119                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11120                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11121                        pkg.manifestPackageName, pkg.mVersionCode)) {
11122                    hasStaticSharedLibs = true;
11123                } else {
11124                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11125                                + pkg.staticSharedLibName + " already exists; skipping");
11126                }
11127                // Static shared libs cannot be updated once installed since they
11128                // use synthetic package name which includes the version code, so
11129                // not need to update other packages's shared lib dependencies.
11130            }
11131
11132            if (!hasStaticSharedLibs
11133                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11134                // Only system apps can add new dynamic shared libraries.
11135                if (pkg.libraryNames != null) {
11136                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11137                        String name = pkg.libraryNames.get(i);
11138                        boolean allowed = false;
11139                        if (pkg.isUpdatedSystemApp()) {
11140                            // New library entries can only be added through the
11141                            // system image.  This is important to get rid of a lot
11142                            // of nasty edge cases: for example if we allowed a non-
11143                            // system update of the app to add a library, then uninstalling
11144                            // the update would make the library go away, and assumptions
11145                            // we made such as through app install filtering would now
11146                            // have allowed apps on the device which aren't compatible
11147                            // with it.  Better to just have the restriction here, be
11148                            // conservative, and create many fewer cases that can negatively
11149                            // impact the user experience.
11150                            final PackageSetting sysPs = mSettings
11151                                    .getDisabledSystemPkgLPr(pkg.packageName);
11152                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11153                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11154                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11155                                        allowed = true;
11156                                        break;
11157                                    }
11158                                }
11159                            }
11160                        } else {
11161                            allowed = true;
11162                        }
11163                        if (allowed) {
11164                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11165                                    SharedLibraryInfo.VERSION_UNDEFINED,
11166                                    SharedLibraryInfo.TYPE_DYNAMIC,
11167                                    pkg.packageName, pkg.mVersionCode)) {
11168                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11169                                        + name + " already exists; skipping");
11170                            }
11171                        } else {
11172                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11173                                    + name + " that is not declared on system image; skipping");
11174                        }
11175                    }
11176
11177                    if ((scanFlags & SCAN_BOOTING) == 0) {
11178                        // If we are not booting, we need to update any applications
11179                        // that are clients of our shared library.  If we are booting,
11180                        // this will all be done once the scan is complete.
11181                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11182                    }
11183                }
11184            }
11185        }
11186
11187        if ((scanFlags & SCAN_BOOTING) != 0) {
11188            // No apps can run during boot scan, so they don't need to be frozen
11189        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11190            // Caller asked to not kill app, so it's probably not frozen
11191        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11192            // Caller asked us to ignore frozen check for some reason; they
11193            // probably didn't know the package name
11194        } else {
11195            // We're doing major surgery on this package, so it better be frozen
11196            // right now to keep it from launching
11197            checkPackageFrozen(pkgName);
11198        }
11199
11200        // Also need to kill any apps that are dependent on the library.
11201        if (clientLibPkgs != null) {
11202            for (int i=0; i<clientLibPkgs.size(); i++) {
11203                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11204                killApplication(clientPkg.applicationInfo.packageName,
11205                        clientPkg.applicationInfo.uid, "update lib");
11206            }
11207        }
11208
11209        // writer
11210        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11211
11212        synchronized (mPackages) {
11213            // We don't expect installation to fail beyond this point
11214
11215            // Add the new setting to mSettings
11216            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11217            // Add the new setting to mPackages
11218            mPackages.put(pkg.applicationInfo.packageName, pkg);
11219            // Make sure we don't accidentally delete its data.
11220            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11221            while (iter.hasNext()) {
11222                PackageCleanItem item = iter.next();
11223                if (pkgName.equals(item.packageName)) {
11224                    iter.remove();
11225                }
11226            }
11227
11228            // Add the package's KeySets to the global KeySetManagerService
11229            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11230            ksms.addScannedPackageLPw(pkg);
11231
11232            int N = pkg.providers.size();
11233            StringBuilder r = null;
11234            int i;
11235            for (i=0; i<N; i++) {
11236                PackageParser.Provider p = pkg.providers.get(i);
11237                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11238                        p.info.processName);
11239                mProviders.addProvider(p);
11240                p.syncable = p.info.isSyncable;
11241                if (p.info.authority != null) {
11242                    String names[] = p.info.authority.split(";");
11243                    p.info.authority = null;
11244                    for (int j = 0; j < names.length; j++) {
11245                        if (j == 1 && p.syncable) {
11246                            // We only want the first authority for a provider to possibly be
11247                            // syncable, so if we already added this provider using a different
11248                            // authority clear the syncable flag. We copy the provider before
11249                            // changing it because the mProviders object contains a reference
11250                            // to a provider that we don't want to change.
11251                            // Only do this for the second authority since the resulting provider
11252                            // object can be the same for all future authorities for this provider.
11253                            p = new PackageParser.Provider(p);
11254                            p.syncable = false;
11255                        }
11256                        if (!mProvidersByAuthority.containsKey(names[j])) {
11257                            mProvidersByAuthority.put(names[j], p);
11258                            if (p.info.authority == null) {
11259                                p.info.authority = names[j];
11260                            } else {
11261                                p.info.authority = p.info.authority + ";" + names[j];
11262                            }
11263                            if (DEBUG_PACKAGE_SCANNING) {
11264                                if (chatty)
11265                                    Log.d(TAG, "Registered content provider: " + names[j]
11266                                            + ", className = " + p.info.name + ", isSyncable = "
11267                                            + p.info.isSyncable);
11268                            }
11269                        } else {
11270                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11271                            Slog.w(TAG, "Skipping provider name " + names[j] +
11272                                    " (in package " + pkg.applicationInfo.packageName +
11273                                    "): name already used by "
11274                                    + ((other != null && other.getComponentName() != null)
11275                                            ? other.getComponentName().getPackageName() : "?"));
11276                        }
11277                    }
11278                }
11279                if (chatty) {
11280                    if (r == null) {
11281                        r = new StringBuilder(256);
11282                    } else {
11283                        r.append(' ');
11284                    }
11285                    r.append(p.info.name);
11286                }
11287            }
11288            if (r != null) {
11289                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11290            }
11291
11292            N = pkg.services.size();
11293            r = null;
11294            for (i=0; i<N; i++) {
11295                PackageParser.Service s = pkg.services.get(i);
11296                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11297                        s.info.processName);
11298                mServices.addService(s);
11299                if (chatty) {
11300                    if (r == null) {
11301                        r = new StringBuilder(256);
11302                    } else {
11303                        r.append(' ');
11304                    }
11305                    r.append(s.info.name);
11306                }
11307            }
11308            if (r != null) {
11309                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11310            }
11311
11312            N = pkg.receivers.size();
11313            r = null;
11314            for (i=0; i<N; i++) {
11315                PackageParser.Activity a = pkg.receivers.get(i);
11316                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11317                        a.info.processName);
11318                mReceivers.addActivity(a, "receiver");
11319                if (chatty) {
11320                    if (r == null) {
11321                        r = new StringBuilder(256);
11322                    } else {
11323                        r.append(' ');
11324                    }
11325                    r.append(a.info.name);
11326                }
11327            }
11328            if (r != null) {
11329                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11330            }
11331
11332            N = pkg.activities.size();
11333            r = null;
11334            for (i=0; i<N; i++) {
11335                PackageParser.Activity a = pkg.activities.get(i);
11336                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11337                        a.info.processName);
11338                mActivities.addActivity(a, "activity");
11339                if (chatty) {
11340                    if (r == null) {
11341                        r = new StringBuilder(256);
11342                    } else {
11343                        r.append(' ');
11344                    }
11345                    r.append(a.info.name);
11346                }
11347            }
11348            if (r != null) {
11349                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11350            }
11351
11352            N = pkg.permissionGroups.size();
11353            r = null;
11354            for (i=0; i<N; i++) {
11355                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11356                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11357                final String curPackageName = cur == null ? null : cur.info.packageName;
11358                // Dont allow ephemeral apps to define new permission groups.
11359                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11360                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11361                            + pg.info.packageName
11362                            + " ignored: instant apps cannot define new permission groups.");
11363                    continue;
11364                }
11365                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11366                if (cur == null || isPackageUpdate) {
11367                    mPermissionGroups.put(pg.info.name, pg);
11368                    if (chatty) {
11369                        if (r == null) {
11370                            r = new StringBuilder(256);
11371                        } else {
11372                            r.append(' ');
11373                        }
11374                        if (isPackageUpdate) {
11375                            r.append("UPD:");
11376                        }
11377                        r.append(pg.info.name);
11378                    }
11379                } else {
11380                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11381                            + pg.info.packageName + " ignored: original from "
11382                            + cur.info.packageName);
11383                    if (chatty) {
11384                        if (r == null) {
11385                            r = new StringBuilder(256);
11386                        } else {
11387                            r.append(' ');
11388                        }
11389                        r.append("DUP:");
11390                        r.append(pg.info.name);
11391                    }
11392                }
11393            }
11394            if (r != null) {
11395                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11396            }
11397
11398            N = pkg.permissions.size();
11399            r = null;
11400            for (i=0; i<N; i++) {
11401                PackageParser.Permission p = pkg.permissions.get(i);
11402
11403                // Dont allow ephemeral apps to define new permissions.
11404                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11405                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11406                            + p.info.packageName
11407                            + " ignored: instant apps cannot define new permissions.");
11408                    continue;
11409                }
11410
11411                // Assume by default that we did not install this permission into the system.
11412                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11413
11414                // Now that permission groups have a special meaning, we ignore permission
11415                // groups for legacy apps to prevent unexpected behavior. In particular,
11416                // permissions for one app being granted to someone just because they happen
11417                // to be in a group defined by another app (before this had no implications).
11418                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11419                    p.group = mPermissionGroups.get(p.info.group);
11420                    // Warn for a permission in an unknown group.
11421                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11422                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11423                                + p.info.packageName + " in an unknown group " + p.info.group);
11424                    }
11425                }
11426
11427                ArrayMap<String, BasePermission> permissionMap =
11428                        p.tree ? mSettings.mPermissionTrees
11429                                : mSettings.mPermissions;
11430                BasePermission bp = permissionMap.get(p.info.name);
11431
11432                // Allow system apps to redefine non-system permissions
11433                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11434                    final boolean currentOwnerIsSystem = (bp.perm != null
11435                            && isSystemApp(bp.perm.owner));
11436                    if (isSystemApp(p.owner)) {
11437                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11438                            // It's a built-in permission and no owner, take ownership now
11439                            bp.packageSetting = pkgSetting;
11440                            bp.perm = p;
11441                            bp.uid = pkg.applicationInfo.uid;
11442                            bp.sourcePackage = p.info.packageName;
11443                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11444                        } else if (!currentOwnerIsSystem) {
11445                            String msg = "New decl " + p.owner + " of permission  "
11446                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11447                            reportSettingsProblem(Log.WARN, msg);
11448                            bp = null;
11449                        }
11450                    }
11451                }
11452
11453                if (bp == null) {
11454                    bp = new BasePermission(p.info.name, p.info.packageName,
11455                            BasePermission.TYPE_NORMAL);
11456                    permissionMap.put(p.info.name, bp);
11457                }
11458
11459                if (bp.perm == null) {
11460                    if (bp.sourcePackage == null
11461                            || bp.sourcePackage.equals(p.info.packageName)) {
11462                        BasePermission tree = findPermissionTreeLP(p.info.name);
11463                        if (tree == null
11464                                || tree.sourcePackage.equals(p.info.packageName)) {
11465                            bp.packageSetting = pkgSetting;
11466                            bp.perm = p;
11467                            bp.uid = pkg.applicationInfo.uid;
11468                            bp.sourcePackage = p.info.packageName;
11469                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11470                            if (chatty) {
11471                                if (r == null) {
11472                                    r = new StringBuilder(256);
11473                                } else {
11474                                    r.append(' ');
11475                                }
11476                                r.append(p.info.name);
11477                            }
11478                        } else {
11479                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11480                                    + p.info.packageName + " ignored: base tree "
11481                                    + tree.name + " is from package "
11482                                    + tree.sourcePackage);
11483                        }
11484                    } else {
11485                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11486                                + p.info.packageName + " ignored: original from "
11487                                + bp.sourcePackage);
11488                    }
11489                } else if (chatty) {
11490                    if (r == null) {
11491                        r = new StringBuilder(256);
11492                    } else {
11493                        r.append(' ');
11494                    }
11495                    r.append("DUP:");
11496                    r.append(p.info.name);
11497                }
11498                if (bp.perm == p) {
11499                    bp.protectionLevel = p.info.protectionLevel;
11500                }
11501            }
11502
11503            if (r != null) {
11504                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11505            }
11506
11507            N = pkg.instrumentation.size();
11508            r = null;
11509            for (i=0; i<N; i++) {
11510                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11511                a.info.packageName = pkg.applicationInfo.packageName;
11512                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11513                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11514                a.info.splitNames = pkg.splitNames;
11515                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11516                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11517                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11518                a.info.dataDir = pkg.applicationInfo.dataDir;
11519                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11520                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11521                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11522                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11523                mInstrumentation.put(a.getComponentName(), a);
11524                if (chatty) {
11525                    if (r == null) {
11526                        r = new StringBuilder(256);
11527                    } else {
11528                        r.append(' ');
11529                    }
11530                    r.append(a.info.name);
11531                }
11532            }
11533            if (r != null) {
11534                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11535            }
11536
11537            if (pkg.protectedBroadcasts != null) {
11538                N = pkg.protectedBroadcasts.size();
11539                for (i=0; i<N; i++) {
11540                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11541                }
11542            }
11543        }
11544
11545        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11546    }
11547
11548    /**
11549     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11550     * is derived purely on the basis of the contents of {@code scanFile} and
11551     * {@code cpuAbiOverride}.
11552     *
11553     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11554     */
11555    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11556                                 String cpuAbiOverride, boolean extractLibs,
11557                                 File appLib32InstallDir)
11558            throws PackageManagerException {
11559        // Give ourselves some initial paths; we'll come back for another
11560        // pass once we've determined ABI below.
11561        setNativeLibraryPaths(pkg, appLib32InstallDir);
11562
11563        // We would never need to extract libs for forward-locked and external packages,
11564        // since the container service will do it for us. We shouldn't attempt to
11565        // extract libs from system app when it was not updated.
11566        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11567                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11568            extractLibs = false;
11569        }
11570
11571        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11572        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11573
11574        NativeLibraryHelper.Handle handle = null;
11575        try {
11576            handle = NativeLibraryHelper.Handle.create(pkg);
11577            // TODO(multiArch): This can be null for apps that didn't go through the
11578            // usual installation process. We can calculate it again, like we
11579            // do during install time.
11580            //
11581            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11582            // unnecessary.
11583            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11584
11585            // Null out the abis so that they can be recalculated.
11586            pkg.applicationInfo.primaryCpuAbi = null;
11587            pkg.applicationInfo.secondaryCpuAbi = null;
11588            if (isMultiArch(pkg.applicationInfo)) {
11589                // Warn if we've set an abiOverride for multi-lib packages..
11590                // By definition, we need to copy both 32 and 64 bit libraries for
11591                // such packages.
11592                if (pkg.cpuAbiOverride != null
11593                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11594                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11595                }
11596
11597                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11598                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11599                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11600                    if (extractLibs) {
11601                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11602                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11603                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11604                                useIsaSpecificSubdirs);
11605                    } else {
11606                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11607                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11608                    }
11609                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11610                }
11611
11612                // Shared library native code should be in the APK zip aligned
11613                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11614                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11615                            "Shared library native lib extraction not supported");
11616                }
11617
11618                maybeThrowExceptionForMultiArchCopy(
11619                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11620
11621                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11622                    if (extractLibs) {
11623                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11624                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11625                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11626                                useIsaSpecificSubdirs);
11627                    } else {
11628                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11629                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11630                    }
11631                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11632                }
11633
11634                maybeThrowExceptionForMultiArchCopy(
11635                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11636
11637                if (abi64 >= 0) {
11638                    // Shared library native libs should be in the APK zip aligned
11639                    if (extractLibs && pkg.isLibrary()) {
11640                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11641                                "Shared library native lib extraction not supported");
11642                    }
11643                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11644                }
11645
11646                if (abi32 >= 0) {
11647                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11648                    if (abi64 >= 0) {
11649                        if (pkg.use32bitAbi) {
11650                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11651                            pkg.applicationInfo.primaryCpuAbi = abi;
11652                        } else {
11653                            pkg.applicationInfo.secondaryCpuAbi = abi;
11654                        }
11655                    } else {
11656                        pkg.applicationInfo.primaryCpuAbi = abi;
11657                    }
11658                }
11659            } else {
11660                String[] abiList = (cpuAbiOverride != null) ?
11661                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11662
11663                // Enable gross and lame hacks for apps that are built with old
11664                // SDK tools. We must scan their APKs for renderscript bitcode and
11665                // not launch them if it's present. Don't bother checking on devices
11666                // that don't have 64 bit support.
11667                boolean needsRenderScriptOverride = false;
11668                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11669                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11670                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11671                    needsRenderScriptOverride = true;
11672                }
11673
11674                final int copyRet;
11675                if (extractLibs) {
11676                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11677                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11678                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11679                } else {
11680                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11681                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11682                }
11683                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11684
11685                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11686                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11687                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11688                }
11689
11690                if (copyRet >= 0) {
11691                    // Shared libraries that have native libs must be multi-architecture
11692                    if (pkg.isLibrary()) {
11693                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11694                                "Shared library with native libs must be multiarch");
11695                    }
11696                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11697                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11698                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11699                } else if (needsRenderScriptOverride) {
11700                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11701                }
11702            }
11703        } catch (IOException ioe) {
11704            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11705        } finally {
11706            IoUtils.closeQuietly(handle);
11707        }
11708
11709        // Now that we've calculated the ABIs and determined if it's an internal app,
11710        // we will go ahead and populate the nativeLibraryPath.
11711        setNativeLibraryPaths(pkg, appLib32InstallDir);
11712    }
11713
11714    /**
11715     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11716     * i.e, so that all packages can be run inside a single process if required.
11717     *
11718     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11719     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11720     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11721     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11722     * updating a package that belongs to a shared user.
11723     *
11724     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11725     * adds unnecessary complexity.
11726     */
11727    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11728            PackageParser.Package scannedPackage) {
11729        String requiredInstructionSet = null;
11730        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11731            requiredInstructionSet = VMRuntime.getInstructionSet(
11732                     scannedPackage.applicationInfo.primaryCpuAbi);
11733        }
11734
11735        PackageSetting requirer = null;
11736        for (PackageSetting ps : packagesForUser) {
11737            // If packagesForUser contains scannedPackage, we skip it. This will happen
11738            // when scannedPackage is an update of an existing package. Without this check,
11739            // we will never be able to change the ABI of any package belonging to a shared
11740            // user, even if it's compatible with other packages.
11741            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11742                if (ps.primaryCpuAbiString == null) {
11743                    continue;
11744                }
11745
11746                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11747                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11748                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11749                    // this but there's not much we can do.
11750                    String errorMessage = "Instruction set mismatch, "
11751                            + ((requirer == null) ? "[caller]" : requirer)
11752                            + " requires " + requiredInstructionSet + " whereas " + ps
11753                            + " requires " + instructionSet;
11754                    Slog.w(TAG, errorMessage);
11755                }
11756
11757                if (requiredInstructionSet == null) {
11758                    requiredInstructionSet = instructionSet;
11759                    requirer = ps;
11760                }
11761            }
11762        }
11763
11764        if (requiredInstructionSet != null) {
11765            String adjustedAbi;
11766            if (requirer != null) {
11767                // requirer != null implies that either scannedPackage was null or that scannedPackage
11768                // did not require an ABI, in which case we have to adjust scannedPackage to match
11769                // the ABI of the set (which is the same as requirer's ABI)
11770                adjustedAbi = requirer.primaryCpuAbiString;
11771                if (scannedPackage != null) {
11772                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11773                }
11774            } else {
11775                // requirer == null implies that we're updating all ABIs in the set to
11776                // match scannedPackage.
11777                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11778            }
11779
11780            for (PackageSetting ps : packagesForUser) {
11781                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11782                    if (ps.primaryCpuAbiString != null) {
11783                        continue;
11784                    }
11785
11786                    ps.primaryCpuAbiString = adjustedAbi;
11787                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11788                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11789                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11790                        if (DEBUG_ABI_SELECTION) {
11791                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11792                                    + " (requirer="
11793                                    + (requirer != null ? requirer.pkg : "null")
11794                                    + ", scannedPackage="
11795                                    + (scannedPackage != null ? scannedPackage : "null")
11796                                    + ")");
11797                        }
11798                        try {
11799                            mInstaller.rmdex(ps.codePathString,
11800                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11801                        } catch (InstallerException ignored) {
11802                        }
11803                    }
11804                }
11805            }
11806        }
11807    }
11808
11809    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11810        synchronized (mPackages) {
11811            mResolverReplaced = true;
11812            // Set up information for custom user intent resolution activity.
11813            mResolveActivity.applicationInfo = pkg.applicationInfo;
11814            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11815            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11816            mResolveActivity.processName = pkg.applicationInfo.packageName;
11817            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11818            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11819                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11820            mResolveActivity.theme = 0;
11821            mResolveActivity.exported = true;
11822            mResolveActivity.enabled = true;
11823            mResolveInfo.activityInfo = mResolveActivity;
11824            mResolveInfo.priority = 0;
11825            mResolveInfo.preferredOrder = 0;
11826            mResolveInfo.match = 0;
11827            mResolveComponentName = mCustomResolverComponentName;
11828            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11829                    mResolveComponentName);
11830        }
11831    }
11832
11833    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11834        if (installerActivity == null) {
11835            if (DEBUG_EPHEMERAL) {
11836                Slog.d(TAG, "Clear ephemeral installer activity");
11837            }
11838            mInstantAppInstallerActivity = null;
11839            return;
11840        }
11841
11842        if (DEBUG_EPHEMERAL) {
11843            Slog.d(TAG, "Set ephemeral installer activity: "
11844                    + installerActivity.getComponentName());
11845        }
11846        // Set up information for ephemeral installer activity
11847        mInstantAppInstallerActivity = installerActivity;
11848        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11849                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11850        mInstantAppInstallerActivity.exported = true;
11851        mInstantAppInstallerActivity.enabled = true;
11852        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11853        mInstantAppInstallerInfo.priority = 0;
11854        mInstantAppInstallerInfo.preferredOrder = 1;
11855        mInstantAppInstallerInfo.isDefault = true;
11856        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11857                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11858    }
11859
11860    private static String calculateBundledApkRoot(final String codePathString) {
11861        final File codePath = new File(codePathString);
11862        final File codeRoot;
11863        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11864            codeRoot = Environment.getRootDirectory();
11865        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11866            codeRoot = Environment.getOemDirectory();
11867        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11868            codeRoot = Environment.getVendorDirectory();
11869        } else {
11870            // Unrecognized code path; take its top real segment as the apk root:
11871            // e.g. /something/app/blah.apk => /something
11872            try {
11873                File f = codePath.getCanonicalFile();
11874                File parent = f.getParentFile();    // non-null because codePath is a file
11875                File tmp;
11876                while ((tmp = parent.getParentFile()) != null) {
11877                    f = parent;
11878                    parent = tmp;
11879                }
11880                codeRoot = f;
11881                Slog.w(TAG, "Unrecognized code path "
11882                        + codePath + " - using " + codeRoot);
11883            } catch (IOException e) {
11884                // Can't canonicalize the code path -- shenanigans?
11885                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11886                return Environment.getRootDirectory().getPath();
11887            }
11888        }
11889        return codeRoot.getPath();
11890    }
11891
11892    /**
11893     * Derive and set the location of native libraries for the given package,
11894     * which varies depending on where and how the package was installed.
11895     */
11896    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11897        final ApplicationInfo info = pkg.applicationInfo;
11898        final String codePath = pkg.codePath;
11899        final File codeFile = new File(codePath);
11900        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11901        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11902
11903        info.nativeLibraryRootDir = null;
11904        info.nativeLibraryRootRequiresIsa = false;
11905        info.nativeLibraryDir = null;
11906        info.secondaryNativeLibraryDir = null;
11907
11908        if (isApkFile(codeFile)) {
11909            // Monolithic install
11910            if (bundledApp) {
11911                // If "/system/lib64/apkname" exists, assume that is the per-package
11912                // native library directory to use; otherwise use "/system/lib/apkname".
11913                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11914                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11915                        getPrimaryInstructionSet(info));
11916
11917                // This is a bundled system app so choose the path based on the ABI.
11918                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11919                // is just the default path.
11920                final String apkName = deriveCodePathName(codePath);
11921                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11922                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11923                        apkName).getAbsolutePath();
11924
11925                if (info.secondaryCpuAbi != null) {
11926                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11927                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11928                            secondaryLibDir, apkName).getAbsolutePath();
11929                }
11930            } else if (asecApp) {
11931                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11932                        .getAbsolutePath();
11933            } else {
11934                final String apkName = deriveCodePathName(codePath);
11935                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11936                        .getAbsolutePath();
11937            }
11938
11939            info.nativeLibraryRootRequiresIsa = false;
11940            info.nativeLibraryDir = info.nativeLibraryRootDir;
11941        } else {
11942            // Cluster install
11943            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11944            info.nativeLibraryRootRequiresIsa = true;
11945
11946            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11947                    getPrimaryInstructionSet(info)).getAbsolutePath();
11948
11949            if (info.secondaryCpuAbi != null) {
11950                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11951                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11952            }
11953        }
11954    }
11955
11956    /**
11957     * Calculate the abis and roots for a bundled app. These can uniquely
11958     * be determined from the contents of the system partition, i.e whether
11959     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11960     * of this information, and instead assume that the system was built
11961     * sensibly.
11962     */
11963    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11964                                           PackageSetting pkgSetting) {
11965        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11966
11967        // If "/system/lib64/apkname" exists, assume that is the per-package
11968        // native library directory to use; otherwise use "/system/lib/apkname".
11969        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11970        setBundledAppAbi(pkg, apkRoot, apkName);
11971        // pkgSetting might be null during rescan following uninstall of updates
11972        // to a bundled app, so accommodate that possibility.  The settings in
11973        // that case will be established later from the parsed package.
11974        //
11975        // If the settings aren't null, sync them up with what we've just derived.
11976        // note that apkRoot isn't stored in the package settings.
11977        if (pkgSetting != null) {
11978            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11979            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11980        }
11981    }
11982
11983    /**
11984     * Deduces the ABI of a bundled app and sets the relevant fields on the
11985     * parsed pkg object.
11986     *
11987     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11988     *        under which system libraries are installed.
11989     * @param apkName the name of the installed package.
11990     */
11991    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11992        final File codeFile = new File(pkg.codePath);
11993
11994        final boolean has64BitLibs;
11995        final boolean has32BitLibs;
11996        if (isApkFile(codeFile)) {
11997            // Monolithic install
11998            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11999            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12000        } else {
12001            // Cluster install
12002            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12003            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12004                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12005                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12006                has64BitLibs = (new File(rootDir, isa)).exists();
12007            } else {
12008                has64BitLibs = false;
12009            }
12010            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12011                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12012                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12013                has32BitLibs = (new File(rootDir, isa)).exists();
12014            } else {
12015                has32BitLibs = false;
12016            }
12017        }
12018
12019        if (has64BitLibs && !has32BitLibs) {
12020            // The package has 64 bit libs, but not 32 bit libs. Its primary
12021            // ABI should be 64 bit. We can safely assume here that the bundled
12022            // native libraries correspond to the most preferred ABI in the list.
12023
12024            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12025            pkg.applicationInfo.secondaryCpuAbi = null;
12026        } else if (has32BitLibs && !has64BitLibs) {
12027            // The package has 32 bit libs but not 64 bit libs. Its primary
12028            // ABI should be 32 bit.
12029
12030            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12031            pkg.applicationInfo.secondaryCpuAbi = null;
12032        } else if (has32BitLibs && has64BitLibs) {
12033            // The application has both 64 and 32 bit bundled libraries. We check
12034            // here that the app declares multiArch support, and warn if it doesn't.
12035            //
12036            // We will be lenient here and record both ABIs. The primary will be the
12037            // ABI that's higher on the list, i.e, a device that's configured to prefer
12038            // 64 bit apps will see a 64 bit primary ABI,
12039
12040            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12041                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12042            }
12043
12044            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12045                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12046                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12047            } else {
12048                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12049                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12050            }
12051        } else {
12052            pkg.applicationInfo.primaryCpuAbi = null;
12053            pkg.applicationInfo.secondaryCpuAbi = null;
12054        }
12055    }
12056
12057    private void killApplication(String pkgName, int appId, String reason) {
12058        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12059    }
12060
12061    private void killApplication(String pkgName, int appId, int userId, String reason) {
12062        // Request the ActivityManager to kill the process(only for existing packages)
12063        // so that we do not end up in a confused state while the user is still using the older
12064        // version of the application while the new one gets installed.
12065        final long token = Binder.clearCallingIdentity();
12066        try {
12067            IActivityManager am = ActivityManager.getService();
12068            if (am != null) {
12069                try {
12070                    am.killApplication(pkgName, appId, userId, reason);
12071                } catch (RemoteException e) {
12072                }
12073            }
12074        } finally {
12075            Binder.restoreCallingIdentity(token);
12076        }
12077    }
12078
12079    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12080        // Remove the parent package setting
12081        PackageSetting ps = (PackageSetting) pkg.mExtras;
12082        if (ps != null) {
12083            removePackageLI(ps, chatty);
12084        }
12085        // Remove the child package setting
12086        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12087        for (int i = 0; i < childCount; i++) {
12088            PackageParser.Package childPkg = pkg.childPackages.get(i);
12089            ps = (PackageSetting) childPkg.mExtras;
12090            if (ps != null) {
12091                removePackageLI(ps, chatty);
12092            }
12093        }
12094    }
12095
12096    void removePackageLI(PackageSetting ps, boolean chatty) {
12097        if (DEBUG_INSTALL) {
12098            if (chatty)
12099                Log.d(TAG, "Removing package " + ps.name);
12100        }
12101
12102        // writer
12103        synchronized (mPackages) {
12104            mPackages.remove(ps.name);
12105            final PackageParser.Package pkg = ps.pkg;
12106            if (pkg != null) {
12107                cleanPackageDataStructuresLILPw(pkg, chatty);
12108            }
12109        }
12110    }
12111
12112    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12113        if (DEBUG_INSTALL) {
12114            if (chatty)
12115                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12116        }
12117
12118        // writer
12119        synchronized (mPackages) {
12120            // Remove the parent package
12121            mPackages.remove(pkg.applicationInfo.packageName);
12122            cleanPackageDataStructuresLILPw(pkg, chatty);
12123
12124            // Remove the child packages
12125            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12126            for (int i = 0; i < childCount; i++) {
12127                PackageParser.Package childPkg = pkg.childPackages.get(i);
12128                mPackages.remove(childPkg.applicationInfo.packageName);
12129                cleanPackageDataStructuresLILPw(childPkg, chatty);
12130            }
12131        }
12132    }
12133
12134    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12135        int N = pkg.providers.size();
12136        StringBuilder r = null;
12137        int i;
12138        for (i=0; i<N; i++) {
12139            PackageParser.Provider p = pkg.providers.get(i);
12140            mProviders.removeProvider(p);
12141            if (p.info.authority == null) {
12142
12143                /* There was another ContentProvider with this authority when
12144                 * this app was installed so this authority is null,
12145                 * Ignore it as we don't have to unregister the provider.
12146                 */
12147                continue;
12148            }
12149            String names[] = p.info.authority.split(";");
12150            for (int j = 0; j < names.length; j++) {
12151                if (mProvidersByAuthority.get(names[j]) == p) {
12152                    mProvidersByAuthority.remove(names[j]);
12153                    if (DEBUG_REMOVE) {
12154                        if (chatty)
12155                            Log.d(TAG, "Unregistered content provider: " + names[j]
12156                                    + ", className = " + p.info.name + ", isSyncable = "
12157                                    + p.info.isSyncable);
12158                    }
12159                }
12160            }
12161            if (DEBUG_REMOVE && chatty) {
12162                if (r == null) {
12163                    r = new StringBuilder(256);
12164                } else {
12165                    r.append(' ');
12166                }
12167                r.append(p.info.name);
12168            }
12169        }
12170        if (r != null) {
12171            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12172        }
12173
12174        N = pkg.services.size();
12175        r = null;
12176        for (i=0; i<N; i++) {
12177            PackageParser.Service s = pkg.services.get(i);
12178            mServices.removeService(s);
12179            if (chatty) {
12180                if (r == null) {
12181                    r = new StringBuilder(256);
12182                } else {
12183                    r.append(' ');
12184                }
12185                r.append(s.info.name);
12186            }
12187        }
12188        if (r != null) {
12189            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12190        }
12191
12192        N = pkg.receivers.size();
12193        r = null;
12194        for (i=0; i<N; i++) {
12195            PackageParser.Activity a = pkg.receivers.get(i);
12196            mReceivers.removeActivity(a, "receiver");
12197            if (DEBUG_REMOVE && chatty) {
12198                if (r == null) {
12199                    r = new StringBuilder(256);
12200                } else {
12201                    r.append(' ');
12202                }
12203                r.append(a.info.name);
12204            }
12205        }
12206        if (r != null) {
12207            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12208        }
12209
12210        N = pkg.activities.size();
12211        r = null;
12212        for (i=0; i<N; i++) {
12213            PackageParser.Activity a = pkg.activities.get(i);
12214            mActivities.removeActivity(a, "activity");
12215            if (DEBUG_REMOVE && chatty) {
12216                if (r == null) {
12217                    r = new StringBuilder(256);
12218                } else {
12219                    r.append(' ');
12220                }
12221                r.append(a.info.name);
12222            }
12223        }
12224        if (r != null) {
12225            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12226        }
12227
12228        N = pkg.permissions.size();
12229        r = null;
12230        for (i=0; i<N; i++) {
12231            PackageParser.Permission p = pkg.permissions.get(i);
12232            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12233            if (bp == null) {
12234                bp = mSettings.mPermissionTrees.get(p.info.name);
12235            }
12236            if (bp != null && bp.perm == p) {
12237                bp.perm = null;
12238                if (DEBUG_REMOVE && chatty) {
12239                    if (r == null) {
12240                        r = new StringBuilder(256);
12241                    } else {
12242                        r.append(' ');
12243                    }
12244                    r.append(p.info.name);
12245                }
12246            }
12247            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12248                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12249                if (appOpPkgs != null) {
12250                    appOpPkgs.remove(pkg.packageName);
12251                }
12252            }
12253        }
12254        if (r != null) {
12255            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12256        }
12257
12258        N = pkg.requestedPermissions.size();
12259        r = null;
12260        for (i=0; i<N; i++) {
12261            String perm = pkg.requestedPermissions.get(i);
12262            BasePermission bp = mSettings.mPermissions.get(perm);
12263            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12264                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12265                if (appOpPkgs != null) {
12266                    appOpPkgs.remove(pkg.packageName);
12267                    if (appOpPkgs.isEmpty()) {
12268                        mAppOpPermissionPackages.remove(perm);
12269                    }
12270                }
12271            }
12272        }
12273        if (r != null) {
12274            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12275        }
12276
12277        N = pkg.instrumentation.size();
12278        r = null;
12279        for (i=0; i<N; i++) {
12280            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12281            mInstrumentation.remove(a.getComponentName());
12282            if (DEBUG_REMOVE && chatty) {
12283                if (r == null) {
12284                    r = new StringBuilder(256);
12285                } else {
12286                    r.append(' ');
12287                }
12288                r.append(a.info.name);
12289            }
12290        }
12291        if (r != null) {
12292            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12293        }
12294
12295        r = null;
12296        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12297            // Only system apps can hold shared libraries.
12298            if (pkg.libraryNames != null) {
12299                for (i = 0; i < pkg.libraryNames.size(); i++) {
12300                    String name = pkg.libraryNames.get(i);
12301                    if (removeSharedLibraryLPw(name, 0)) {
12302                        if (DEBUG_REMOVE && chatty) {
12303                            if (r == null) {
12304                                r = new StringBuilder(256);
12305                            } else {
12306                                r.append(' ');
12307                            }
12308                            r.append(name);
12309                        }
12310                    }
12311                }
12312            }
12313        }
12314
12315        r = null;
12316
12317        // Any package can hold static shared libraries.
12318        if (pkg.staticSharedLibName != null) {
12319            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12320                if (DEBUG_REMOVE && chatty) {
12321                    if (r == null) {
12322                        r = new StringBuilder(256);
12323                    } else {
12324                        r.append(' ');
12325                    }
12326                    r.append(pkg.staticSharedLibName);
12327                }
12328            }
12329        }
12330
12331        if (r != null) {
12332            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12333        }
12334    }
12335
12336    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12337        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12338            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12339                return true;
12340            }
12341        }
12342        return false;
12343    }
12344
12345    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12346    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12347    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12348
12349    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12350        // Update the parent permissions
12351        updatePermissionsLPw(pkg.packageName, pkg, flags);
12352        // Update the child permissions
12353        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12354        for (int i = 0; i < childCount; i++) {
12355            PackageParser.Package childPkg = pkg.childPackages.get(i);
12356            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12357        }
12358    }
12359
12360    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12361            int flags) {
12362        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12363        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12364    }
12365
12366    private void updatePermissionsLPw(String changingPkg,
12367            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12368        // Make sure there are no dangling permission trees.
12369        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12370        while (it.hasNext()) {
12371            final BasePermission bp = it.next();
12372            if (bp.packageSetting == null) {
12373                // We may not yet have parsed the package, so just see if
12374                // we still know about its settings.
12375                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12376            }
12377            if (bp.packageSetting == null) {
12378                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12379                        + " from package " + bp.sourcePackage);
12380                it.remove();
12381            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12382                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12383                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12384                            + " from package " + bp.sourcePackage);
12385                    flags |= UPDATE_PERMISSIONS_ALL;
12386                    it.remove();
12387                }
12388            }
12389        }
12390
12391        // Make sure all dynamic permissions have been assigned to a package,
12392        // and make sure there are no dangling permissions.
12393        it = mSettings.mPermissions.values().iterator();
12394        while (it.hasNext()) {
12395            final BasePermission bp = it.next();
12396            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12397                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12398                        + bp.name + " pkg=" + bp.sourcePackage
12399                        + " info=" + bp.pendingInfo);
12400                if (bp.packageSetting == null && bp.pendingInfo != null) {
12401                    final BasePermission tree = findPermissionTreeLP(bp.name);
12402                    if (tree != null && tree.perm != null) {
12403                        bp.packageSetting = tree.packageSetting;
12404                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12405                                new PermissionInfo(bp.pendingInfo));
12406                        bp.perm.info.packageName = tree.perm.info.packageName;
12407                        bp.perm.info.name = bp.name;
12408                        bp.uid = tree.uid;
12409                    }
12410                }
12411            }
12412            if (bp.packageSetting == null) {
12413                // We may not yet have parsed the package, so just see if
12414                // we still know about its settings.
12415                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12416            }
12417            if (bp.packageSetting == null) {
12418                Slog.w(TAG, "Removing dangling permission: " + bp.name
12419                        + " from package " + bp.sourcePackage);
12420                it.remove();
12421            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12422                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12423                    Slog.i(TAG, "Removing old permission: " + bp.name
12424                            + " from package " + bp.sourcePackage);
12425                    flags |= UPDATE_PERMISSIONS_ALL;
12426                    it.remove();
12427                }
12428            }
12429        }
12430
12431        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12432        // Now update the permissions for all packages, in particular
12433        // replace the granted permissions of the system packages.
12434        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12435            for (PackageParser.Package pkg : mPackages.values()) {
12436                if (pkg != pkgInfo) {
12437                    // Only replace for packages on requested volume
12438                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12439                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12440                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12441                    grantPermissionsLPw(pkg, replace, changingPkg);
12442                }
12443            }
12444        }
12445
12446        if (pkgInfo != null) {
12447            // Only replace for packages on requested volume
12448            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12449            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12450                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12451            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12452        }
12453        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12454    }
12455
12456    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12457            String packageOfInterest) {
12458        // IMPORTANT: There are two types of permissions: install and runtime.
12459        // Install time permissions are granted when the app is installed to
12460        // all device users and users added in the future. Runtime permissions
12461        // are granted at runtime explicitly to specific users. Normal and signature
12462        // protected permissions are install time permissions. Dangerous permissions
12463        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12464        // otherwise they are runtime permissions. This function does not manage
12465        // runtime permissions except for the case an app targeting Lollipop MR1
12466        // being upgraded to target a newer SDK, in which case dangerous permissions
12467        // are transformed from install time to runtime ones.
12468
12469        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12470        if (ps == null) {
12471            return;
12472        }
12473
12474        PermissionsState permissionsState = ps.getPermissionsState();
12475        PermissionsState origPermissions = permissionsState;
12476
12477        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12478
12479        boolean runtimePermissionsRevoked = false;
12480        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12481
12482        boolean changedInstallPermission = false;
12483
12484        if (replace) {
12485            ps.installPermissionsFixed = false;
12486            if (!ps.isSharedUser()) {
12487                origPermissions = new PermissionsState(permissionsState);
12488                permissionsState.reset();
12489            } else {
12490                // We need to know only about runtime permission changes since the
12491                // calling code always writes the install permissions state but
12492                // the runtime ones are written only if changed. The only cases of
12493                // changed runtime permissions here are promotion of an install to
12494                // runtime and revocation of a runtime from a shared user.
12495                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12496                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12497                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12498                    runtimePermissionsRevoked = true;
12499                }
12500            }
12501        }
12502
12503        permissionsState.setGlobalGids(mGlobalGids);
12504
12505        final int N = pkg.requestedPermissions.size();
12506        for (int i=0; i<N; i++) {
12507            final String name = pkg.requestedPermissions.get(i);
12508            final BasePermission bp = mSettings.mPermissions.get(name);
12509            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12510                    >= Build.VERSION_CODES.M;
12511
12512            if (DEBUG_INSTALL) {
12513                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12514            }
12515
12516            if (bp == null || bp.packageSetting == null) {
12517                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12518                    if (DEBUG_PERMISSIONS) {
12519                        Slog.i(TAG, "Unknown permission " + name
12520                                + " in package " + pkg.packageName);
12521                    }
12522                }
12523                continue;
12524            }
12525
12526
12527            // Limit ephemeral apps to ephemeral allowed permissions.
12528            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12529                if (DEBUG_PERMISSIONS) {
12530                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12531                            + pkg.packageName);
12532                }
12533                continue;
12534            }
12535
12536            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12537                if (DEBUG_PERMISSIONS) {
12538                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12539                            + pkg.packageName);
12540                }
12541                continue;
12542            }
12543
12544            final String perm = bp.name;
12545            boolean allowedSig = false;
12546            int grant = GRANT_DENIED;
12547
12548            // Keep track of app op permissions.
12549            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12550                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12551                if (pkgs == null) {
12552                    pkgs = new ArraySet<>();
12553                    mAppOpPermissionPackages.put(bp.name, pkgs);
12554                }
12555                pkgs.add(pkg.packageName);
12556            }
12557
12558            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12559            switch (level) {
12560                case PermissionInfo.PROTECTION_NORMAL: {
12561                    // For all apps normal permissions are install time ones.
12562                    grant = GRANT_INSTALL;
12563                } break;
12564
12565                case PermissionInfo.PROTECTION_DANGEROUS: {
12566                    // If a permission review is required for legacy apps we represent
12567                    // their permissions as always granted runtime ones since we need
12568                    // to keep the review required permission flag per user while an
12569                    // install permission's state is shared across all users.
12570                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12571                        // For legacy apps dangerous permissions are install time ones.
12572                        grant = GRANT_INSTALL;
12573                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12574                        // For legacy apps that became modern, install becomes runtime.
12575                        grant = GRANT_UPGRADE;
12576                    } else if (mPromoteSystemApps
12577                            && isSystemApp(ps)
12578                            && mExistingSystemPackages.contains(ps.name)) {
12579                        // For legacy system apps, install becomes runtime.
12580                        // We cannot check hasInstallPermission() for system apps since those
12581                        // permissions were granted implicitly and not persisted pre-M.
12582                        grant = GRANT_UPGRADE;
12583                    } else {
12584                        // For modern apps keep runtime permissions unchanged.
12585                        grant = GRANT_RUNTIME;
12586                    }
12587                } break;
12588
12589                case PermissionInfo.PROTECTION_SIGNATURE: {
12590                    // For all apps signature permissions are install time ones.
12591                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12592                    if (allowedSig) {
12593                        grant = GRANT_INSTALL;
12594                    }
12595                } break;
12596            }
12597
12598            if (DEBUG_PERMISSIONS) {
12599                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12600            }
12601
12602            if (grant != GRANT_DENIED) {
12603                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12604                    // If this is an existing, non-system package, then
12605                    // we can't add any new permissions to it.
12606                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12607                        // Except...  if this is a permission that was added
12608                        // to the platform (note: need to only do this when
12609                        // updating the platform).
12610                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12611                            grant = GRANT_DENIED;
12612                        }
12613                    }
12614                }
12615
12616                switch (grant) {
12617                    case GRANT_INSTALL: {
12618                        // Revoke this as runtime permission to handle the case of
12619                        // a runtime permission being downgraded to an install one.
12620                        // Also in permission review mode we keep dangerous permissions
12621                        // for legacy apps
12622                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12623                            if (origPermissions.getRuntimePermissionState(
12624                                    bp.name, userId) != null) {
12625                                // Revoke the runtime permission and clear the flags.
12626                                origPermissions.revokeRuntimePermission(bp, userId);
12627                                origPermissions.updatePermissionFlags(bp, userId,
12628                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12629                                // If we revoked a permission permission, we have to write.
12630                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12631                                        changedRuntimePermissionUserIds, userId);
12632                            }
12633                        }
12634                        // Grant an install permission.
12635                        if (permissionsState.grantInstallPermission(bp) !=
12636                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12637                            changedInstallPermission = true;
12638                        }
12639                    } break;
12640
12641                    case GRANT_RUNTIME: {
12642                        // Grant previously granted runtime permissions.
12643                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12644                            PermissionState permissionState = origPermissions
12645                                    .getRuntimePermissionState(bp.name, userId);
12646                            int flags = permissionState != null
12647                                    ? permissionState.getFlags() : 0;
12648                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12649                                // Don't propagate the permission in a permission review mode if
12650                                // the former was revoked, i.e. marked to not propagate on upgrade.
12651                                // Note that in a permission review mode install permissions are
12652                                // represented as constantly granted runtime ones since we need to
12653                                // keep a per user state associated with the permission. Also the
12654                                // revoke on upgrade flag is no longer applicable and is reset.
12655                                final boolean revokeOnUpgrade = (flags & PackageManager
12656                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12657                                if (revokeOnUpgrade) {
12658                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12659                                    // Since we changed the flags, we have to write.
12660                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12661                                            changedRuntimePermissionUserIds, userId);
12662                                }
12663                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12664                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12665                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12666                                        // If we cannot put the permission as it was,
12667                                        // we have to write.
12668                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12669                                                changedRuntimePermissionUserIds, userId);
12670                                    }
12671                                }
12672
12673                                // If the app supports runtime permissions no need for a review.
12674                                if (mPermissionReviewRequired
12675                                        && appSupportsRuntimePermissions
12676                                        && (flags & PackageManager
12677                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12678                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12679                                    // Since we changed the flags, we have to write.
12680                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12681                                            changedRuntimePermissionUserIds, userId);
12682                                }
12683                            } else if (mPermissionReviewRequired
12684                                    && !appSupportsRuntimePermissions) {
12685                                // For legacy apps that need a permission review, every new
12686                                // runtime permission is granted but it is pending a review.
12687                                // We also need to review only platform defined runtime
12688                                // permissions as these are the only ones the platform knows
12689                                // how to disable the API to simulate revocation as legacy
12690                                // apps don't expect to run with revoked permissions.
12691                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12692                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12693                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12694                                        // We changed the flags, hence have to write.
12695                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12696                                                changedRuntimePermissionUserIds, userId);
12697                                    }
12698                                }
12699                                if (permissionsState.grantRuntimePermission(bp, userId)
12700                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12701                                    // We changed the permission, hence have to write.
12702                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12703                                            changedRuntimePermissionUserIds, userId);
12704                                }
12705                            }
12706                            // Propagate the permission flags.
12707                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12708                        }
12709                    } break;
12710
12711                    case GRANT_UPGRADE: {
12712                        // Grant runtime permissions for a previously held install permission.
12713                        PermissionState permissionState = origPermissions
12714                                .getInstallPermissionState(bp.name);
12715                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12716
12717                        if (origPermissions.revokeInstallPermission(bp)
12718                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12719                            // We will be transferring the permission flags, so clear them.
12720                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12721                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12722                            changedInstallPermission = true;
12723                        }
12724
12725                        // If the permission is not to be promoted to runtime we ignore it and
12726                        // also its other flags as they are not applicable to install permissions.
12727                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12728                            for (int userId : currentUserIds) {
12729                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12730                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12731                                    // Transfer the permission flags.
12732                                    permissionsState.updatePermissionFlags(bp, userId,
12733                                            flags, flags);
12734                                    // If we granted the permission, we have to write.
12735                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12736                                            changedRuntimePermissionUserIds, userId);
12737                                }
12738                            }
12739                        }
12740                    } break;
12741
12742                    default: {
12743                        if (packageOfInterest == null
12744                                || packageOfInterest.equals(pkg.packageName)) {
12745                            if (DEBUG_PERMISSIONS) {
12746                                Slog.i(TAG, "Not granting permission " + perm
12747                                        + " to package " + pkg.packageName
12748                                        + " because it was previously installed without");
12749                            }
12750                        }
12751                    } break;
12752                }
12753            } else {
12754                if (permissionsState.revokeInstallPermission(bp) !=
12755                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12756                    // Also drop the permission flags.
12757                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12758                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12759                    changedInstallPermission = true;
12760                    Slog.i(TAG, "Un-granting permission " + perm
12761                            + " from package " + pkg.packageName
12762                            + " (protectionLevel=" + bp.protectionLevel
12763                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12764                            + ")");
12765                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12766                    // Don't print warning for app op permissions, since it is fine for them
12767                    // not to be granted, there is a UI for the user to decide.
12768                    if (DEBUG_PERMISSIONS
12769                            && (packageOfInterest == null
12770                                    || packageOfInterest.equals(pkg.packageName))) {
12771                        Slog.i(TAG, "Not granting permission " + perm
12772                                + " to package " + pkg.packageName
12773                                + " (protectionLevel=" + bp.protectionLevel
12774                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12775                                + ")");
12776                    }
12777                }
12778            }
12779        }
12780
12781        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12782                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12783            // This is the first that we have heard about this package, so the
12784            // permissions we have now selected are fixed until explicitly
12785            // changed.
12786            ps.installPermissionsFixed = true;
12787        }
12788
12789        // Persist the runtime permissions state for users with changes. If permissions
12790        // were revoked because no app in the shared user declares them we have to
12791        // write synchronously to avoid losing runtime permissions state.
12792        for (int userId : changedRuntimePermissionUserIds) {
12793            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12794        }
12795    }
12796
12797    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12798        boolean allowed = false;
12799        final int NP = PackageParser.NEW_PERMISSIONS.length;
12800        for (int ip=0; ip<NP; ip++) {
12801            final PackageParser.NewPermissionInfo npi
12802                    = PackageParser.NEW_PERMISSIONS[ip];
12803            if (npi.name.equals(perm)
12804                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12805                allowed = true;
12806                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12807                        + pkg.packageName);
12808                break;
12809            }
12810        }
12811        return allowed;
12812    }
12813
12814    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12815            BasePermission bp, PermissionsState origPermissions) {
12816        boolean privilegedPermission = (bp.protectionLevel
12817                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12818        boolean privappPermissionsDisable =
12819                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12820        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12821        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12822        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12823                && !platformPackage && platformPermission) {
12824            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12825                    .getPrivAppPermissions(pkg.packageName);
12826            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12827            if (!whitelisted) {
12828                Slog.w(TAG, "Privileged permission " + perm + " for package "
12829                        + pkg.packageName + " - not in privapp-permissions whitelist");
12830                // Only report violations for apps on system image
12831                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12832                    if (mPrivappPermissionsViolations == null) {
12833                        mPrivappPermissionsViolations = new ArraySet<>();
12834                    }
12835                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12836                }
12837                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12838                    return false;
12839                }
12840            }
12841        }
12842        boolean allowed = (compareSignatures(
12843                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12844                        == PackageManager.SIGNATURE_MATCH)
12845                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12846                        == PackageManager.SIGNATURE_MATCH);
12847        if (!allowed && privilegedPermission) {
12848            if (isSystemApp(pkg)) {
12849                // For updated system applications, a system permission
12850                // is granted only if it had been defined by the original application.
12851                if (pkg.isUpdatedSystemApp()) {
12852                    final PackageSetting sysPs = mSettings
12853                            .getDisabledSystemPkgLPr(pkg.packageName);
12854                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12855                        // If the original was granted this permission, we take
12856                        // that grant decision as read and propagate it to the
12857                        // update.
12858                        if (sysPs.isPrivileged()) {
12859                            allowed = true;
12860                        }
12861                    } else {
12862                        // The system apk may have been updated with an older
12863                        // version of the one on the data partition, but which
12864                        // granted a new system permission that it didn't have
12865                        // before.  In this case we do want to allow the app to
12866                        // now get the new permission if the ancestral apk is
12867                        // privileged to get it.
12868                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12869                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12870                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12871                                    allowed = true;
12872                                    break;
12873                                }
12874                            }
12875                        }
12876                        // Also if a privileged parent package on the system image or any of
12877                        // its children requested a privileged permission, the updated child
12878                        // packages can also get the permission.
12879                        if (pkg.parentPackage != null) {
12880                            final PackageSetting disabledSysParentPs = mSettings
12881                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12882                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12883                                    && disabledSysParentPs.isPrivileged()) {
12884                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12885                                    allowed = true;
12886                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12887                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12888                                    for (int i = 0; i < count; i++) {
12889                                        PackageParser.Package disabledSysChildPkg =
12890                                                disabledSysParentPs.pkg.childPackages.get(i);
12891                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12892                                                perm)) {
12893                                            allowed = true;
12894                                            break;
12895                                        }
12896                                    }
12897                                }
12898                            }
12899                        }
12900                    }
12901                } else {
12902                    allowed = isPrivilegedApp(pkg);
12903                }
12904            }
12905        }
12906        if (!allowed) {
12907            if (!allowed && (bp.protectionLevel
12908                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12909                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12910                // If this was a previously normal/dangerous permission that got moved
12911                // to a system permission as part of the runtime permission redesign, then
12912                // we still want to blindly grant it to old apps.
12913                allowed = true;
12914            }
12915            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12916                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12917                // If this permission is to be granted to the system installer and
12918                // this app is an installer, then it gets the permission.
12919                allowed = true;
12920            }
12921            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12922                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12923                // If this permission is to be granted to the system verifier and
12924                // this app is a verifier, then it gets the permission.
12925                allowed = true;
12926            }
12927            if (!allowed && (bp.protectionLevel
12928                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12929                    && isSystemApp(pkg)) {
12930                // Any pre-installed system app is allowed to get this permission.
12931                allowed = true;
12932            }
12933            if (!allowed && (bp.protectionLevel
12934                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12935                // For development permissions, a development permission
12936                // is granted only if it was already granted.
12937                allowed = origPermissions.hasInstallPermission(perm);
12938            }
12939            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12940                    && pkg.packageName.equals(mSetupWizardPackage)) {
12941                // If this permission is to be granted to the system setup wizard and
12942                // this app is a setup wizard, then it gets the permission.
12943                allowed = true;
12944            }
12945        }
12946        return allowed;
12947    }
12948
12949    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12950        final int permCount = pkg.requestedPermissions.size();
12951        for (int j = 0; j < permCount; j++) {
12952            String requestedPermission = pkg.requestedPermissions.get(j);
12953            if (permission.equals(requestedPermission)) {
12954                return true;
12955            }
12956        }
12957        return false;
12958    }
12959
12960    final class ActivityIntentResolver
12961            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12962        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12963                boolean defaultOnly, int userId) {
12964            if (!sUserManager.exists(userId)) return null;
12965            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12966            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12967        }
12968
12969        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12970                int userId) {
12971            if (!sUserManager.exists(userId)) return null;
12972            mFlags = flags;
12973            return super.queryIntent(intent, resolvedType,
12974                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12975                    userId);
12976        }
12977
12978        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12979                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12980            if (!sUserManager.exists(userId)) return null;
12981            if (packageActivities == null) {
12982                return null;
12983            }
12984            mFlags = flags;
12985            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12986            final int N = packageActivities.size();
12987            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12988                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12989
12990            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12991            for (int i = 0; i < N; ++i) {
12992                intentFilters = packageActivities.get(i).intents;
12993                if (intentFilters != null && intentFilters.size() > 0) {
12994                    PackageParser.ActivityIntentInfo[] array =
12995                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12996                    intentFilters.toArray(array);
12997                    listCut.add(array);
12998                }
12999            }
13000            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13001        }
13002
13003        /**
13004         * Finds a privileged activity that matches the specified activity names.
13005         */
13006        private PackageParser.Activity findMatchingActivity(
13007                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13008            for (PackageParser.Activity sysActivity : activityList) {
13009                if (sysActivity.info.name.equals(activityInfo.name)) {
13010                    return sysActivity;
13011                }
13012                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13013                    return sysActivity;
13014                }
13015                if (sysActivity.info.targetActivity != null) {
13016                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13017                        return sysActivity;
13018                    }
13019                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13020                        return sysActivity;
13021                    }
13022                }
13023            }
13024            return null;
13025        }
13026
13027        public class IterGenerator<E> {
13028            public Iterator<E> generate(ActivityIntentInfo info) {
13029                return null;
13030            }
13031        }
13032
13033        public class ActionIterGenerator extends IterGenerator<String> {
13034            @Override
13035            public Iterator<String> generate(ActivityIntentInfo info) {
13036                return info.actionsIterator();
13037            }
13038        }
13039
13040        public class CategoriesIterGenerator extends IterGenerator<String> {
13041            @Override
13042            public Iterator<String> generate(ActivityIntentInfo info) {
13043                return info.categoriesIterator();
13044            }
13045        }
13046
13047        public class SchemesIterGenerator extends IterGenerator<String> {
13048            @Override
13049            public Iterator<String> generate(ActivityIntentInfo info) {
13050                return info.schemesIterator();
13051            }
13052        }
13053
13054        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13055            @Override
13056            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13057                return info.authoritiesIterator();
13058            }
13059        }
13060
13061        /**
13062         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13063         * MODIFIED. Do not pass in a list that should not be changed.
13064         */
13065        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13066                IterGenerator<T> generator, Iterator<T> searchIterator) {
13067            // loop through the set of actions; every one must be found in the intent filter
13068            while (searchIterator.hasNext()) {
13069                // we must have at least one filter in the list to consider a match
13070                if (intentList.size() == 0) {
13071                    break;
13072                }
13073
13074                final T searchAction = searchIterator.next();
13075
13076                // loop through the set of intent filters
13077                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13078                while (intentIter.hasNext()) {
13079                    final ActivityIntentInfo intentInfo = intentIter.next();
13080                    boolean selectionFound = false;
13081
13082                    // loop through the intent filter's selection criteria; at least one
13083                    // of them must match the searched criteria
13084                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13085                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13086                        final T intentSelection = intentSelectionIter.next();
13087                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13088                            selectionFound = true;
13089                            break;
13090                        }
13091                    }
13092
13093                    // the selection criteria wasn't found in this filter's set; this filter
13094                    // is not a potential match
13095                    if (!selectionFound) {
13096                        intentIter.remove();
13097                    }
13098                }
13099            }
13100        }
13101
13102        private boolean isProtectedAction(ActivityIntentInfo filter) {
13103            final Iterator<String> actionsIter = filter.actionsIterator();
13104            while (actionsIter != null && actionsIter.hasNext()) {
13105                final String filterAction = actionsIter.next();
13106                if (PROTECTED_ACTIONS.contains(filterAction)) {
13107                    return true;
13108                }
13109            }
13110            return false;
13111        }
13112
13113        /**
13114         * Adjusts the priority of the given intent filter according to policy.
13115         * <p>
13116         * <ul>
13117         * <li>The priority for non privileged applications is capped to '0'</li>
13118         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13119         * <li>The priority for unbundled updates to privileged applications is capped to the
13120         *      priority defined on the system partition</li>
13121         * </ul>
13122         * <p>
13123         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13124         * allowed to obtain any priority on any action.
13125         */
13126        private void adjustPriority(
13127                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13128            // nothing to do; priority is fine as-is
13129            if (intent.getPriority() <= 0) {
13130                return;
13131            }
13132
13133            final ActivityInfo activityInfo = intent.activity.info;
13134            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13135
13136            final boolean privilegedApp =
13137                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13138            if (!privilegedApp) {
13139                // non-privileged applications can never define a priority >0
13140                if (DEBUG_FILTERS) {
13141                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13142                            + " package: " + applicationInfo.packageName
13143                            + " activity: " + intent.activity.className
13144                            + " origPrio: " + intent.getPriority());
13145                }
13146                intent.setPriority(0);
13147                return;
13148            }
13149
13150            if (systemActivities == null) {
13151                // the system package is not disabled; we're parsing the system partition
13152                if (isProtectedAction(intent)) {
13153                    if (mDeferProtectedFilters) {
13154                        // We can't deal with these just yet. No component should ever obtain a
13155                        // >0 priority for a protected actions, with ONE exception -- the setup
13156                        // wizard. The setup wizard, however, cannot be known until we're able to
13157                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13158                        // until all intent filters have been processed. Chicken, meet egg.
13159                        // Let the filter temporarily have a high priority and rectify the
13160                        // priorities after all system packages have been scanned.
13161                        mProtectedFilters.add(intent);
13162                        if (DEBUG_FILTERS) {
13163                            Slog.i(TAG, "Protected action; save for later;"
13164                                    + " package: " + applicationInfo.packageName
13165                                    + " activity: " + intent.activity.className
13166                                    + " origPrio: " + intent.getPriority());
13167                        }
13168                        return;
13169                    } else {
13170                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13171                            Slog.i(TAG, "No setup wizard;"
13172                                + " All protected intents capped to priority 0");
13173                        }
13174                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13175                            if (DEBUG_FILTERS) {
13176                                Slog.i(TAG, "Found setup wizard;"
13177                                    + " allow priority " + intent.getPriority() + ";"
13178                                    + " package: " + intent.activity.info.packageName
13179                                    + " activity: " + intent.activity.className
13180                                    + " priority: " + intent.getPriority());
13181                            }
13182                            // setup wizard gets whatever it wants
13183                            return;
13184                        }
13185                        if (DEBUG_FILTERS) {
13186                            Slog.i(TAG, "Protected action; cap priority to 0;"
13187                                    + " package: " + intent.activity.info.packageName
13188                                    + " activity: " + intent.activity.className
13189                                    + " origPrio: " + intent.getPriority());
13190                        }
13191                        intent.setPriority(0);
13192                        return;
13193                    }
13194                }
13195                // privileged apps on the system image get whatever priority they request
13196                return;
13197            }
13198
13199            // privileged app unbundled update ... try to find the same activity
13200            final PackageParser.Activity foundActivity =
13201                    findMatchingActivity(systemActivities, activityInfo);
13202            if (foundActivity == null) {
13203                // this is a new activity; it cannot obtain >0 priority
13204                if (DEBUG_FILTERS) {
13205                    Slog.i(TAG, "New activity; cap priority to 0;"
13206                            + " package: " + applicationInfo.packageName
13207                            + " activity: " + intent.activity.className
13208                            + " origPrio: " + intent.getPriority());
13209                }
13210                intent.setPriority(0);
13211                return;
13212            }
13213
13214            // found activity, now check for filter equivalence
13215
13216            // a shallow copy is enough; we modify the list, not its contents
13217            final List<ActivityIntentInfo> intentListCopy =
13218                    new ArrayList<>(foundActivity.intents);
13219            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13220
13221            // find matching action subsets
13222            final Iterator<String> actionsIterator = intent.actionsIterator();
13223            if (actionsIterator != null) {
13224                getIntentListSubset(
13225                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13226                if (intentListCopy.size() == 0) {
13227                    // no more intents to match; we're not equivalent
13228                    if (DEBUG_FILTERS) {
13229                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13230                                + " package: " + applicationInfo.packageName
13231                                + " activity: " + intent.activity.className
13232                                + " origPrio: " + intent.getPriority());
13233                    }
13234                    intent.setPriority(0);
13235                    return;
13236                }
13237            }
13238
13239            // find matching category subsets
13240            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13241            if (categoriesIterator != null) {
13242                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13243                        categoriesIterator);
13244                if (intentListCopy.size() == 0) {
13245                    // no more intents to match; we're not equivalent
13246                    if (DEBUG_FILTERS) {
13247                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13248                                + " package: " + applicationInfo.packageName
13249                                + " activity: " + intent.activity.className
13250                                + " origPrio: " + intent.getPriority());
13251                    }
13252                    intent.setPriority(0);
13253                    return;
13254                }
13255            }
13256
13257            // find matching schemes subsets
13258            final Iterator<String> schemesIterator = intent.schemesIterator();
13259            if (schemesIterator != null) {
13260                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13261                        schemesIterator);
13262                if (intentListCopy.size() == 0) {
13263                    // no more intents to match; we're not equivalent
13264                    if (DEBUG_FILTERS) {
13265                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13266                                + " package: " + applicationInfo.packageName
13267                                + " activity: " + intent.activity.className
13268                                + " origPrio: " + intent.getPriority());
13269                    }
13270                    intent.setPriority(0);
13271                    return;
13272                }
13273            }
13274
13275            // find matching authorities subsets
13276            final Iterator<IntentFilter.AuthorityEntry>
13277                    authoritiesIterator = intent.authoritiesIterator();
13278            if (authoritiesIterator != null) {
13279                getIntentListSubset(intentListCopy,
13280                        new AuthoritiesIterGenerator(),
13281                        authoritiesIterator);
13282                if (intentListCopy.size() == 0) {
13283                    // no more intents to match; we're not equivalent
13284                    if (DEBUG_FILTERS) {
13285                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13286                                + " package: " + applicationInfo.packageName
13287                                + " activity: " + intent.activity.className
13288                                + " origPrio: " + intent.getPriority());
13289                    }
13290                    intent.setPriority(0);
13291                    return;
13292                }
13293            }
13294
13295            // we found matching filter(s); app gets the max priority of all intents
13296            int cappedPriority = 0;
13297            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13298                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13299            }
13300            if (intent.getPriority() > cappedPriority) {
13301                if (DEBUG_FILTERS) {
13302                    Slog.i(TAG, "Found matching filter(s);"
13303                            + " cap priority to " + cappedPriority + ";"
13304                            + " package: " + applicationInfo.packageName
13305                            + " activity: " + intent.activity.className
13306                            + " origPrio: " + intent.getPriority());
13307                }
13308                intent.setPriority(cappedPriority);
13309                return;
13310            }
13311            // all this for nothing; the requested priority was <= what was on the system
13312        }
13313
13314        public final void addActivity(PackageParser.Activity a, String type) {
13315            mActivities.put(a.getComponentName(), a);
13316            if (DEBUG_SHOW_INFO)
13317                Log.v(
13318                TAG, "  " + type + " " +
13319                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13320            if (DEBUG_SHOW_INFO)
13321                Log.v(TAG, "    Class=" + a.info.name);
13322            final int NI = a.intents.size();
13323            for (int j=0; j<NI; j++) {
13324                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13325                if ("activity".equals(type)) {
13326                    final PackageSetting ps =
13327                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13328                    final List<PackageParser.Activity> systemActivities =
13329                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13330                    adjustPriority(systemActivities, intent);
13331                }
13332                if (DEBUG_SHOW_INFO) {
13333                    Log.v(TAG, "    IntentFilter:");
13334                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13335                }
13336                if (!intent.debugCheck()) {
13337                    Log.w(TAG, "==> For Activity " + a.info.name);
13338                }
13339                addFilter(intent);
13340            }
13341        }
13342
13343        public final void removeActivity(PackageParser.Activity a, String type) {
13344            mActivities.remove(a.getComponentName());
13345            if (DEBUG_SHOW_INFO) {
13346                Log.v(TAG, "  " + type + " "
13347                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13348                                : a.info.name) + ":");
13349                Log.v(TAG, "    Class=" + a.info.name);
13350            }
13351            final int NI = a.intents.size();
13352            for (int j=0; j<NI; j++) {
13353                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13354                if (DEBUG_SHOW_INFO) {
13355                    Log.v(TAG, "    IntentFilter:");
13356                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13357                }
13358                removeFilter(intent);
13359            }
13360        }
13361
13362        @Override
13363        protected boolean allowFilterResult(
13364                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13365            ActivityInfo filterAi = filter.activity.info;
13366            for (int i=dest.size()-1; i>=0; i--) {
13367                ActivityInfo destAi = dest.get(i).activityInfo;
13368                if (destAi.name == filterAi.name
13369                        && destAi.packageName == filterAi.packageName) {
13370                    return false;
13371                }
13372            }
13373            return true;
13374        }
13375
13376        @Override
13377        protected ActivityIntentInfo[] newArray(int size) {
13378            return new ActivityIntentInfo[size];
13379        }
13380
13381        @Override
13382        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13383            if (!sUserManager.exists(userId)) return true;
13384            PackageParser.Package p = filter.activity.owner;
13385            if (p != null) {
13386                PackageSetting ps = (PackageSetting)p.mExtras;
13387                if (ps != null) {
13388                    // System apps are never considered stopped for purposes of
13389                    // filtering, because there may be no way for the user to
13390                    // actually re-launch them.
13391                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13392                            && ps.getStopped(userId);
13393                }
13394            }
13395            return false;
13396        }
13397
13398        @Override
13399        protected boolean isPackageForFilter(String packageName,
13400                PackageParser.ActivityIntentInfo info) {
13401            return packageName.equals(info.activity.owner.packageName);
13402        }
13403
13404        @Override
13405        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13406                int match, int userId) {
13407            if (!sUserManager.exists(userId)) return null;
13408            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13409                return null;
13410            }
13411            final PackageParser.Activity activity = info.activity;
13412            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13413            if (ps == null) {
13414                return null;
13415            }
13416            final PackageUserState userState = ps.readUserState(userId);
13417            ActivityInfo ai =
13418                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13419            if (ai == null) {
13420                return null;
13421            }
13422            final boolean matchExplicitlyVisibleOnly =
13423                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13424            final boolean matchVisibleToInstantApp =
13425                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13426            final boolean componentVisible =
13427                    matchVisibleToInstantApp
13428                    && info.isVisibleToInstantApp()
13429                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13430            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13431            // throw out filters that aren't visible to ephemeral apps
13432            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13433                return null;
13434            }
13435            // throw out instant app filters if we're not explicitly requesting them
13436            if (!matchInstantApp && userState.instantApp) {
13437                return null;
13438            }
13439            // throw out instant app filters if updates are available; will trigger
13440            // instant app resolution
13441            if (userState.instantApp && ps.isUpdateAvailable()) {
13442                return null;
13443            }
13444            final ResolveInfo res = new ResolveInfo();
13445            res.activityInfo = ai;
13446            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13447                res.filter = info;
13448            }
13449            if (info != null) {
13450                res.handleAllWebDataURI = info.handleAllWebDataURI();
13451            }
13452            res.priority = info.getPriority();
13453            res.preferredOrder = activity.owner.mPreferredOrder;
13454            //System.out.println("Result: " + res.activityInfo.className +
13455            //                   " = " + res.priority);
13456            res.match = match;
13457            res.isDefault = info.hasDefault;
13458            res.labelRes = info.labelRes;
13459            res.nonLocalizedLabel = info.nonLocalizedLabel;
13460            if (userNeedsBadging(userId)) {
13461                res.noResourceId = true;
13462            } else {
13463                res.icon = info.icon;
13464            }
13465            res.iconResourceId = info.icon;
13466            res.system = res.activityInfo.applicationInfo.isSystemApp();
13467            res.isInstantAppAvailable = userState.instantApp;
13468            return res;
13469        }
13470
13471        @Override
13472        protected void sortResults(List<ResolveInfo> results) {
13473            Collections.sort(results, mResolvePrioritySorter);
13474        }
13475
13476        @Override
13477        protected void dumpFilter(PrintWriter out, String prefix,
13478                PackageParser.ActivityIntentInfo filter) {
13479            out.print(prefix); out.print(
13480                    Integer.toHexString(System.identityHashCode(filter.activity)));
13481                    out.print(' ');
13482                    filter.activity.printComponentShortName(out);
13483                    out.print(" filter ");
13484                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13485        }
13486
13487        @Override
13488        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13489            return filter.activity;
13490        }
13491
13492        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13493            PackageParser.Activity activity = (PackageParser.Activity)label;
13494            out.print(prefix); out.print(
13495                    Integer.toHexString(System.identityHashCode(activity)));
13496                    out.print(' ');
13497                    activity.printComponentShortName(out);
13498            if (count > 1) {
13499                out.print(" ("); out.print(count); out.print(" filters)");
13500            }
13501            out.println();
13502        }
13503
13504        // Keys are String (activity class name), values are Activity.
13505        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13506                = new ArrayMap<ComponentName, PackageParser.Activity>();
13507        private int mFlags;
13508    }
13509
13510    private final class ServiceIntentResolver
13511            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13512        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13513                boolean defaultOnly, int userId) {
13514            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13515            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13516        }
13517
13518        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13519                int userId) {
13520            if (!sUserManager.exists(userId)) return null;
13521            mFlags = flags;
13522            return super.queryIntent(intent, resolvedType,
13523                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13524                    userId);
13525        }
13526
13527        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13528                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13529            if (!sUserManager.exists(userId)) return null;
13530            if (packageServices == null) {
13531                return null;
13532            }
13533            mFlags = flags;
13534            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13535            final int N = packageServices.size();
13536            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13537                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13538
13539            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13540            for (int i = 0; i < N; ++i) {
13541                intentFilters = packageServices.get(i).intents;
13542                if (intentFilters != null && intentFilters.size() > 0) {
13543                    PackageParser.ServiceIntentInfo[] array =
13544                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13545                    intentFilters.toArray(array);
13546                    listCut.add(array);
13547                }
13548            }
13549            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13550        }
13551
13552        public final void addService(PackageParser.Service s) {
13553            mServices.put(s.getComponentName(), s);
13554            if (DEBUG_SHOW_INFO) {
13555                Log.v(TAG, "  "
13556                        + (s.info.nonLocalizedLabel != null
13557                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13558                Log.v(TAG, "    Class=" + s.info.name);
13559            }
13560            final int NI = s.intents.size();
13561            int j;
13562            for (j=0; j<NI; j++) {
13563                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13564                if (DEBUG_SHOW_INFO) {
13565                    Log.v(TAG, "    IntentFilter:");
13566                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13567                }
13568                if (!intent.debugCheck()) {
13569                    Log.w(TAG, "==> For Service " + s.info.name);
13570                }
13571                addFilter(intent);
13572            }
13573        }
13574
13575        public final void removeService(PackageParser.Service s) {
13576            mServices.remove(s.getComponentName());
13577            if (DEBUG_SHOW_INFO) {
13578                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13579                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13580                Log.v(TAG, "    Class=" + s.info.name);
13581            }
13582            final int NI = s.intents.size();
13583            int j;
13584            for (j=0; j<NI; j++) {
13585                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13586                if (DEBUG_SHOW_INFO) {
13587                    Log.v(TAG, "    IntentFilter:");
13588                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13589                }
13590                removeFilter(intent);
13591            }
13592        }
13593
13594        @Override
13595        protected boolean allowFilterResult(
13596                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13597            ServiceInfo filterSi = filter.service.info;
13598            for (int i=dest.size()-1; i>=0; i--) {
13599                ServiceInfo destAi = dest.get(i).serviceInfo;
13600                if (destAi.name == filterSi.name
13601                        && destAi.packageName == filterSi.packageName) {
13602                    return false;
13603                }
13604            }
13605            return true;
13606        }
13607
13608        @Override
13609        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13610            return new PackageParser.ServiceIntentInfo[size];
13611        }
13612
13613        @Override
13614        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13615            if (!sUserManager.exists(userId)) return true;
13616            PackageParser.Package p = filter.service.owner;
13617            if (p != null) {
13618                PackageSetting ps = (PackageSetting)p.mExtras;
13619                if (ps != null) {
13620                    // System apps are never considered stopped for purposes of
13621                    // filtering, because there may be no way for the user to
13622                    // actually re-launch them.
13623                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13624                            && ps.getStopped(userId);
13625                }
13626            }
13627            return false;
13628        }
13629
13630        @Override
13631        protected boolean isPackageForFilter(String packageName,
13632                PackageParser.ServiceIntentInfo info) {
13633            return packageName.equals(info.service.owner.packageName);
13634        }
13635
13636        @Override
13637        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13638                int match, int userId) {
13639            if (!sUserManager.exists(userId)) return null;
13640            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13641            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13642                return null;
13643            }
13644            final PackageParser.Service service = info.service;
13645            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13646            if (ps == null) {
13647                return null;
13648            }
13649            final PackageUserState userState = ps.readUserState(userId);
13650            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13651                    userState, userId);
13652            if (si == null) {
13653                return null;
13654            }
13655            final boolean matchVisibleToInstantApp =
13656                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13657            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13658            // throw out filters that aren't visible to ephemeral apps
13659            if (matchVisibleToInstantApp
13660                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13661                return null;
13662            }
13663            // throw out ephemeral filters if we're not explicitly requesting them
13664            if (!isInstantApp && userState.instantApp) {
13665                return null;
13666            }
13667            // throw out instant app filters if updates are available; will trigger
13668            // instant app resolution
13669            if (userState.instantApp && ps.isUpdateAvailable()) {
13670                return null;
13671            }
13672            final ResolveInfo res = new ResolveInfo();
13673            res.serviceInfo = si;
13674            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13675                res.filter = filter;
13676            }
13677            res.priority = info.getPriority();
13678            res.preferredOrder = service.owner.mPreferredOrder;
13679            res.match = match;
13680            res.isDefault = info.hasDefault;
13681            res.labelRes = info.labelRes;
13682            res.nonLocalizedLabel = info.nonLocalizedLabel;
13683            res.icon = info.icon;
13684            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13685            return res;
13686        }
13687
13688        @Override
13689        protected void sortResults(List<ResolveInfo> results) {
13690            Collections.sort(results, mResolvePrioritySorter);
13691        }
13692
13693        @Override
13694        protected void dumpFilter(PrintWriter out, String prefix,
13695                PackageParser.ServiceIntentInfo filter) {
13696            out.print(prefix); out.print(
13697                    Integer.toHexString(System.identityHashCode(filter.service)));
13698                    out.print(' ');
13699                    filter.service.printComponentShortName(out);
13700                    out.print(" filter ");
13701                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13702        }
13703
13704        @Override
13705        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13706            return filter.service;
13707        }
13708
13709        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13710            PackageParser.Service service = (PackageParser.Service)label;
13711            out.print(prefix); out.print(
13712                    Integer.toHexString(System.identityHashCode(service)));
13713                    out.print(' ');
13714                    service.printComponentShortName(out);
13715            if (count > 1) {
13716                out.print(" ("); out.print(count); out.print(" filters)");
13717            }
13718            out.println();
13719        }
13720
13721//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13722//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13723//            final List<ResolveInfo> retList = Lists.newArrayList();
13724//            while (i.hasNext()) {
13725//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13726//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13727//                    retList.add(resolveInfo);
13728//                }
13729//            }
13730//            return retList;
13731//        }
13732
13733        // Keys are String (activity class name), values are Activity.
13734        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13735                = new ArrayMap<ComponentName, PackageParser.Service>();
13736        private int mFlags;
13737    }
13738
13739    private final class ProviderIntentResolver
13740            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13741        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13742                boolean defaultOnly, int userId) {
13743            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13744            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13745        }
13746
13747        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13748                int userId) {
13749            if (!sUserManager.exists(userId))
13750                return null;
13751            mFlags = flags;
13752            return super.queryIntent(intent, resolvedType,
13753                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13754                    userId);
13755        }
13756
13757        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13758                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13759            if (!sUserManager.exists(userId))
13760                return null;
13761            if (packageProviders == null) {
13762                return null;
13763            }
13764            mFlags = flags;
13765            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13766            final int N = packageProviders.size();
13767            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13768                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13769
13770            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13771            for (int i = 0; i < N; ++i) {
13772                intentFilters = packageProviders.get(i).intents;
13773                if (intentFilters != null && intentFilters.size() > 0) {
13774                    PackageParser.ProviderIntentInfo[] array =
13775                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13776                    intentFilters.toArray(array);
13777                    listCut.add(array);
13778                }
13779            }
13780            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13781        }
13782
13783        public final void addProvider(PackageParser.Provider p) {
13784            if (mProviders.containsKey(p.getComponentName())) {
13785                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13786                return;
13787            }
13788
13789            mProviders.put(p.getComponentName(), p);
13790            if (DEBUG_SHOW_INFO) {
13791                Log.v(TAG, "  "
13792                        + (p.info.nonLocalizedLabel != null
13793                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13794                Log.v(TAG, "    Class=" + p.info.name);
13795            }
13796            final int NI = p.intents.size();
13797            int j;
13798            for (j = 0; j < NI; j++) {
13799                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13800                if (DEBUG_SHOW_INFO) {
13801                    Log.v(TAG, "    IntentFilter:");
13802                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13803                }
13804                if (!intent.debugCheck()) {
13805                    Log.w(TAG, "==> For Provider " + p.info.name);
13806                }
13807                addFilter(intent);
13808            }
13809        }
13810
13811        public final void removeProvider(PackageParser.Provider p) {
13812            mProviders.remove(p.getComponentName());
13813            if (DEBUG_SHOW_INFO) {
13814                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13815                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13816                Log.v(TAG, "    Class=" + p.info.name);
13817            }
13818            final int NI = p.intents.size();
13819            int j;
13820            for (j = 0; j < NI; j++) {
13821                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13822                if (DEBUG_SHOW_INFO) {
13823                    Log.v(TAG, "    IntentFilter:");
13824                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13825                }
13826                removeFilter(intent);
13827            }
13828        }
13829
13830        @Override
13831        protected boolean allowFilterResult(
13832                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13833            ProviderInfo filterPi = filter.provider.info;
13834            for (int i = dest.size() - 1; i >= 0; i--) {
13835                ProviderInfo destPi = dest.get(i).providerInfo;
13836                if (destPi.name == filterPi.name
13837                        && destPi.packageName == filterPi.packageName) {
13838                    return false;
13839                }
13840            }
13841            return true;
13842        }
13843
13844        @Override
13845        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13846            return new PackageParser.ProviderIntentInfo[size];
13847        }
13848
13849        @Override
13850        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13851            if (!sUserManager.exists(userId))
13852                return true;
13853            PackageParser.Package p = filter.provider.owner;
13854            if (p != null) {
13855                PackageSetting ps = (PackageSetting) p.mExtras;
13856                if (ps != null) {
13857                    // System apps are never considered stopped for purposes of
13858                    // filtering, because there may be no way for the user to
13859                    // actually re-launch them.
13860                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13861                            && ps.getStopped(userId);
13862                }
13863            }
13864            return false;
13865        }
13866
13867        @Override
13868        protected boolean isPackageForFilter(String packageName,
13869                PackageParser.ProviderIntentInfo info) {
13870            return packageName.equals(info.provider.owner.packageName);
13871        }
13872
13873        @Override
13874        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13875                int match, int userId) {
13876            if (!sUserManager.exists(userId))
13877                return null;
13878            final PackageParser.ProviderIntentInfo info = filter;
13879            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13880                return null;
13881            }
13882            final PackageParser.Provider provider = info.provider;
13883            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13884            if (ps == null) {
13885                return null;
13886            }
13887            final PackageUserState userState = ps.readUserState(userId);
13888            final boolean matchVisibleToInstantApp =
13889                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13890            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13891            // throw out filters that aren't visible to instant applications
13892            if (matchVisibleToInstantApp
13893                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13894                return null;
13895            }
13896            // throw out instant application filters if we're not explicitly requesting them
13897            if (!isInstantApp && userState.instantApp) {
13898                return null;
13899            }
13900            // throw out instant application filters if updates are available; will trigger
13901            // instant application resolution
13902            if (userState.instantApp && ps.isUpdateAvailable()) {
13903                return null;
13904            }
13905            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13906                    userState, userId);
13907            if (pi == null) {
13908                return null;
13909            }
13910            final ResolveInfo res = new ResolveInfo();
13911            res.providerInfo = pi;
13912            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13913                res.filter = filter;
13914            }
13915            res.priority = info.getPriority();
13916            res.preferredOrder = provider.owner.mPreferredOrder;
13917            res.match = match;
13918            res.isDefault = info.hasDefault;
13919            res.labelRes = info.labelRes;
13920            res.nonLocalizedLabel = info.nonLocalizedLabel;
13921            res.icon = info.icon;
13922            res.system = res.providerInfo.applicationInfo.isSystemApp();
13923            return res;
13924        }
13925
13926        @Override
13927        protected void sortResults(List<ResolveInfo> results) {
13928            Collections.sort(results, mResolvePrioritySorter);
13929        }
13930
13931        @Override
13932        protected void dumpFilter(PrintWriter out, String prefix,
13933                PackageParser.ProviderIntentInfo filter) {
13934            out.print(prefix);
13935            out.print(
13936                    Integer.toHexString(System.identityHashCode(filter.provider)));
13937            out.print(' ');
13938            filter.provider.printComponentShortName(out);
13939            out.print(" filter ");
13940            out.println(Integer.toHexString(System.identityHashCode(filter)));
13941        }
13942
13943        @Override
13944        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13945            return filter.provider;
13946        }
13947
13948        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13949            PackageParser.Provider provider = (PackageParser.Provider)label;
13950            out.print(prefix); out.print(
13951                    Integer.toHexString(System.identityHashCode(provider)));
13952                    out.print(' ');
13953                    provider.printComponentShortName(out);
13954            if (count > 1) {
13955                out.print(" ("); out.print(count); out.print(" filters)");
13956            }
13957            out.println();
13958        }
13959
13960        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13961                = new ArrayMap<ComponentName, PackageParser.Provider>();
13962        private int mFlags;
13963    }
13964
13965    static final class EphemeralIntentResolver
13966            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13967        /**
13968         * The result that has the highest defined order. Ordering applies on a
13969         * per-package basis. Mapping is from package name to Pair of order and
13970         * EphemeralResolveInfo.
13971         * <p>
13972         * NOTE: This is implemented as a field variable for convenience and efficiency.
13973         * By having a field variable, we're able to track filter ordering as soon as
13974         * a non-zero order is defined. Otherwise, multiple loops across the result set
13975         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13976         * this needs to be contained entirely within {@link #filterResults}.
13977         */
13978        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13979
13980        @Override
13981        protected AuxiliaryResolveInfo[] newArray(int size) {
13982            return new AuxiliaryResolveInfo[size];
13983        }
13984
13985        @Override
13986        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13987            return true;
13988        }
13989
13990        @Override
13991        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13992                int userId) {
13993            if (!sUserManager.exists(userId)) {
13994                return null;
13995            }
13996            final String packageName = responseObj.resolveInfo.getPackageName();
13997            final Integer order = responseObj.getOrder();
13998            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13999                    mOrderResult.get(packageName);
14000            // ordering is enabled and this item's order isn't high enough
14001            if (lastOrderResult != null && lastOrderResult.first >= order) {
14002                return null;
14003            }
14004            final InstantAppResolveInfo res = responseObj.resolveInfo;
14005            if (order > 0) {
14006                // non-zero order, enable ordering
14007                mOrderResult.put(packageName, new Pair<>(order, res));
14008            }
14009            return responseObj;
14010        }
14011
14012        @Override
14013        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14014            // only do work if ordering is enabled [most of the time it won't be]
14015            if (mOrderResult.size() == 0) {
14016                return;
14017            }
14018            int resultSize = results.size();
14019            for (int i = 0; i < resultSize; i++) {
14020                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14021                final String packageName = info.getPackageName();
14022                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14023                if (savedInfo == null) {
14024                    // package doesn't having ordering
14025                    continue;
14026                }
14027                if (savedInfo.second == info) {
14028                    // circled back to the highest ordered item; remove from order list
14029                    mOrderResult.remove(savedInfo);
14030                    if (mOrderResult.size() == 0) {
14031                        // no more ordered items
14032                        break;
14033                    }
14034                    continue;
14035                }
14036                // item has a worse order, remove it from the result list
14037                results.remove(i);
14038                resultSize--;
14039                i--;
14040            }
14041        }
14042    }
14043
14044    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14045            new Comparator<ResolveInfo>() {
14046        public int compare(ResolveInfo r1, ResolveInfo r2) {
14047            int v1 = r1.priority;
14048            int v2 = r2.priority;
14049            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14050            if (v1 != v2) {
14051                return (v1 > v2) ? -1 : 1;
14052            }
14053            v1 = r1.preferredOrder;
14054            v2 = r2.preferredOrder;
14055            if (v1 != v2) {
14056                return (v1 > v2) ? -1 : 1;
14057            }
14058            if (r1.isDefault != r2.isDefault) {
14059                return r1.isDefault ? -1 : 1;
14060            }
14061            v1 = r1.match;
14062            v2 = r2.match;
14063            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14064            if (v1 != v2) {
14065                return (v1 > v2) ? -1 : 1;
14066            }
14067            if (r1.system != r2.system) {
14068                return r1.system ? -1 : 1;
14069            }
14070            if (r1.activityInfo != null) {
14071                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14072            }
14073            if (r1.serviceInfo != null) {
14074                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14075            }
14076            if (r1.providerInfo != null) {
14077                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14078            }
14079            return 0;
14080        }
14081    };
14082
14083    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14084            new Comparator<ProviderInfo>() {
14085        public int compare(ProviderInfo p1, ProviderInfo p2) {
14086            final int v1 = p1.initOrder;
14087            final int v2 = p2.initOrder;
14088            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14089        }
14090    };
14091
14092    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14093            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14094            final int[] userIds) {
14095        mHandler.post(new Runnable() {
14096            @Override
14097            public void run() {
14098                try {
14099                    final IActivityManager am = ActivityManager.getService();
14100                    if (am == null) return;
14101                    final int[] resolvedUserIds;
14102                    if (userIds == null) {
14103                        resolvedUserIds = am.getRunningUserIds();
14104                    } else {
14105                        resolvedUserIds = userIds;
14106                    }
14107                    for (int id : resolvedUserIds) {
14108                        final Intent intent = new Intent(action,
14109                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14110                        if (extras != null) {
14111                            intent.putExtras(extras);
14112                        }
14113                        if (targetPkg != null) {
14114                            intent.setPackage(targetPkg);
14115                        }
14116                        // Modify the UID when posting to other users
14117                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14118                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14119                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14120                            intent.putExtra(Intent.EXTRA_UID, uid);
14121                        }
14122                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14123                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14124                        if (DEBUG_BROADCASTS) {
14125                            RuntimeException here = new RuntimeException("here");
14126                            here.fillInStackTrace();
14127                            Slog.d(TAG, "Sending to user " + id + ": "
14128                                    + intent.toShortString(false, true, false, false)
14129                                    + " " + intent.getExtras(), here);
14130                        }
14131                        am.broadcastIntent(null, intent, null, finishedReceiver,
14132                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14133                                null, finishedReceiver != null, false, id);
14134                    }
14135                } catch (RemoteException ex) {
14136                }
14137            }
14138        });
14139    }
14140
14141    /**
14142     * Check if the external storage media is available. This is true if there
14143     * is a mounted external storage medium or if the external storage is
14144     * emulated.
14145     */
14146    private boolean isExternalMediaAvailable() {
14147        return mMediaMounted || Environment.isExternalStorageEmulated();
14148    }
14149
14150    @Override
14151    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14152        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14153            return null;
14154        }
14155        // writer
14156        synchronized (mPackages) {
14157            if (!isExternalMediaAvailable()) {
14158                // If the external storage is no longer mounted at this point,
14159                // the caller may not have been able to delete all of this
14160                // packages files and can not delete any more.  Bail.
14161                return null;
14162            }
14163            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14164            if (lastPackage != null) {
14165                pkgs.remove(lastPackage);
14166            }
14167            if (pkgs.size() > 0) {
14168                return pkgs.get(0);
14169            }
14170        }
14171        return null;
14172    }
14173
14174    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14175        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14176                userId, andCode ? 1 : 0, packageName);
14177        if (mSystemReady) {
14178            msg.sendToTarget();
14179        } else {
14180            if (mPostSystemReadyMessages == null) {
14181                mPostSystemReadyMessages = new ArrayList<>();
14182            }
14183            mPostSystemReadyMessages.add(msg);
14184        }
14185    }
14186
14187    void startCleaningPackages() {
14188        // reader
14189        if (!isExternalMediaAvailable()) {
14190            return;
14191        }
14192        synchronized (mPackages) {
14193            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14194                return;
14195            }
14196        }
14197        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14198        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14199        IActivityManager am = ActivityManager.getService();
14200        if (am != null) {
14201            int dcsUid = -1;
14202            synchronized (mPackages) {
14203                if (!mDefaultContainerWhitelisted) {
14204                    mDefaultContainerWhitelisted = true;
14205                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14206                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14207                }
14208            }
14209            try {
14210                if (dcsUid > 0) {
14211                    am.backgroundWhitelistUid(dcsUid);
14212                }
14213                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14214                        UserHandle.USER_SYSTEM);
14215            } catch (RemoteException e) {
14216            }
14217        }
14218    }
14219
14220    @Override
14221    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14222            int installFlags, String installerPackageName, int userId) {
14223        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14224
14225        final int callingUid = Binder.getCallingUid();
14226        enforceCrossUserPermission(callingUid, userId,
14227                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14228
14229        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14230            try {
14231                if (observer != null) {
14232                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14233                }
14234            } catch (RemoteException re) {
14235            }
14236            return;
14237        }
14238
14239        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14240            installFlags |= PackageManager.INSTALL_FROM_ADB;
14241
14242        } else {
14243            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14244            // about installerPackageName.
14245
14246            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14247            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14248        }
14249
14250        UserHandle user;
14251        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14252            user = UserHandle.ALL;
14253        } else {
14254            user = new UserHandle(userId);
14255        }
14256
14257        // Only system components can circumvent runtime permissions when installing.
14258        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14259                && mContext.checkCallingOrSelfPermission(Manifest.permission
14260                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14261            throw new SecurityException("You need the "
14262                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14263                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14264        }
14265
14266        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14267                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14268            throw new IllegalArgumentException(
14269                    "New installs into ASEC containers no longer supported");
14270        }
14271
14272        final File originFile = new File(originPath);
14273        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14274
14275        final Message msg = mHandler.obtainMessage(INIT_COPY);
14276        final VerificationInfo verificationInfo = new VerificationInfo(
14277                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14278        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14279                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14280                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14281                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14282        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14283        msg.obj = params;
14284
14285        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14286                System.identityHashCode(msg.obj));
14287        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14288                System.identityHashCode(msg.obj));
14289
14290        mHandler.sendMessage(msg);
14291    }
14292
14293
14294    /**
14295     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14296     * it is acting on behalf on an enterprise or the user).
14297     *
14298     * Note that the ordering of the conditionals in this method is important. The checks we perform
14299     * are as follows, in this order:
14300     *
14301     * 1) If the install is being performed by a system app, we can trust the app to have set the
14302     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14303     *    what it is.
14304     * 2) If the install is being performed by a device or profile owner app, the install reason
14305     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14306     *    set the install reason correctly. If the app targets an older SDK version where install
14307     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14308     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14309     * 3) In all other cases, the install is being performed by a regular app that is neither part
14310     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14311     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14312     *    set to enterprise policy and if so, change it to unknown instead.
14313     */
14314    private int fixUpInstallReason(String installerPackageName, int installerUid,
14315            int installReason) {
14316        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14317                == PERMISSION_GRANTED) {
14318            // If the install is being performed by a system app, we trust that app to have set the
14319            // install reason correctly.
14320            return installReason;
14321        }
14322
14323        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14324            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14325        if (dpm != null) {
14326            ComponentName owner = null;
14327            try {
14328                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14329                if (owner == null) {
14330                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14331                }
14332            } catch (RemoteException e) {
14333            }
14334            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14335                // If the install is being performed by a device or profile owner, the install
14336                // reason should be enterprise policy.
14337                return PackageManager.INSTALL_REASON_POLICY;
14338            }
14339        }
14340
14341        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14342            // If the install is being performed by a regular app (i.e. neither system app nor
14343            // device or profile owner), we have no reason to believe that the app is acting on
14344            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14345            // change it to unknown instead.
14346            return PackageManager.INSTALL_REASON_UNKNOWN;
14347        }
14348
14349        // If the install is being performed by a regular app and the install reason was set to any
14350        // value but enterprise policy, leave the install reason unchanged.
14351        return installReason;
14352    }
14353
14354    void installStage(String packageName, File stagedDir, String stagedCid,
14355            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14356            String installerPackageName, int installerUid, UserHandle user,
14357            Certificate[][] certificates) {
14358        if (DEBUG_EPHEMERAL) {
14359            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14360                Slog.d(TAG, "Ephemeral install of " + packageName);
14361            }
14362        }
14363        final VerificationInfo verificationInfo = new VerificationInfo(
14364                sessionParams.originatingUri, sessionParams.referrerUri,
14365                sessionParams.originatingUid, installerUid);
14366
14367        final OriginInfo origin;
14368        if (stagedDir != null) {
14369            origin = OriginInfo.fromStagedFile(stagedDir);
14370        } else {
14371            origin = OriginInfo.fromStagedContainer(stagedCid);
14372        }
14373
14374        final Message msg = mHandler.obtainMessage(INIT_COPY);
14375        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14376                sessionParams.installReason);
14377        final InstallParams params = new InstallParams(origin, null, observer,
14378                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14379                verificationInfo, user, sessionParams.abiOverride,
14380                sessionParams.grantedRuntimePermissions, certificates, installReason);
14381        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14382        msg.obj = params;
14383
14384        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14385                System.identityHashCode(msg.obj));
14386        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14387                System.identityHashCode(msg.obj));
14388
14389        mHandler.sendMessage(msg);
14390    }
14391
14392    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14393            int userId) {
14394        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14395        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14396
14397        // Send a session commit broadcast
14398        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14399        info.installReason = pkgSetting.getInstallReason(userId);
14400        info.appPackageName = packageName;
14401        sendSessionCommitBroadcast(info, userId);
14402    }
14403
14404    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14405        if (ArrayUtils.isEmpty(userIds)) {
14406            return;
14407        }
14408        Bundle extras = new Bundle(1);
14409        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14410        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14411
14412        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14413                packageName, extras, 0, null, null, userIds);
14414        if (isSystem) {
14415            mHandler.post(() -> {
14416                        for (int userId : userIds) {
14417                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14418                        }
14419                    }
14420            );
14421        }
14422    }
14423
14424    /**
14425     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14426     * automatically without needing an explicit launch.
14427     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14428     */
14429    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14430        // If user is not running, the app didn't miss any broadcast
14431        if (!mUserManagerInternal.isUserRunning(userId)) {
14432            return;
14433        }
14434        final IActivityManager am = ActivityManager.getService();
14435        try {
14436            // Deliver LOCKED_BOOT_COMPLETED first
14437            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14438                    .setPackage(packageName);
14439            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14440            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14441                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14442
14443            // Deliver BOOT_COMPLETED only if user is unlocked
14444            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14445                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14446                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14447                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14448            }
14449        } catch (RemoteException e) {
14450            throw e.rethrowFromSystemServer();
14451        }
14452    }
14453
14454    @Override
14455    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14456            int userId) {
14457        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14458        PackageSetting pkgSetting;
14459        final int callingUid = Binder.getCallingUid();
14460        enforceCrossUserPermission(callingUid, userId,
14461                true /* requireFullPermission */, true /* checkShell */,
14462                "setApplicationHiddenSetting for user " + userId);
14463
14464        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14465            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14466            return false;
14467        }
14468
14469        long callingId = Binder.clearCallingIdentity();
14470        try {
14471            boolean sendAdded = false;
14472            boolean sendRemoved = false;
14473            // writer
14474            synchronized (mPackages) {
14475                pkgSetting = mSettings.mPackages.get(packageName);
14476                if (pkgSetting == null) {
14477                    return false;
14478                }
14479                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14480                    return false;
14481                }
14482                // Do not allow "android" is being disabled
14483                if ("android".equals(packageName)) {
14484                    Slog.w(TAG, "Cannot hide package: android");
14485                    return false;
14486                }
14487                // Cannot hide static shared libs as they are considered
14488                // a part of the using app (emulating static linking). Also
14489                // static libs are installed always on internal storage.
14490                PackageParser.Package pkg = mPackages.get(packageName);
14491                if (pkg != null && pkg.staticSharedLibName != null) {
14492                    Slog.w(TAG, "Cannot hide package: " + packageName
14493                            + " providing static shared library: "
14494                            + pkg.staticSharedLibName);
14495                    return false;
14496                }
14497                // Only allow protected packages to hide themselves.
14498                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14499                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14500                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14501                    return false;
14502                }
14503
14504                if (pkgSetting.getHidden(userId) != hidden) {
14505                    pkgSetting.setHidden(hidden, userId);
14506                    mSettings.writePackageRestrictionsLPr(userId);
14507                    if (hidden) {
14508                        sendRemoved = true;
14509                    } else {
14510                        sendAdded = true;
14511                    }
14512                }
14513            }
14514            if (sendAdded) {
14515                sendPackageAddedForUser(packageName, pkgSetting, userId);
14516                return true;
14517            }
14518            if (sendRemoved) {
14519                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14520                        "hiding pkg");
14521                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14522                return true;
14523            }
14524        } finally {
14525            Binder.restoreCallingIdentity(callingId);
14526        }
14527        return false;
14528    }
14529
14530    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14531            int userId) {
14532        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14533        info.removedPackage = packageName;
14534        info.installerPackageName = pkgSetting.installerPackageName;
14535        info.removedUsers = new int[] {userId};
14536        info.broadcastUsers = new int[] {userId};
14537        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14538        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14539    }
14540
14541    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14542        if (pkgList.length > 0) {
14543            Bundle extras = new Bundle(1);
14544            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14545
14546            sendPackageBroadcast(
14547                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14548                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14549                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14550                    new int[] {userId});
14551        }
14552    }
14553
14554    /**
14555     * Returns true if application is not found or there was an error. Otherwise it returns
14556     * the hidden state of the package for the given user.
14557     */
14558    @Override
14559    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14560        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14561        final int callingUid = Binder.getCallingUid();
14562        enforceCrossUserPermission(callingUid, userId,
14563                true /* requireFullPermission */, false /* checkShell */,
14564                "getApplicationHidden for user " + userId);
14565        PackageSetting ps;
14566        long callingId = Binder.clearCallingIdentity();
14567        try {
14568            // writer
14569            synchronized (mPackages) {
14570                ps = mSettings.mPackages.get(packageName);
14571                if (ps == null) {
14572                    return true;
14573                }
14574                if (filterAppAccessLPr(ps, callingUid, userId)) {
14575                    return true;
14576                }
14577                return ps.getHidden(userId);
14578            }
14579        } finally {
14580            Binder.restoreCallingIdentity(callingId);
14581        }
14582    }
14583
14584    /**
14585     * @hide
14586     */
14587    @Override
14588    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14589            int installReason) {
14590        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14591                null);
14592        PackageSetting pkgSetting;
14593        final int callingUid = Binder.getCallingUid();
14594        enforceCrossUserPermission(callingUid, userId,
14595                true /* requireFullPermission */, true /* checkShell */,
14596                "installExistingPackage for user " + userId);
14597        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14598            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14599        }
14600
14601        long callingId = Binder.clearCallingIdentity();
14602        try {
14603            boolean installed = false;
14604            final boolean instantApp =
14605                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14606            final boolean fullApp =
14607                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14608
14609            // writer
14610            synchronized (mPackages) {
14611                pkgSetting = mSettings.mPackages.get(packageName);
14612                if (pkgSetting == null) {
14613                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14614                }
14615                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14616                    // only allow the existing package to be used if it's installed as a full
14617                    // application for at least one user
14618                    boolean installAllowed = false;
14619                    for (int checkUserId : sUserManager.getUserIds()) {
14620                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14621                        if (installAllowed) {
14622                            break;
14623                        }
14624                    }
14625                    if (!installAllowed) {
14626                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14627                    }
14628                }
14629                if (!pkgSetting.getInstalled(userId)) {
14630                    pkgSetting.setInstalled(true, userId);
14631                    pkgSetting.setHidden(false, userId);
14632                    pkgSetting.setInstallReason(installReason, userId);
14633                    mSettings.writePackageRestrictionsLPr(userId);
14634                    mSettings.writeKernelMappingLPr(pkgSetting);
14635                    installed = true;
14636                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14637                    // upgrade app from instant to full; we don't allow app downgrade
14638                    installed = true;
14639                }
14640                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14641            }
14642
14643            if (installed) {
14644                if (pkgSetting.pkg != null) {
14645                    synchronized (mInstallLock) {
14646                        // We don't need to freeze for a brand new install
14647                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14648                    }
14649                }
14650                sendPackageAddedForUser(packageName, pkgSetting, userId);
14651                synchronized (mPackages) {
14652                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14653                }
14654            }
14655        } finally {
14656            Binder.restoreCallingIdentity(callingId);
14657        }
14658
14659        return PackageManager.INSTALL_SUCCEEDED;
14660    }
14661
14662    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14663            boolean instantApp, boolean fullApp) {
14664        // no state specified; do nothing
14665        if (!instantApp && !fullApp) {
14666            return;
14667        }
14668        if (userId != UserHandle.USER_ALL) {
14669            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14670                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14671            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14672                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14673            }
14674        } else {
14675            for (int currentUserId : sUserManager.getUserIds()) {
14676                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14677                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14678                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14679                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14680                }
14681            }
14682        }
14683    }
14684
14685    boolean isUserRestricted(int userId, String restrictionKey) {
14686        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14687        if (restrictions.getBoolean(restrictionKey, false)) {
14688            Log.w(TAG, "User is restricted: " + restrictionKey);
14689            return true;
14690        }
14691        return false;
14692    }
14693
14694    @Override
14695    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14696            int userId) {
14697        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14698        final int callingUid = Binder.getCallingUid();
14699        enforceCrossUserPermission(callingUid, userId,
14700                true /* requireFullPermission */, true /* checkShell */,
14701                "setPackagesSuspended for user " + userId);
14702
14703        if (ArrayUtils.isEmpty(packageNames)) {
14704            return packageNames;
14705        }
14706
14707        // List of package names for whom the suspended state has changed.
14708        List<String> changedPackages = new ArrayList<>(packageNames.length);
14709        // List of package names for whom the suspended state is not set as requested in this
14710        // method.
14711        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14712        long callingId = Binder.clearCallingIdentity();
14713        try {
14714            for (int i = 0; i < packageNames.length; i++) {
14715                String packageName = packageNames[i];
14716                boolean changed = false;
14717                final int appId;
14718                synchronized (mPackages) {
14719                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14720                    if (pkgSetting == null
14721                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14722                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14723                                + "\". Skipping suspending/un-suspending.");
14724                        unactionedPackages.add(packageName);
14725                        continue;
14726                    }
14727                    appId = pkgSetting.appId;
14728                    if (pkgSetting.getSuspended(userId) != suspended) {
14729                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14730                            unactionedPackages.add(packageName);
14731                            continue;
14732                        }
14733                        pkgSetting.setSuspended(suspended, userId);
14734                        mSettings.writePackageRestrictionsLPr(userId);
14735                        changed = true;
14736                        changedPackages.add(packageName);
14737                    }
14738                }
14739
14740                if (changed && suspended) {
14741                    killApplication(packageName, UserHandle.getUid(userId, appId),
14742                            "suspending package");
14743                }
14744            }
14745        } finally {
14746            Binder.restoreCallingIdentity(callingId);
14747        }
14748
14749        if (!changedPackages.isEmpty()) {
14750            sendPackagesSuspendedForUser(changedPackages.toArray(
14751                    new String[changedPackages.size()]), userId, suspended);
14752        }
14753
14754        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14755    }
14756
14757    @Override
14758    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14759        final int callingUid = Binder.getCallingUid();
14760        enforceCrossUserPermission(callingUid, userId,
14761                true /* requireFullPermission */, false /* checkShell */,
14762                "isPackageSuspendedForUser for user " + userId);
14763        synchronized (mPackages) {
14764            final PackageSetting ps = mSettings.mPackages.get(packageName);
14765            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14766                throw new IllegalArgumentException("Unknown target package: " + packageName);
14767            }
14768            return ps.getSuspended(userId);
14769        }
14770    }
14771
14772    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14773        if (isPackageDeviceAdmin(packageName, userId)) {
14774            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14775                    + "\": has an active device admin");
14776            return false;
14777        }
14778
14779        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14780        if (packageName.equals(activeLauncherPackageName)) {
14781            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14782                    + "\": contains the active launcher");
14783            return false;
14784        }
14785
14786        if (packageName.equals(mRequiredInstallerPackage)) {
14787            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14788                    + "\": required for package installation");
14789            return false;
14790        }
14791
14792        if (packageName.equals(mRequiredUninstallerPackage)) {
14793            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14794                    + "\": required for package uninstallation");
14795            return false;
14796        }
14797
14798        if (packageName.equals(mRequiredVerifierPackage)) {
14799            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14800                    + "\": required for package verification");
14801            return false;
14802        }
14803
14804        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14805            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14806                    + "\": is the default dialer");
14807            return false;
14808        }
14809
14810        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14811            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14812                    + "\": protected package");
14813            return false;
14814        }
14815
14816        // Cannot suspend static shared libs as they are considered
14817        // a part of the using app (emulating static linking). Also
14818        // static libs are installed always on internal storage.
14819        PackageParser.Package pkg = mPackages.get(packageName);
14820        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14821            Slog.w(TAG, "Cannot suspend package: " + packageName
14822                    + " providing static shared library: "
14823                    + pkg.staticSharedLibName);
14824            return false;
14825        }
14826
14827        return true;
14828    }
14829
14830    private String getActiveLauncherPackageName(int userId) {
14831        Intent intent = new Intent(Intent.ACTION_MAIN);
14832        intent.addCategory(Intent.CATEGORY_HOME);
14833        ResolveInfo resolveInfo = resolveIntent(
14834                intent,
14835                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14836                PackageManager.MATCH_DEFAULT_ONLY,
14837                userId);
14838
14839        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14840    }
14841
14842    private String getDefaultDialerPackageName(int userId) {
14843        synchronized (mPackages) {
14844            return mSettings.getDefaultDialerPackageNameLPw(userId);
14845        }
14846    }
14847
14848    @Override
14849    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14850        mContext.enforceCallingOrSelfPermission(
14851                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14852                "Only package verification agents can verify applications");
14853
14854        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14855        final PackageVerificationResponse response = new PackageVerificationResponse(
14856                verificationCode, Binder.getCallingUid());
14857        msg.arg1 = id;
14858        msg.obj = response;
14859        mHandler.sendMessage(msg);
14860    }
14861
14862    @Override
14863    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14864            long millisecondsToDelay) {
14865        mContext.enforceCallingOrSelfPermission(
14866                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14867                "Only package verification agents can extend verification timeouts");
14868
14869        final PackageVerificationState state = mPendingVerification.get(id);
14870        final PackageVerificationResponse response = new PackageVerificationResponse(
14871                verificationCodeAtTimeout, Binder.getCallingUid());
14872
14873        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14874            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14875        }
14876        if (millisecondsToDelay < 0) {
14877            millisecondsToDelay = 0;
14878        }
14879        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14880                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14881            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14882        }
14883
14884        if ((state != null) && !state.timeoutExtended()) {
14885            state.extendTimeout();
14886
14887            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14888            msg.arg1 = id;
14889            msg.obj = response;
14890            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14891        }
14892    }
14893
14894    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14895            int verificationCode, UserHandle user) {
14896        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14897        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14898        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14899        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14900        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14901
14902        mContext.sendBroadcastAsUser(intent, user,
14903                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14904    }
14905
14906    private ComponentName matchComponentForVerifier(String packageName,
14907            List<ResolveInfo> receivers) {
14908        ActivityInfo targetReceiver = null;
14909
14910        final int NR = receivers.size();
14911        for (int i = 0; i < NR; i++) {
14912            final ResolveInfo info = receivers.get(i);
14913            if (info.activityInfo == null) {
14914                continue;
14915            }
14916
14917            if (packageName.equals(info.activityInfo.packageName)) {
14918                targetReceiver = info.activityInfo;
14919                break;
14920            }
14921        }
14922
14923        if (targetReceiver == null) {
14924            return null;
14925        }
14926
14927        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14928    }
14929
14930    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14931            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14932        if (pkgInfo.verifiers.length == 0) {
14933            return null;
14934        }
14935
14936        final int N = pkgInfo.verifiers.length;
14937        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14938        for (int i = 0; i < N; i++) {
14939            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14940
14941            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14942                    receivers);
14943            if (comp == null) {
14944                continue;
14945            }
14946
14947            final int verifierUid = getUidForVerifier(verifierInfo);
14948            if (verifierUid == -1) {
14949                continue;
14950            }
14951
14952            if (DEBUG_VERIFY) {
14953                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14954                        + " with the correct signature");
14955            }
14956            sufficientVerifiers.add(comp);
14957            verificationState.addSufficientVerifier(verifierUid);
14958        }
14959
14960        return sufficientVerifiers;
14961    }
14962
14963    private int getUidForVerifier(VerifierInfo verifierInfo) {
14964        synchronized (mPackages) {
14965            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14966            if (pkg == null) {
14967                return -1;
14968            } else if (pkg.mSignatures.length != 1) {
14969                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14970                        + " has more than one signature; ignoring");
14971                return -1;
14972            }
14973
14974            /*
14975             * If the public key of the package's signature does not match
14976             * our expected public key, then this is a different package and
14977             * we should skip.
14978             */
14979
14980            final byte[] expectedPublicKey;
14981            try {
14982                final Signature verifierSig = pkg.mSignatures[0];
14983                final PublicKey publicKey = verifierSig.getPublicKey();
14984                expectedPublicKey = publicKey.getEncoded();
14985            } catch (CertificateException e) {
14986                return -1;
14987            }
14988
14989            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14990
14991            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14992                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14993                        + " does not have the expected public key; ignoring");
14994                return -1;
14995            }
14996
14997            return pkg.applicationInfo.uid;
14998        }
14999    }
15000
15001    @Override
15002    public void finishPackageInstall(int token, boolean didLaunch) {
15003        enforceSystemOrRoot("Only the system is allowed to finish installs");
15004
15005        if (DEBUG_INSTALL) {
15006            Slog.v(TAG, "BM finishing package install for " + token);
15007        }
15008        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15009
15010        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15011        mHandler.sendMessage(msg);
15012    }
15013
15014    /**
15015     * Get the verification agent timeout.  Used for both the APK verifier and the
15016     * intent filter verifier.
15017     *
15018     * @return verification timeout in milliseconds
15019     */
15020    private long getVerificationTimeout() {
15021        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15022                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15023                DEFAULT_VERIFICATION_TIMEOUT);
15024    }
15025
15026    /**
15027     * Get the default verification agent response code.
15028     *
15029     * @return default verification response code
15030     */
15031    private int getDefaultVerificationResponse(UserHandle user) {
15032        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15033            return PackageManager.VERIFICATION_REJECT;
15034        }
15035        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15036                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15037                DEFAULT_VERIFICATION_RESPONSE);
15038    }
15039
15040    /**
15041     * Check whether or not package verification has been enabled.
15042     *
15043     * @return true if verification should be performed
15044     */
15045    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15046        if (!DEFAULT_VERIFY_ENABLE) {
15047            return false;
15048        }
15049
15050        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15051
15052        // Check if installing from ADB
15053        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15054            // Do not run verification in a test harness environment
15055            if (ActivityManager.isRunningInTestHarness()) {
15056                return false;
15057            }
15058            if (ensureVerifyAppsEnabled) {
15059                return true;
15060            }
15061            // Check if the developer does not want package verification for ADB installs
15062            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15063                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15064                return false;
15065            }
15066        } else {
15067            // only when not installed from ADB, skip verification for instant apps when
15068            // the installer and verifier are the same.
15069            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15070                if (mInstantAppInstallerActivity != null
15071                        && mInstantAppInstallerActivity.packageName.equals(
15072                                mRequiredVerifierPackage)) {
15073                    try {
15074                        mContext.getSystemService(AppOpsManager.class)
15075                                .checkPackage(installerUid, mRequiredVerifierPackage);
15076                        if (DEBUG_VERIFY) {
15077                            Slog.i(TAG, "disable verification for instant app");
15078                        }
15079                        return false;
15080                    } catch (SecurityException ignore) { }
15081                }
15082            }
15083        }
15084
15085        if (ensureVerifyAppsEnabled) {
15086            return true;
15087        }
15088
15089        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15090                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15091    }
15092
15093    @Override
15094    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15095            throws RemoteException {
15096        mContext.enforceCallingOrSelfPermission(
15097                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15098                "Only intentfilter verification agents can verify applications");
15099
15100        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15101        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15102                Binder.getCallingUid(), verificationCode, failedDomains);
15103        msg.arg1 = id;
15104        msg.obj = response;
15105        mHandler.sendMessage(msg);
15106    }
15107
15108    @Override
15109    public int getIntentVerificationStatus(String packageName, int userId) {
15110        final int callingUid = Binder.getCallingUid();
15111        if (getInstantAppPackageName(callingUid) != null) {
15112            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15113        }
15114        synchronized (mPackages) {
15115            final PackageSetting ps = mSettings.mPackages.get(packageName);
15116            if (ps == null
15117                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15118                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15119            }
15120            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15121        }
15122    }
15123
15124    @Override
15125    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15126        mContext.enforceCallingOrSelfPermission(
15127                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15128
15129        boolean result = false;
15130        synchronized (mPackages) {
15131            final PackageSetting ps = mSettings.mPackages.get(packageName);
15132            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15133                return false;
15134            }
15135            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15136        }
15137        if (result) {
15138            scheduleWritePackageRestrictionsLocked(userId);
15139        }
15140        return result;
15141    }
15142
15143    @Override
15144    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15145            String packageName) {
15146        final int callingUid = Binder.getCallingUid();
15147        if (getInstantAppPackageName(callingUid) != null) {
15148            return ParceledListSlice.emptyList();
15149        }
15150        synchronized (mPackages) {
15151            final PackageSetting ps = mSettings.mPackages.get(packageName);
15152            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15153                return ParceledListSlice.emptyList();
15154            }
15155            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15156        }
15157    }
15158
15159    @Override
15160    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15161        if (TextUtils.isEmpty(packageName)) {
15162            return ParceledListSlice.emptyList();
15163        }
15164        final int callingUid = Binder.getCallingUid();
15165        final int callingUserId = UserHandle.getUserId(callingUid);
15166        synchronized (mPackages) {
15167            PackageParser.Package pkg = mPackages.get(packageName);
15168            if (pkg == null || pkg.activities == null) {
15169                return ParceledListSlice.emptyList();
15170            }
15171            if (pkg.mExtras == null) {
15172                return ParceledListSlice.emptyList();
15173            }
15174            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15175            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15176                return ParceledListSlice.emptyList();
15177            }
15178            final int count = pkg.activities.size();
15179            ArrayList<IntentFilter> result = new ArrayList<>();
15180            for (int n=0; n<count; n++) {
15181                PackageParser.Activity activity = pkg.activities.get(n);
15182                if (activity.intents != null && activity.intents.size() > 0) {
15183                    result.addAll(activity.intents);
15184                }
15185            }
15186            return new ParceledListSlice<>(result);
15187        }
15188    }
15189
15190    @Override
15191    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15192        mContext.enforceCallingOrSelfPermission(
15193                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15194
15195        synchronized (mPackages) {
15196            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15197            if (packageName != null) {
15198                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15199                        packageName, userId);
15200            }
15201            return result;
15202        }
15203    }
15204
15205    @Override
15206    public String getDefaultBrowserPackageName(int userId) {
15207        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15208            return null;
15209        }
15210        synchronized (mPackages) {
15211            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15212        }
15213    }
15214
15215    /**
15216     * Get the "allow unknown sources" setting.
15217     *
15218     * @return the current "allow unknown sources" setting
15219     */
15220    private int getUnknownSourcesSettings() {
15221        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15222                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15223                -1);
15224    }
15225
15226    @Override
15227    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15228        final int callingUid = Binder.getCallingUid();
15229        if (getInstantAppPackageName(callingUid) != null) {
15230            return;
15231        }
15232        // writer
15233        synchronized (mPackages) {
15234            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15235            if (targetPackageSetting == null
15236                    || filterAppAccessLPr(
15237                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15238                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15239            }
15240
15241            PackageSetting installerPackageSetting;
15242            if (installerPackageName != null) {
15243                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15244                if (installerPackageSetting == null) {
15245                    throw new IllegalArgumentException("Unknown installer package: "
15246                            + installerPackageName);
15247                }
15248            } else {
15249                installerPackageSetting = null;
15250            }
15251
15252            Signature[] callerSignature;
15253            Object obj = mSettings.getUserIdLPr(callingUid);
15254            if (obj != null) {
15255                if (obj instanceof SharedUserSetting) {
15256                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15257                } else if (obj instanceof PackageSetting) {
15258                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15259                } else {
15260                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15261                }
15262            } else {
15263                throw new SecurityException("Unknown calling UID: " + callingUid);
15264            }
15265
15266            // Verify: can't set installerPackageName to a package that is
15267            // not signed with the same cert as the caller.
15268            if (installerPackageSetting != null) {
15269                if (compareSignatures(callerSignature,
15270                        installerPackageSetting.signatures.mSignatures)
15271                        != PackageManager.SIGNATURE_MATCH) {
15272                    throw new SecurityException(
15273                            "Caller does not have same cert as new installer package "
15274                            + installerPackageName);
15275                }
15276            }
15277
15278            // Verify: if target already has an installer package, it must
15279            // be signed with the same cert as the caller.
15280            if (targetPackageSetting.installerPackageName != null) {
15281                PackageSetting setting = mSettings.mPackages.get(
15282                        targetPackageSetting.installerPackageName);
15283                // If the currently set package isn't valid, then it's always
15284                // okay to change it.
15285                if (setting != null) {
15286                    if (compareSignatures(callerSignature,
15287                            setting.signatures.mSignatures)
15288                            != PackageManager.SIGNATURE_MATCH) {
15289                        throw new SecurityException(
15290                                "Caller does not have same cert as old installer package "
15291                                + targetPackageSetting.installerPackageName);
15292                    }
15293                }
15294            }
15295
15296            // Okay!
15297            targetPackageSetting.installerPackageName = installerPackageName;
15298            if (installerPackageName != null) {
15299                mSettings.mInstallerPackages.add(installerPackageName);
15300            }
15301            scheduleWriteSettingsLocked();
15302        }
15303    }
15304
15305    @Override
15306    public void setApplicationCategoryHint(String packageName, int categoryHint,
15307            String callerPackageName) {
15308        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15309            throw new SecurityException("Instant applications don't have access to this method");
15310        }
15311        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15312                callerPackageName);
15313        synchronized (mPackages) {
15314            PackageSetting ps = mSettings.mPackages.get(packageName);
15315            if (ps == null) {
15316                throw new IllegalArgumentException("Unknown target package " + packageName);
15317            }
15318            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15319                throw new IllegalArgumentException("Unknown target package " + packageName);
15320            }
15321            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15322                throw new IllegalArgumentException("Calling package " + callerPackageName
15323                        + " is not installer for " + packageName);
15324            }
15325
15326            if (ps.categoryHint != categoryHint) {
15327                ps.categoryHint = categoryHint;
15328                scheduleWriteSettingsLocked();
15329            }
15330        }
15331    }
15332
15333    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15334        // Queue up an async operation since the package installation may take a little while.
15335        mHandler.post(new Runnable() {
15336            public void run() {
15337                mHandler.removeCallbacks(this);
15338                 // Result object to be returned
15339                PackageInstalledInfo res = new PackageInstalledInfo();
15340                res.setReturnCode(currentStatus);
15341                res.uid = -1;
15342                res.pkg = null;
15343                res.removedInfo = null;
15344                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15345                    args.doPreInstall(res.returnCode);
15346                    synchronized (mInstallLock) {
15347                        installPackageTracedLI(args, res);
15348                    }
15349                    args.doPostInstall(res.returnCode, res.uid);
15350                }
15351
15352                // A restore should be performed at this point if (a) the install
15353                // succeeded, (b) the operation is not an update, and (c) the new
15354                // package has not opted out of backup participation.
15355                final boolean update = res.removedInfo != null
15356                        && res.removedInfo.removedPackage != null;
15357                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15358                boolean doRestore = !update
15359                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15360
15361                // Set up the post-install work request bookkeeping.  This will be used
15362                // and cleaned up by the post-install event handling regardless of whether
15363                // there's a restore pass performed.  Token values are >= 1.
15364                int token;
15365                if (mNextInstallToken < 0) mNextInstallToken = 1;
15366                token = mNextInstallToken++;
15367
15368                PostInstallData data = new PostInstallData(args, res);
15369                mRunningInstalls.put(token, data);
15370                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15371
15372                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15373                    // Pass responsibility to the Backup Manager.  It will perform a
15374                    // restore if appropriate, then pass responsibility back to the
15375                    // Package Manager to run the post-install observer callbacks
15376                    // and broadcasts.
15377                    IBackupManager bm = IBackupManager.Stub.asInterface(
15378                            ServiceManager.getService(Context.BACKUP_SERVICE));
15379                    if (bm != null) {
15380                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15381                                + " to BM for possible restore");
15382                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15383                        try {
15384                            // TODO: http://b/22388012
15385                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15386                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15387                            } else {
15388                                doRestore = false;
15389                            }
15390                        } catch (RemoteException e) {
15391                            // can't happen; the backup manager is local
15392                        } catch (Exception e) {
15393                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15394                            doRestore = false;
15395                        }
15396                    } else {
15397                        Slog.e(TAG, "Backup Manager not found!");
15398                        doRestore = false;
15399                    }
15400                }
15401
15402                if (!doRestore) {
15403                    // No restore possible, or the Backup Manager was mysteriously not
15404                    // available -- just fire the post-install work request directly.
15405                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15406
15407                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15408
15409                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15410                    mHandler.sendMessage(msg);
15411                }
15412            }
15413        });
15414    }
15415
15416    /**
15417     * Callback from PackageSettings whenever an app is first transitioned out of the
15418     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15419     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15420     * here whether the app is the target of an ongoing install, and only send the
15421     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15422     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15423     * handling.
15424     */
15425    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15426        // Serialize this with the rest of the install-process message chain.  In the
15427        // restore-at-install case, this Runnable will necessarily run before the
15428        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15429        // are coherent.  In the non-restore case, the app has already completed install
15430        // and been launched through some other means, so it is not in a problematic
15431        // state for observers to see the FIRST_LAUNCH signal.
15432        mHandler.post(new Runnable() {
15433            @Override
15434            public void run() {
15435                for (int i = 0; i < mRunningInstalls.size(); i++) {
15436                    final PostInstallData data = mRunningInstalls.valueAt(i);
15437                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15438                        continue;
15439                    }
15440                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15441                        // right package; but is it for the right user?
15442                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15443                            if (userId == data.res.newUsers[uIndex]) {
15444                                if (DEBUG_BACKUP) {
15445                                    Slog.i(TAG, "Package " + pkgName
15446                                            + " being restored so deferring FIRST_LAUNCH");
15447                                }
15448                                return;
15449                            }
15450                        }
15451                    }
15452                }
15453                // didn't find it, so not being restored
15454                if (DEBUG_BACKUP) {
15455                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15456                }
15457                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15458            }
15459        });
15460    }
15461
15462    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15463        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15464                installerPkg, null, userIds);
15465    }
15466
15467    private abstract class HandlerParams {
15468        private static final int MAX_RETRIES = 4;
15469
15470        /**
15471         * Number of times startCopy() has been attempted and had a non-fatal
15472         * error.
15473         */
15474        private int mRetries = 0;
15475
15476        /** User handle for the user requesting the information or installation. */
15477        private final UserHandle mUser;
15478        String traceMethod;
15479        int traceCookie;
15480
15481        HandlerParams(UserHandle user) {
15482            mUser = user;
15483        }
15484
15485        UserHandle getUser() {
15486            return mUser;
15487        }
15488
15489        HandlerParams setTraceMethod(String traceMethod) {
15490            this.traceMethod = traceMethod;
15491            return this;
15492        }
15493
15494        HandlerParams setTraceCookie(int traceCookie) {
15495            this.traceCookie = traceCookie;
15496            return this;
15497        }
15498
15499        final boolean startCopy() {
15500            boolean res;
15501            try {
15502                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15503
15504                if (++mRetries > MAX_RETRIES) {
15505                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15506                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15507                    handleServiceError();
15508                    return false;
15509                } else {
15510                    handleStartCopy();
15511                    res = true;
15512                }
15513            } catch (RemoteException e) {
15514                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15515                mHandler.sendEmptyMessage(MCS_RECONNECT);
15516                res = false;
15517            }
15518            handleReturnCode();
15519            return res;
15520        }
15521
15522        final void serviceError() {
15523            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15524            handleServiceError();
15525            handleReturnCode();
15526        }
15527
15528        abstract void handleStartCopy() throws RemoteException;
15529        abstract void handleServiceError();
15530        abstract void handleReturnCode();
15531    }
15532
15533    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15534        for (File path : paths) {
15535            try {
15536                mcs.clearDirectory(path.getAbsolutePath());
15537            } catch (RemoteException e) {
15538            }
15539        }
15540    }
15541
15542    static class OriginInfo {
15543        /**
15544         * Location where install is coming from, before it has been
15545         * copied/renamed into place. This could be a single monolithic APK
15546         * file, or a cluster directory. This location may be untrusted.
15547         */
15548        final File file;
15549        final String cid;
15550
15551        /**
15552         * Flag indicating that {@link #file} or {@link #cid} has already been
15553         * staged, meaning downstream users don't need to defensively copy the
15554         * contents.
15555         */
15556        final boolean staged;
15557
15558        /**
15559         * Flag indicating that {@link #file} or {@link #cid} is an already
15560         * installed app that is being moved.
15561         */
15562        final boolean existing;
15563
15564        final String resolvedPath;
15565        final File resolvedFile;
15566
15567        static OriginInfo fromNothing() {
15568            return new OriginInfo(null, null, false, false);
15569        }
15570
15571        static OriginInfo fromUntrustedFile(File file) {
15572            return new OriginInfo(file, null, false, false);
15573        }
15574
15575        static OriginInfo fromExistingFile(File file) {
15576            return new OriginInfo(file, null, false, true);
15577        }
15578
15579        static OriginInfo fromStagedFile(File file) {
15580            return new OriginInfo(file, null, true, false);
15581        }
15582
15583        static OriginInfo fromStagedContainer(String cid) {
15584            return new OriginInfo(null, cid, true, false);
15585        }
15586
15587        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15588            this.file = file;
15589            this.cid = cid;
15590            this.staged = staged;
15591            this.existing = existing;
15592
15593            if (cid != null) {
15594                resolvedPath = PackageHelper.getSdDir(cid);
15595                resolvedFile = new File(resolvedPath);
15596            } else if (file != null) {
15597                resolvedPath = file.getAbsolutePath();
15598                resolvedFile = file;
15599            } else {
15600                resolvedPath = null;
15601                resolvedFile = null;
15602            }
15603        }
15604    }
15605
15606    static class MoveInfo {
15607        final int moveId;
15608        final String fromUuid;
15609        final String toUuid;
15610        final String packageName;
15611        final String dataAppName;
15612        final int appId;
15613        final String seinfo;
15614        final int targetSdkVersion;
15615
15616        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15617                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15618            this.moveId = moveId;
15619            this.fromUuid = fromUuid;
15620            this.toUuid = toUuid;
15621            this.packageName = packageName;
15622            this.dataAppName = dataAppName;
15623            this.appId = appId;
15624            this.seinfo = seinfo;
15625            this.targetSdkVersion = targetSdkVersion;
15626        }
15627    }
15628
15629    static class VerificationInfo {
15630        /** A constant used to indicate that a uid value is not present. */
15631        public static final int NO_UID = -1;
15632
15633        /** URI referencing where the package was downloaded from. */
15634        final Uri originatingUri;
15635
15636        /** HTTP referrer URI associated with the originatingURI. */
15637        final Uri referrer;
15638
15639        /** UID of the application that the install request originated from. */
15640        final int originatingUid;
15641
15642        /** UID of application requesting the install */
15643        final int installerUid;
15644
15645        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15646            this.originatingUri = originatingUri;
15647            this.referrer = referrer;
15648            this.originatingUid = originatingUid;
15649            this.installerUid = installerUid;
15650        }
15651    }
15652
15653    class InstallParams extends HandlerParams {
15654        final OriginInfo origin;
15655        final MoveInfo move;
15656        final IPackageInstallObserver2 observer;
15657        int installFlags;
15658        final String installerPackageName;
15659        final String volumeUuid;
15660        private InstallArgs mArgs;
15661        private int mRet;
15662        final String packageAbiOverride;
15663        final String[] grantedRuntimePermissions;
15664        final VerificationInfo verificationInfo;
15665        final Certificate[][] certificates;
15666        final int installReason;
15667
15668        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15669                int installFlags, String installerPackageName, String volumeUuid,
15670                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15671                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15672            super(user);
15673            this.origin = origin;
15674            this.move = move;
15675            this.observer = observer;
15676            this.installFlags = installFlags;
15677            this.installerPackageName = installerPackageName;
15678            this.volumeUuid = volumeUuid;
15679            this.verificationInfo = verificationInfo;
15680            this.packageAbiOverride = packageAbiOverride;
15681            this.grantedRuntimePermissions = grantedPermissions;
15682            this.certificates = certificates;
15683            this.installReason = installReason;
15684        }
15685
15686        @Override
15687        public String toString() {
15688            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15689                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15690        }
15691
15692        private int installLocationPolicy(PackageInfoLite pkgLite) {
15693            String packageName = pkgLite.packageName;
15694            int installLocation = pkgLite.installLocation;
15695            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15696            // reader
15697            synchronized (mPackages) {
15698                // Currently installed package which the new package is attempting to replace or
15699                // null if no such package is installed.
15700                PackageParser.Package installedPkg = mPackages.get(packageName);
15701                // Package which currently owns the data which the new package will own if installed.
15702                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15703                // will be null whereas dataOwnerPkg will contain information about the package
15704                // which was uninstalled while keeping its data.
15705                PackageParser.Package dataOwnerPkg = installedPkg;
15706                if (dataOwnerPkg  == null) {
15707                    PackageSetting ps = mSettings.mPackages.get(packageName);
15708                    if (ps != null) {
15709                        dataOwnerPkg = ps.pkg;
15710                    }
15711                }
15712
15713                if (dataOwnerPkg != null) {
15714                    // If installed, the package will get access to data left on the device by its
15715                    // predecessor. As a security measure, this is permited only if this is not a
15716                    // version downgrade or if the predecessor package is marked as debuggable and
15717                    // a downgrade is explicitly requested.
15718                    //
15719                    // On debuggable platform builds, downgrades are permitted even for
15720                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15721                    // not offer security guarantees and thus it's OK to disable some security
15722                    // mechanisms to make debugging/testing easier on those builds. However, even on
15723                    // debuggable builds downgrades of packages are permitted only if requested via
15724                    // installFlags. This is because we aim to keep the behavior of debuggable
15725                    // platform builds as close as possible to the behavior of non-debuggable
15726                    // platform builds.
15727                    final boolean downgradeRequested =
15728                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15729                    final boolean packageDebuggable =
15730                                (dataOwnerPkg.applicationInfo.flags
15731                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15732                    final boolean downgradePermitted =
15733                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15734                    if (!downgradePermitted) {
15735                        try {
15736                            checkDowngrade(dataOwnerPkg, pkgLite);
15737                        } catch (PackageManagerException e) {
15738                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15739                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15740                        }
15741                    }
15742                }
15743
15744                if (installedPkg != null) {
15745                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15746                        // Check for updated system application.
15747                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15748                            if (onSd) {
15749                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15750                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15751                            }
15752                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15753                        } else {
15754                            if (onSd) {
15755                                // Install flag overrides everything.
15756                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15757                            }
15758                            // If current upgrade specifies particular preference
15759                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15760                                // Application explicitly specified internal.
15761                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15762                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15763                                // App explictly prefers external. Let policy decide
15764                            } else {
15765                                // Prefer previous location
15766                                if (isExternal(installedPkg)) {
15767                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15768                                }
15769                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15770                            }
15771                        }
15772                    } else {
15773                        // Invalid install. Return error code
15774                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15775                    }
15776                }
15777            }
15778            // All the special cases have been taken care of.
15779            // Return result based on recommended install location.
15780            if (onSd) {
15781                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15782            }
15783            return pkgLite.recommendedInstallLocation;
15784        }
15785
15786        /*
15787         * Invoke remote method to get package information and install
15788         * location values. Override install location based on default
15789         * policy if needed and then create install arguments based
15790         * on the install location.
15791         */
15792        public void handleStartCopy() throws RemoteException {
15793            int ret = PackageManager.INSTALL_SUCCEEDED;
15794
15795            // If we're already staged, we've firmly committed to an install location
15796            if (origin.staged) {
15797                if (origin.file != null) {
15798                    installFlags |= PackageManager.INSTALL_INTERNAL;
15799                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15800                } else if (origin.cid != null) {
15801                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15802                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15803                } else {
15804                    throw new IllegalStateException("Invalid stage location");
15805                }
15806            }
15807
15808            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15809            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15810            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15811            PackageInfoLite pkgLite = null;
15812
15813            if (onInt && onSd) {
15814                // Check if both bits are set.
15815                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15816                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15817            } else if (onSd && ephemeral) {
15818                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15819                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15820            } else {
15821                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15822                        packageAbiOverride);
15823
15824                if (DEBUG_EPHEMERAL && ephemeral) {
15825                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15826                }
15827
15828                /*
15829                 * If we have too little free space, try to free cache
15830                 * before giving up.
15831                 */
15832                if (!origin.staged && pkgLite.recommendedInstallLocation
15833                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15834                    // TODO: focus freeing disk space on the target device
15835                    final StorageManager storage = StorageManager.from(mContext);
15836                    final long lowThreshold = storage.getStorageLowBytes(
15837                            Environment.getDataDirectory());
15838
15839                    final long sizeBytes = mContainerService.calculateInstalledSize(
15840                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15841
15842                    try {
15843                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15844                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15845                                installFlags, packageAbiOverride);
15846                    } catch (InstallerException e) {
15847                        Slog.w(TAG, "Failed to free cache", e);
15848                    }
15849
15850                    /*
15851                     * The cache free must have deleted the file we
15852                     * downloaded to install.
15853                     *
15854                     * TODO: fix the "freeCache" call to not delete
15855                     *       the file we care about.
15856                     */
15857                    if (pkgLite.recommendedInstallLocation
15858                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15859                        pkgLite.recommendedInstallLocation
15860                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15861                    }
15862                }
15863            }
15864
15865            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15866                int loc = pkgLite.recommendedInstallLocation;
15867                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15868                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15869                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15870                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15871                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15872                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15873                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15874                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15875                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15876                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15877                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15878                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15879                } else {
15880                    // Override with defaults if needed.
15881                    loc = installLocationPolicy(pkgLite);
15882                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15883                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15884                    } else if (!onSd && !onInt) {
15885                        // Override install location with flags
15886                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15887                            // Set the flag to install on external media.
15888                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15889                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15890                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15891                            if (DEBUG_EPHEMERAL) {
15892                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15893                            }
15894                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15895                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15896                                    |PackageManager.INSTALL_INTERNAL);
15897                        } else {
15898                            // Make sure the flag for installing on external
15899                            // media is unset
15900                            installFlags |= PackageManager.INSTALL_INTERNAL;
15901                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15902                        }
15903                    }
15904                }
15905            }
15906
15907            final InstallArgs args = createInstallArgs(this);
15908            mArgs = args;
15909
15910            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15911                // TODO: http://b/22976637
15912                // Apps installed for "all" users use the device owner to verify the app
15913                UserHandle verifierUser = getUser();
15914                if (verifierUser == UserHandle.ALL) {
15915                    verifierUser = UserHandle.SYSTEM;
15916                }
15917
15918                /*
15919                 * Determine if we have any installed package verifiers. If we
15920                 * do, then we'll defer to them to verify the packages.
15921                 */
15922                final int requiredUid = mRequiredVerifierPackage == null ? -1
15923                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15924                                verifierUser.getIdentifier());
15925                final int installerUid =
15926                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15927                if (!origin.existing && requiredUid != -1
15928                        && isVerificationEnabled(
15929                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15930                    final Intent verification = new Intent(
15931                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15932                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15933                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15934                            PACKAGE_MIME_TYPE);
15935                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15936
15937                    // Query all live verifiers based on current user state
15938                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15939                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15940
15941                    if (DEBUG_VERIFY) {
15942                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15943                                + verification.toString() + " with " + pkgLite.verifiers.length
15944                                + " optional verifiers");
15945                    }
15946
15947                    final int verificationId = mPendingVerificationToken++;
15948
15949                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15950
15951                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15952                            installerPackageName);
15953
15954                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15955                            installFlags);
15956
15957                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15958                            pkgLite.packageName);
15959
15960                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15961                            pkgLite.versionCode);
15962
15963                    if (verificationInfo != null) {
15964                        if (verificationInfo.originatingUri != null) {
15965                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15966                                    verificationInfo.originatingUri);
15967                        }
15968                        if (verificationInfo.referrer != null) {
15969                            verification.putExtra(Intent.EXTRA_REFERRER,
15970                                    verificationInfo.referrer);
15971                        }
15972                        if (verificationInfo.originatingUid >= 0) {
15973                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15974                                    verificationInfo.originatingUid);
15975                        }
15976                        if (verificationInfo.installerUid >= 0) {
15977                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15978                                    verificationInfo.installerUid);
15979                        }
15980                    }
15981
15982                    final PackageVerificationState verificationState = new PackageVerificationState(
15983                            requiredUid, args);
15984
15985                    mPendingVerification.append(verificationId, verificationState);
15986
15987                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15988                            receivers, verificationState);
15989
15990                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15991                    final long idleDuration = getVerificationTimeout();
15992
15993                    /*
15994                     * If any sufficient verifiers were listed in the package
15995                     * manifest, attempt to ask them.
15996                     */
15997                    if (sufficientVerifiers != null) {
15998                        final int N = sufficientVerifiers.size();
15999                        if (N == 0) {
16000                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16001                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16002                        } else {
16003                            for (int i = 0; i < N; i++) {
16004                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16005                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16006                                        verifierComponent.getPackageName(), idleDuration,
16007                                        verifierUser.getIdentifier(), false, "package verifier");
16008
16009                                final Intent sufficientIntent = new Intent(verification);
16010                                sufficientIntent.setComponent(verifierComponent);
16011                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16012                            }
16013                        }
16014                    }
16015
16016                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16017                            mRequiredVerifierPackage, receivers);
16018                    if (ret == PackageManager.INSTALL_SUCCEEDED
16019                            && mRequiredVerifierPackage != null) {
16020                        Trace.asyncTraceBegin(
16021                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16022                        /*
16023                         * Send the intent to the required verification agent,
16024                         * but only start the verification timeout after the
16025                         * target BroadcastReceivers have run.
16026                         */
16027                        verification.setComponent(requiredVerifierComponent);
16028                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16029                                mRequiredVerifierPackage, idleDuration,
16030                                verifierUser.getIdentifier(), false, "package verifier");
16031                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16032                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16033                                new BroadcastReceiver() {
16034                                    @Override
16035                                    public void onReceive(Context context, Intent intent) {
16036                                        final Message msg = mHandler
16037                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16038                                        msg.arg1 = verificationId;
16039                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16040                                    }
16041                                }, null, 0, null, null);
16042
16043                        /*
16044                         * We don't want the copy to proceed until verification
16045                         * succeeds, so null out this field.
16046                         */
16047                        mArgs = null;
16048                    }
16049                } else {
16050                    /*
16051                     * No package verification is enabled, so immediately start
16052                     * the remote call to initiate copy using temporary file.
16053                     */
16054                    ret = args.copyApk(mContainerService, true);
16055                }
16056            }
16057
16058            mRet = ret;
16059        }
16060
16061        @Override
16062        void handleReturnCode() {
16063            // If mArgs is null, then MCS couldn't be reached. When it
16064            // reconnects, it will try again to install. At that point, this
16065            // will succeed.
16066            if (mArgs != null) {
16067                processPendingInstall(mArgs, mRet);
16068            }
16069        }
16070
16071        @Override
16072        void handleServiceError() {
16073            mArgs = createInstallArgs(this);
16074            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16075        }
16076
16077        public boolean isForwardLocked() {
16078            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16079        }
16080    }
16081
16082    /**
16083     * Used during creation of InstallArgs
16084     *
16085     * @param installFlags package installation flags
16086     * @return true if should be installed on external storage
16087     */
16088    private static boolean installOnExternalAsec(int installFlags) {
16089        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16090            return false;
16091        }
16092        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16093            return true;
16094        }
16095        return false;
16096    }
16097
16098    /**
16099     * Used during creation of InstallArgs
16100     *
16101     * @param installFlags package installation flags
16102     * @return true if should be installed as forward locked
16103     */
16104    private static boolean installForwardLocked(int installFlags) {
16105        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16106    }
16107
16108    private InstallArgs createInstallArgs(InstallParams params) {
16109        if (params.move != null) {
16110            return new MoveInstallArgs(params);
16111        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16112            return new AsecInstallArgs(params);
16113        } else {
16114            return new FileInstallArgs(params);
16115        }
16116    }
16117
16118    /**
16119     * Create args that describe an existing installed package. Typically used
16120     * when cleaning up old installs, or used as a move source.
16121     */
16122    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16123            String resourcePath, String[] instructionSets) {
16124        final boolean isInAsec;
16125        if (installOnExternalAsec(installFlags)) {
16126            /* Apps on SD card are always in ASEC containers. */
16127            isInAsec = true;
16128        } else if (installForwardLocked(installFlags)
16129                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16130            /*
16131             * Forward-locked apps are only in ASEC containers if they're the
16132             * new style
16133             */
16134            isInAsec = true;
16135        } else {
16136            isInAsec = false;
16137        }
16138
16139        if (isInAsec) {
16140            return new AsecInstallArgs(codePath, instructionSets,
16141                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16142        } else {
16143            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16144        }
16145    }
16146
16147    static abstract class InstallArgs {
16148        /** @see InstallParams#origin */
16149        final OriginInfo origin;
16150        /** @see InstallParams#move */
16151        final MoveInfo move;
16152
16153        final IPackageInstallObserver2 observer;
16154        // Always refers to PackageManager flags only
16155        final int installFlags;
16156        final String installerPackageName;
16157        final String volumeUuid;
16158        final UserHandle user;
16159        final String abiOverride;
16160        final String[] installGrantPermissions;
16161        /** If non-null, drop an async trace when the install completes */
16162        final String traceMethod;
16163        final int traceCookie;
16164        final Certificate[][] certificates;
16165        final int installReason;
16166
16167        // The list of instruction sets supported by this app. This is currently
16168        // only used during the rmdex() phase to clean up resources. We can get rid of this
16169        // if we move dex files under the common app path.
16170        /* nullable */ String[] instructionSets;
16171
16172        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16173                int installFlags, String installerPackageName, String volumeUuid,
16174                UserHandle user, String[] instructionSets,
16175                String abiOverride, String[] installGrantPermissions,
16176                String traceMethod, int traceCookie, Certificate[][] certificates,
16177                int installReason) {
16178            this.origin = origin;
16179            this.move = move;
16180            this.installFlags = installFlags;
16181            this.observer = observer;
16182            this.installerPackageName = installerPackageName;
16183            this.volumeUuid = volumeUuid;
16184            this.user = user;
16185            this.instructionSets = instructionSets;
16186            this.abiOverride = abiOverride;
16187            this.installGrantPermissions = installGrantPermissions;
16188            this.traceMethod = traceMethod;
16189            this.traceCookie = traceCookie;
16190            this.certificates = certificates;
16191            this.installReason = installReason;
16192        }
16193
16194        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16195        abstract int doPreInstall(int status);
16196
16197        /**
16198         * Rename package into final resting place. All paths on the given
16199         * scanned package should be updated to reflect the rename.
16200         */
16201        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16202        abstract int doPostInstall(int status, int uid);
16203
16204        /** @see PackageSettingBase#codePathString */
16205        abstract String getCodePath();
16206        /** @see PackageSettingBase#resourcePathString */
16207        abstract String getResourcePath();
16208
16209        // Need installer lock especially for dex file removal.
16210        abstract void cleanUpResourcesLI();
16211        abstract boolean doPostDeleteLI(boolean delete);
16212
16213        /**
16214         * Called before the source arguments are copied. This is used mostly
16215         * for MoveParams when it needs to read the source file to put it in the
16216         * destination.
16217         */
16218        int doPreCopy() {
16219            return PackageManager.INSTALL_SUCCEEDED;
16220        }
16221
16222        /**
16223         * Called after the source arguments are copied. This is used mostly for
16224         * MoveParams when it needs to read the source file to put it in the
16225         * destination.
16226         */
16227        int doPostCopy(int uid) {
16228            return PackageManager.INSTALL_SUCCEEDED;
16229        }
16230
16231        protected boolean isFwdLocked() {
16232            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16233        }
16234
16235        protected boolean isExternalAsec() {
16236            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16237        }
16238
16239        protected boolean isEphemeral() {
16240            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16241        }
16242
16243        UserHandle getUser() {
16244            return user;
16245        }
16246    }
16247
16248    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16249        if (!allCodePaths.isEmpty()) {
16250            if (instructionSets == null) {
16251                throw new IllegalStateException("instructionSet == null");
16252            }
16253            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16254            for (String codePath : allCodePaths) {
16255                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16256                    try {
16257                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16258                    } catch (InstallerException ignored) {
16259                    }
16260                }
16261            }
16262        }
16263    }
16264
16265    /**
16266     * Logic to handle installation of non-ASEC applications, including copying
16267     * and renaming logic.
16268     */
16269    class FileInstallArgs extends InstallArgs {
16270        private File codeFile;
16271        private File resourceFile;
16272
16273        // Example topology:
16274        // /data/app/com.example/base.apk
16275        // /data/app/com.example/split_foo.apk
16276        // /data/app/com.example/lib/arm/libfoo.so
16277        // /data/app/com.example/lib/arm64/libfoo.so
16278        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16279
16280        /** New install */
16281        FileInstallArgs(InstallParams params) {
16282            super(params.origin, params.move, params.observer, params.installFlags,
16283                    params.installerPackageName, params.volumeUuid,
16284                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16285                    params.grantedRuntimePermissions,
16286                    params.traceMethod, params.traceCookie, params.certificates,
16287                    params.installReason);
16288            if (isFwdLocked()) {
16289                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16290            }
16291        }
16292
16293        /** Existing install */
16294        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16295            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16296                    null, null, null, 0, null /*certificates*/,
16297                    PackageManager.INSTALL_REASON_UNKNOWN);
16298            this.codeFile = (codePath != null) ? new File(codePath) : null;
16299            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16300        }
16301
16302        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16303            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16304            try {
16305                return doCopyApk(imcs, temp);
16306            } finally {
16307                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16308            }
16309        }
16310
16311        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16312            if (origin.staged) {
16313                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16314                codeFile = origin.file;
16315                resourceFile = origin.file;
16316                return PackageManager.INSTALL_SUCCEEDED;
16317            }
16318
16319            try {
16320                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16321                final File tempDir =
16322                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16323                codeFile = tempDir;
16324                resourceFile = tempDir;
16325            } catch (IOException e) {
16326                Slog.w(TAG, "Failed to create copy file: " + e);
16327                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16328            }
16329
16330            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16331                @Override
16332                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16333                    if (!FileUtils.isValidExtFilename(name)) {
16334                        throw new IllegalArgumentException("Invalid filename: " + name);
16335                    }
16336                    try {
16337                        final File file = new File(codeFile, name);
16338                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16339                                O_RDWR | O_CREAT, 0644);
16340                        Os.chmod(file.getAbsolutePath(), 0644);
16341                        return new ParcelFileDescriptor(fd);
16342                    } catch (ErrnoException e) {
16343                        throw new RemoteException("Failed to open: " + e.getMessage());
16344                    }
16345                }
16346            };
16347
16348            int ret = PackageManager.INSTALL_SUCCEEDED;
16349            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16350            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16351                Slog.e(TAG, "Failed to copy package");
16352                return ret;
16353            }
16354
16355            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16356            NativeLibraryHelper.Handle handle = null;
16357            try {
16358                handle = NativeLibraryHelper.Handle.create(codeFile);
16359                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16360                        abiOverride);
16361            } catch (IOException e) {
16362                Slog.e(TAG, "Copying native libraries failed", e);
16363                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16364            } finally {
16365                IoUtils.closeQuietly(handle);
16366            }
16367
16368            return ret;
16369        }
16370
16371        int doPreInstall(int status) {
16372            if (status != PackageManager.INSTALL_SUCCEEDED) {
16373                cleanUp();
16374            }
16375            return status;
16376        }
16377
16378        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16379            if (status != PackageManager.INSTALL_SUCCEEDED) {
16380                cleanUp();
16381                return false;
16382            }
16383
16384            final File targetDir = codeFile.getParentFile();
16385            final File beforeCodeFile = codeFile;
16386            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16387
16388            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16389            try {
16390                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16391            } catch (ErrnoException e) {
16392                Slog.w(TAG, "Failed to rename", e);
16393                return false;
16394            }
16395
16396            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16397                Slog.w(TAG, "Failed to restorecon");
16398                return false;
16399            }
16400
16401            // Reflect the rename internally
16402            codeFile = afterCodeFile;
16403            resourceFile = afterCodeFile;
16404
16405            // Reflect the rename in scanned details
16406            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16407            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16408                    afterCodeFile, pkg.baseCodePath));
16409            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16410                    afterCodeFile, pkg.splitCodePaths));
16411
16412            // Reflect the rename in app info
16413            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16414            pkg.setApplicationInfoCodePath(pkg.codePath);
16415            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16416            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16417            pkg.setApplicationInfoResourcePath(pkg.codePath);
16418            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16419            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16420
16421            return true;
16422        }
16423
16424        int doPostInstall(int status, int uid) {
16425            if (status != PackageManager.INSTALL_SUCCEEDED) {
16426                cleanUp();
16427            }
16428            return status;
16429        }
16430
16431        @Override
16432        String getCodePath() {
16433            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16434        }
16435
16436        @Override
16437        String getResourcePath() {
16438            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16439        }
16440
16441        private boolean cleanUp() {
16442            if (codeFile == null || !codeFile.exists()) {
16443                return false;
16444            }
16445
16446            removeCodePathLI(codeFile);
16447
16448            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16449                resourceFile.delete();
16450            }
16451
16452            return true;
16453        }
16454
16455        void cleanUpResourcesLI() {
16456            // Try enumerating all code paths before deleting
16457            List<String> allCodePaths = Collections.EMPTY_LIST;
16458            if (codeFile != null && codeFile.exists()) {
16459                try {
16460                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16461                    allCodePaths = pkg.getAllCodePaths();
16462                } catch (PackageParserException e) {
16463                    // Ignored; we tried our best
16464                }
16465            }
16466
16467            cleanUp();
16468            removeDexFiles(allCodePaths, instructionSets);
16469        }
16470
16471        boolean doPostDeleteLI(boolean delete) {
16472            // XXX err, shouldn't we respect the delete flag?
16473            cleanUpResourcesLI();
16474            return true;
16475        }
16476    }
16477
16478    private boolean isAsecExternal(String cid) {
16479        final String asecPath = PackageHelper.getSdFilesystem(cid);
16480        return !asecPath.startsWith(mAsecInternalPath);
16481    }
16482
16483    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16484            PackageManagerException {
16485        if (copyRet < 0) {
16486            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16487                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16488                throw new PackageManagerException(copyRet, message);
16489            }
16490        }
16491    }
16492
16493    /**
16494     * Extract the StorageManagerService "container ID" from the full code path of an
16495     * .apk.
16496     */
16497    static String cidFromCodePath(String fullCodePath) {
16498        int eidx = fullCodePath.lastIndexOf("/");
16499        String subStr1 = fullCodePath.substring(0, eidx);
16500        int sidx = subStr1.lastIndexOf("/");
16501        return subStr1.substring(sidx+1, eidx);
16502    }
16503
16504    /**
16505     * Logic to handle installation of ASEC applications, including copying and
16506     * renaming logic.
16507     */
16508    class AsecInstallArgs extends InstallArgs {
16509        static final String RES_FILE_NAME = "pkg.apk";
16510        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16511
16512        String cid;
16513        String packagePath;
16514        String resourcePath;
16515
16516        /** New install */
16517        AsecInstallArgs(InstallParams params) {
16518            super(params.origin, params.move, params.observer, params.installFlags,
16519                    params.installerPackageName, params.volumeUuid,
16520                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16521                    params.grantedRuntimePermissions,
16522                    params.traceMethod, params.traceCookie, params.certificates,
16523                    params.installReason);
16524        }
16525
16526        /** Existing install */
16527        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16528                        boolean isExternal, boolean isForwardLocked) {
16529            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16530                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16531                    instructionSets, null, null, null, 0, null /*certificates*/,
16532                    PackageManager.INSTALL_REASON_UNKNOWN);
16533            // Hackily pretend we're still looking at a full code path
16534            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16535                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16536            }
16537
16538            // Extract cid from fullCodePath
16539            int eidx = fullCodePath.lastIndexOf("/");
16540            String subStr1 = fullCodePath.substring(0, eidx);
16541            int sidx = subStr1.lastIndexOf("/");
16542            cid = subStr1.substring(sidx+1, eidx);
16543            setMountPath(subStr1);
16544        }
16545
16546        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16547            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16548                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16549                    instructionSets, null, null, null, 0, null /*certificates*/,
16550                    PackageManager.INSTALL_REASON_UNKNOWN);
16551            this.cid = cid;
16552            setMountPath(PackageHelper.getSdDir(cid));
16553        }
16554
16555        void createCopyFile() {
16556            cid = mInstallerService.allocateExternalStageCidLegacy();
16557        }
16558
16559        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16560            if (origin.staged && origin.cid != null) {
16561                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16562                cid = origin.cid;
16563                setMountPath(PackageHelper.getSdDir(cid));
16564                return PackageManager.INSTALL_SUCCEEDED;
16565            }
16566
16567            if (temp) {
16568                createCopyFile();
16569            } else {
16570                /*
16571                 * Pre-emptively destroy the container since it's destroyed if
16572                 * copying fails due to it existing anyway.
16573                 */
16574                PackageHelper.destroySdDir(cid);
16575            }
16576
16577            final String newMountPath = imcs.copyPackageToContainer(
16578                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16579                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16580
16581            if (newMountPath != null) {
16582                setMountPath(newMountPath);
16583                return PackageManager.INSTALL_SUCCEEDED;
16584            } else {
16585                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16586            }
16587        }
16588
16589        @Override
16590        String getCodePath() {
16591            return packagePath;
16592        }
16593
16594        @Override
16595        String getResourcePath() {
16596            return resourcePath;
16597        }
16598
16599        int doPreInstall(int status) {
16600            if (status != PackageManager.INSTALL_SUCCEEDED) {
16601                // Destroy container
16602                PackageHelper.destroySdDir(cid);
16603            } else {
16604                boolean mounted = PackageHelper.isContainerMounted(cid);
16605                if (!mounted) {
16606                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16607                            Process.SYSTEM_UID);
16608                    if (newMountPath != null) {
16609                        setMountPath(newMountPath);
16610                    } else {
16611                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16612                    }
16613                }
16614            }
16615            return status;
16616        }
16617
16618        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16619            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16620            String newMountPath = null;
16621            if (PackageHelper.isContainerMounted(cid)) {
16622                // Unmount the container
16623                if (!PackageHelper.unMountSdDir(cid)) {
16624                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16625                    return false;
16626                }
16627            }
16628            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16629                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16630                        " which might be stale. Will try to clean up.");
16631                // Clean up the stale container and proceed to recreate.
16632                if (!PackageHelper.destroySdDir(newCacheId)) {
16633                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16634                    return false;
16635                }
16636                // Successfully cleaned up stale container. Try to rename again.
16637                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16638                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16639                            + " inspite of cleaning it up.");
16640                    return false;
16641                }
16642            }
16643            if (!PackageHelper.isContainerMounted(newCacheId)) {
16644                Slog.w(TAG, "Mounting container " + newCacheId);
16645                newMountPath = PackageHelper.mountSdDir(newCacheId,
16646                        getEncryptKey(), Process.SYSTEM_UID);
16647            } else {
16648                newMountPath = PackageHelper.getSdDir(newCacheId);
16649            }
16650            if (newMountPath == null) {
16651                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16652                return false;
16653            }
16654            Log.i(TAG, "Succesfully renamed " + cid +
16655                    " to " + newCacheId +
16656                    " at new path: " + newMountPath);
16657            cid = newCacheId;
16658
16659            final File beforeCodeFile = new File(packagePath);
16660            setMountPath(newMountPath);
16661            final File afterCodeFile = new File(packagePath);
16662
16663            // Reflect the rename in scanned details
16664            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16665            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16666                    afterCodeFile, pkg.baseCodePath));
16667            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16668                    afterCodeFile, pkg.splitCodePaths));
16669
16670            // Reflect the rename in app info
16671            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16672            pkg.setApplicationInfoCodePath(pkg.codePath);
16673            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16674            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16675            pkg.setApplicationInfoResourcePath(pkg.codePath);
16676            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16677            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16678
16679            return true;
16680        }
16681
16682        private void setMountPath(String mountPath) {
16683            final File mountFile = new File(mountPath);
16684
16685            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16686            if (monolithicFile.exists()) {
16687                packagePath = monolithicFile.getAbsolutePath();
16688                if (isFwdLocked()) {
16689                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16690                } else {
16691                    resourcePath = packagePath;
16692                }
16693            } else {
16694                packagePath = mountFile.getAbsolutePath();
16695                resourcePath = packagePath;
16696            }
16697        }
16698
16699        int doPostInstall(int status, int uid) {
16700            if (status != PackageManager.INSTALL_SUCCEEDED) {
16701                cleanUp();
16702            } else {
16703                final int groupOwner;
16704                final String protectedFile;
16705                if (isFwdLocked()) {
16706                    groupOwner = UserHandle.getSharedAppGid(uid);
16707                    protectedFile = RES_FILE_NAME;
16708                } else {
16709                    groupOwner = -1;
16710                    protectedFile = null;
16711                }
16712
16713                if (uid < Process.FIRST_APPLICATION_UID
16714                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16715                    Slog.e(TAG, "Failed to finalize " + cid);
16716                    PackageHelper.destroySdDir(cid);
16717                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16718                }
16719
16720                boolean mounted = PackageHelper.isContainerMounted(cid);
16721                if (!mounted) {
16722                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16723                }
16724            }
16725            return status;
16726        }
16727
16728        private void cleanUp() {
16729            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16730
16731            // Destroy secure container
16732            PackageHelper.destroySdDir(cid);
16733        }
16734
16735        private List<String> getAllCodePaths() {
16736            final File codeFile = new File(getCodePath());
16737            if (codeFile != null && codeFile.exists()) {
16738                try {
16739                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16740                    return pkg.getAllCodePaths();
16741                } catch (PackageParserException e) {
16742                    // Ignored; we tried our best
16743                }
16744            }
16745            return Collections.EMPTY_LIST;
16746        }
16747
16748        void cleanUpResourcesLI() {
16749            // Enumerate all code paths before deleting
16750            cleanUpResourcesLI(getAllCodePaths());
16751        }
16752
16753        private void cleanUpResourcesLI(List<String> allCodePaths) {
16754            cleanUp();
16755            removeDexFiles(allCodePaths, instructionSets);
16756        }
16757
16758        String getPackageName() {
16759            return getAsecPackageName(cid);
16760        }
16761
16762        boolean doPostDeleteLI(boolean delete) {
16763            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16764            final List<String> allCodePaths = getAllCodePaths();
16765            boolean mounted = PackageHelper.isContainerMounted(cid);
16766            if (mounted) {
16767                // Unmount first
16768                if (PackageHelper.unMountSdDir(cid)) {
16769                    mounted = false;
16770                }
16771            }
16772            if (!mounted && delete) {
16773                cleanUpResourcesLI(allCodePaths);
16774            }
16775            return !mounted;
16776        }
16777
16778        @Override
16779        int doPreCopy() {
16780            if (isFwdLocked()) {
16781                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16782                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16783                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16784                }
16785            }
16786
16787            return PackageManager.INSTALL_SUCCEEDED;
16788        }
16789
16790        @Override
16791        int doPostCopy(int uid) {
16792            if (isFwdLocked()) {
16793                if (uid < Process.FIRST_APPLICATION_UID
16794                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16795                                RES_FILE_NAME)) {
16796                    Slog.e(TAG, "Failed to finalize " + cid);
16797                    PackageHelper.destroySdDir(cid);
16798                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16799                }
16800            }
16801
16802            return PackageManager.INSTALL_SUCCEEDED;
16803        }
16804    }
16805
16806    /**
16807     * Logic to handle movement of existing installed applications.
16808     */
16809    class MoveInstallArgs extends InstallArgs {
16810        private File codeFile;
16811        private File resourceFile;
16812
16813        /** New install */
16814        MoveInstallArgs(InstallParams params) {
16815            super(params.origin, params.move, params.observer, params.installFlags,
16816                    params.installerPackageName, params.volumeUuid,
16817                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16818                    params.grantedRuntimePermissions,
16819                    params.traceMethod, params.traceCookie, params.certificates,
16820                    params.installReason);
16821        }
16822
16823        int copyApk(IMediaContainerService imcs, boolean temp) {
16824            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16825                    + move.fromUuid + " to " + move.toUuid);
16826            synchronized (mInstaller) {
16827                try {
16828                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16829                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16830                } catch (InstallerException e) {
16831                    Slog.w(TAG, "Failed to move app", e);
16832                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16833                }
16834            }
16835
16836            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16837            resourceFile = codeFile;
16838            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16839
16840            return PackageManager.INSTALL_SUCCEEDED;
16841        }
16842
16843        int doPreInstall(int status) {
16844            if (status != PackageManager.INSTALL_SUCCEEDED) {
16845                cleanUp(move.toUuid);
16846            }
16847            return status;
16848        }
16849
16850        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16851            if (status != PackageManager.INSTALL_SUCCEEDED) {
16852                cleanUp(move.toUuid);
16853                return false;
16854            }
16855
16856            // Reflect the move in app info
16857            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16858            pkg.setApplicationInfoCodePath(pkg.codePath);
16859            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16860            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16861            pkg.setApplicationInfoResourcePath(pkg.codePath);
16862            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16863            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16864
16865            return true;
16866        }
16867
16868        int doPostInstall(int status, int uid) {
16869            if (status == PackageManager.INSTALL_SUCCEEDED) {
16870                cleanUp(move.fromUuid);
16871            } else {
16872                cleanUp(move.toUuid);
16873            }
16874            return status;
16875        }
16876
16877        @Override
16878        String getCodePath() {
16879            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16880        }
16881
16882        @Override
16883        String getResourcePath() {
16884            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16885        }
16886
16887        private boolean cleanUp(String volumeUuid) {
16888            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16889                    move.dataAppName);
16890            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16891            final int[] userIds = sUserManager.getUserIds();
16892            synchronized (mInstallLock) {
16893                // Clean up both app data and code
16894                // All package moves are frozen until finished
16895                for (int userId : userIds) {
16896                    try {
16897                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16898                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16899                    } catch (InstallerException e) {
16900                        Slog.w(TAG, String.valueOf(e));
16901                    }
16902                }
16903                removeCodePathLI(codeFile);
16904            }
16905            return true;
16906        }
16907
16908        void cleanUpResourcesLI() {
16909            throw new UnsupportedOperationException();
16910        }
16911
16912        boolean doPostDeleteLI(boolean delete) {
16913            throw new UnsupportedOperationException();
16914        }
16915    }
16916
16917    static String getAsecPackageName(String packageCid) {
16918        int idx = packageCid.lastIndexOf("-");
16919        if (idx == -1) {
16920            return packageCid;
16921        }
16922        return packageCid.substring(0, idx);
16923    }
16924
16925    // Utility method used to create code paths based on package name and available index.
16926    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16927        String idxStr = "";
16928        int idx = 1;
16929        // Fall back to default value of idx=1 if prefix is not
16930        // part of oldCodePath
16931        if (oldCodePath != null) {
16932            String subStr = oldCodePath;
16933            // Drop the suffix right away
16934            if (suffix != null && subStr.endsWith(suffix)) {
16935                subStr = subStr.substring(0, subStr.length() - suffix.length());
16936            }
16937            // If oldCodePath already contains prefix find out the
16938            // ending index to either increment or decrement.
16939            int sidx = subStr.lastIndexOf(prefix);
16940            if (sidx != -1) {
16941                subStr = subStr.substring(sidx + prefix.length());
16942                if (subStr != null) {
16943                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16944                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16945                    }
16946                    try {
16947                        idx = Integer.parseInt(subStr);
16948                        if (idx <= 1) {
16949                            idx++;
16950                        } else {
16951                            idx--;
16952                        }
16953                    } catch(NumberFormatException e) {
16954                    }
16955                }
16956            }
16957        }
16958        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16959        return prefix + idxStr;
16960    }
16961
16962    private File getNextCodePath(File targetDir, String packageName) {
16963        File result;
16964        SecureRandom random = new SecureRandom();
16965        byte[] bytes = new byte[16];
16966        do {
16967            random.nextBytes(bytes);
16968            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16969            result = new File(targetDir, packageName + "-" + suffix);
16970        } while (result.exists());
16971        return result;
16972    }
16973
16974    // Utility method that returns the relative package path with respect
16975    // to the installation directory. Like say for /data/data/com.test-1.apk
16976    // string com.test-1 is returned.
16977    static String deriveCodePathName(String codePath) {
16978        if (codePath == null) {
16979            return null;
16980        }
16981        final File codeFile = new File(codePath);
16982        final String name = codeFile.getName();
16983        if (codeFile.isDirectory()) {
16984            return name;
16985        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16986            final int lastDot = name.lastIndexOf('.');
16987            return name.substring(0, lastDot);
16988        } else {
16989            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16990            return null;
16991        }
16992    }
16993
16994    static class PackageInstalledInfo {
16995        String name;
16996        int uid;
16997        // The set of users that originally had this package installed.
16998        int[] origUsers;
16999        // The set of users that now have this package installed.
17000        int[] newUsers;
17001        PackageParser.Package pkg;
17002        int returnCode;
17003        String returnMsg;
17004        PackageRemovedInfo removedInfo;
17005        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17006
17007        public void setError(int code, String msg) {
17008            setReturnCode(code);
17009            setReturnMessage(msg);
17010            Slog.w(TAG, msg);
17011        }
17012
17013        public void setError(String msg, PackageParserException e) {
17014            setReturnCode(e.error);
17015            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17016            Slog.w(TAG, msg, e);
17017        }
17018
17019        public void setError(String msg, PackageManagerException e) {
17020            returnCode = e.error;
17021            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17022            Slog.w(TAG, msg, e);
17023        }
17024
17025        public void setReturnCode(int returnCode) {
17026            this.returnCode = returnCode;
17027            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17028            for (int i = 0; i < childCount; i++) {
17029                addedChildPackages.valueAt(i).returnCode = returnCode;
17030            }
17031        }
17032
17033        private void setReturnMessage(String returnMsg) {
17034            this.returnMsg = returnMsg;
17035            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17036            for (int i = 0; i < childCount; i++) {
17037                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17038            }
17039        }
17040
17041        // In some error cases we want to convey more info back to the observer
17042        String origPackage;
17043        String origPermission;
17044    }
17045
17046    /*
17047     * Install a non-existing package.
17048     */
17049    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17050            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17051            PackageInstalledInfo res, int installReason) {
17052        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17053
17054        // Remember this for later, in case we need to rollback this install
17055        String pkgName = pkg.packageName;
17056
17057        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17058
17059        synchronized(mPackages) {
17060            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17061            if (renamedPackage != null) {
17062                // A package with the same name is already installed, though
17063                // it has been renamed to an older name.  The package we
17064                // are trying to install should be installed as an update to
17065                // the existing one, but that has not been requested, so bail.
17066                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17067                        + " without first uninstalling package running as "
17068                        + renamedPackage);
17069                return;
17070            }
17071            if (mPackages.containsKey(pkgName)) {
17072                // Don't allow installation over an existing package with the same name.
17073                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17074                        + " without first uninstalling.");
17075                return;
17076            }
17077        }
17078
17079        try {
17080            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17081                    System.currentTimeMillis(), user);
17082
17083            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17084
17085            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17086                prepareAppDataAfterInstallLIF(newPackage);
17087
17088            } else {
17089                // Remove package from internal structures, but keep around any
17090                // data that might have already existed
17091                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17092                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17093            }
17094        } catch (PackageManagerException e) {
17095            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17096        }
17097
17098        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17099    }
17100
17101    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17102        // Can't rotate keys during boot or if sharedUser.
17103        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17104                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17105            return false;
17106        }
17107        // app is using upgradeKeySets; make sure all are valid
17108        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17109        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17110        for (int i = 0; i < upgradeKeySets.length; i++) {
17111            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17112                Slog.wtf(TAG, "Package "
17113                         + (oldPs.name != null ? oldPs.name : "<null>")
17114                         + " contains upgrade-key-set reference to unknown key-set: "
17115                         + upgradeKeySets[i]
17116                         + " reverting to signatures check.");
17117                return false;
17118            }
17119        }
17120        return true;
17121    }
17122
17123    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17124        // Upgrade keysets are being used.  Determine if new package has a superset of the
17125        // required keys.
17126        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17127        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17128        for (int i = 0; i < upgradeKeySets.length; i++) {
17129            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17130            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17131                return true;
17132            }
17133        }
17134        return false;
17135    }
17136
17137    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17138        try (DigestInputStream digestStream =
17139                new DigestInputStream(new FileInputStream(file), digest)) {
17140            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17141        }
17142    }
17143
17144    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17145            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17146            int installReason) {
17147        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17148
17149        final PackageParser.Package oldPackage;
17150        final PackageSetting ps;
17151        final String pkgName = pkg.packageName;
17152        final int[] allUsers;
17153        final int[] installedUsers;
17154
17155        synchronized(mPackages) {
17156            oldPackage = mPackages.get(pkgName);
17157            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17158
17159            // don't allow upgrade to target a release SDK from a pre-release SDK
17160            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17161                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17162            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17163                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17164            if (oldTargetsPreRelease
17165                    && !newTargetsPreRelease
17166                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17167                Slog.w(TAG, "Can't install package targeting released sdk");
17168                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17169                return;
17170            }
17171
17172            ps = mSettings.mPackages.get(pkgName);
17173
17174            // verify signatures are valid
17175            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17176                if (!checkUpgradeKeySetLP(ps, pkg)) {
17177                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17178                            "New package not signed by keys specified by upgrade-keysets: "
17179                                    + pkgName);
17180                    return;
17181                }
17182            } else {
17183                // default to original signature matching
17184                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17185                        != PackageManager.SIGNATURE_MATCH) {
17186                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17187                            "New package has a different signature: " + pkgName);
17188                    return;
17189                }
17190            }
17191
17192            // don't allow a system upgrade unless the upgrade hash matches
17193            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17194                byte[] digestBytes = null;
17195                try {
17196                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17197                    updateDigest(digest, new File(pkg.baseCodePath));
17198                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17199                        for (String path : pkg.splitCodePaths) {
17200                            updateDigest(digest, new File(path));
17201                        }
17202                    }
17203                    digestBytes = digest.digest();
17204                } catch (NoSuchAlgorithmException | IOException e) {
17205                    res.setError(INSTALL_FAILED_INVALID_APK,
17206                            "Could not compute hash: " + pkgName);
17207                    return;
17208                }
17209                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17210                    res.setError(INSTALL_FAILED_INVALID_APK,
17211                            "New package fails restrict-update check: " + pkgName);
17212                    return;
17213                }
17214                // retain upgrade restriction
17215                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17216            }
17217
17218            // Check for shared user id changes
17219            String invalidPackageName =
17220                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17221            if (invalidPackageName != null) {
17222                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17223                        "Package " + invalidPackageName + " tried to change user "
17224                                + oldPackage.mSharedUserId);
17225                return;
17226            }
17227
17228            // In case of rollback, remember per-user/profile install state
17229            allUsers = sUserManager.getUserIds();
17230            installedUsers = ps.queryInstalledUsers(allUsers, true);
17231
17232            // don't allow an upgrade from full to ephemeral
17233            if (isInstantApp) {
17234                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17235                    for (int currentUser : allUsers) {
17236                        if (!ps.getInstantApp(currentUser)) {
17237                            // can't downgrade from full to instant
17238                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17239                                    + " for user: " + currentUser);
17240                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17241                            return;
17242                        }
17243                    }
17244                } else if (!ps.getInstantApp(user.getIdentifier())) {
17245                    // can't downgrade from full to instant
17246                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17247                            + " for user: " + user.getIdentifier());
17248                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17249                    return;
17250                }
17251            }
17252        }
17253
17254        // Update what is removed
17255        res.removedInfo = new PackageRemovedInfo(this);
17256        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17257        res.removedInfo.removedPackage = oldPackage.packageName;
17258        res.removedInfo.installerPackageName = ps.installerPackageName;
17259        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17260        res.removedInfo.isUpdate = true;
17261        res.removedInfo.origUsers = installedUsers;
17262        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17263        for (int i = 0; i < installedUsers.length; i++) {
17264            final int userId = installedUsers[i];
17265            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17266        }
17267
17268        final int childCount = (oldPackage.childPackages != null)
17269                ? oldPackage.childPackages.size() : 0;
17270        for (int i = 0; i < childCount; i++) {
17271            boolean childPackageUpdated = false;
17272            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17273            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17274            if (res.addedChildPackages != null) {
17275                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17276                if (childRes != null) {
17277                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17278                    childRes.removedInfo.removedPackage = childPkg.packageName;
17279                    if (childPs != null) {
17280                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17281                    }
17282                    childRes.removedInfo.isUpdate = true;
17283                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17284                    childPackageUpdated = true;
17285                }
17286            }
17287            if (!childPackageUpdated) {
17288                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17289                childRemovedRes.removedPackage = childPkg.packageName;
17290                if (childPs != null) {
17291                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17292                }
17293                childRemovedRes.isUpdate = false;
17294                childRemovedRes.dataRemoved = true;
17295                synchronized (mPackages) {
17296                    if (childPs != null) {
17297                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17298                    }
17299                }
17300                if (res.removedInfo.removedChildPackages == null) {
17301                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17302                }
17303                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17304            }
17305        }
17306
17307        boolean sysPkg = (isSystemApp(oldPackage));
17308        if (sysPkg) {
17309            // Set the system/privileged flags as needed
17310            final boolean privileged =
17311                    (oldPackage.applicationInfo.privateFlags
17312                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17313            final int systemPolicyFlags = policyFlags
17314                    | PackageParser.PARSE_IS_SYSTEM
17315                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17316
17317            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17318                    user, allUsers, installerPackageName, res, installReason);
17319        } else {
17320            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17321                    user, allUsers, installerPackageName, res, installReason);
17322        }
17323    }
17324
17325    @Override
17326    public List<String> getPreviousCodePaths(String packageName) {
17327        final int callingUid = Binder.getCallingUid();
17328        final List<String> result = new ArrayList<>();
17329        if (getInstantAppPackageName(callingUid) != null) {
17330            return result;
17331        }
17332        final PackageSetting ps = mSettings.mPackages.get(packageName);
17333        if (ps != null
17334                && ps.oldCodePaths != null
17335                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17336            result.addAll(ps.oldCodePaths);
17337        }
17338        return result;
17339    }
17340
17341    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17342            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17343            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17344            int installReason) {
17345        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17346                + deletedPackage);
17347
17348        String pkgName = deletedPackage.packageName;
17349        boolean deletedPkg = true;
17350        boolean addedPkg = false;
17351        boolean updatedSettings = false;
17352        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17353        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17354                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17355
17356        final long origUpdateTime = (pkg.mExtras != null)
17357                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17358
17359        // First delete the existing package while retaining the data directory
17360        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17361                res.removedInfo, true, pkg)) {
17362            // If the existing package wasn't successfully deleted
17363            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17364            deletedPkg = false;
17365        } else {
17366            // Successfully deleted the old package; proceed with replace.
17367
17368            // If deleted package lived in a container, give users a chance to
17369            // relinquish resources before killing.
17370            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17371                if (DEBUG_INSTALL) {
17372                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17373                }
17374                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17375                final ArrayList<String> pkgList = new ArrayList<String>(1);
17376                pkgList.add(deletedPackage.applicationInfo.packageName);
17377                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17378            }
17379
17380            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17381                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17382            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17383
17384            try {
17385                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17386                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17387                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17388                        installReason);
17389
17390                // Update the in-memory copy of the previous code paths.
17391                PackageSetting ps = mSettings.mPackages.get(pkgName);
17392                if (!killApp) {
17393                    if (ps.oldCodePaths == null) {
17394                        ps.oldCodePaths = new ArraySet<>();
17395                    }
17396                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17397                    if (deletedPackage.splitCodePaths != null) {
17398                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17399                    }
17400                } else {
17401                    ps.oldCodePaths = null;
17402                }
17403                if (ps.childPackageNames != null) {
17404                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17405                        final String childPkgName = ps.childPackageNames.get(i);
17406                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17407                        childPs.oldCodePaths = ps.oldCodePaths;
17408                    }
17409                }
17410                // set instant app status, but, only if it's explicitly specified
17411                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17412                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17413                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17414                prepareAppDataAfterInstallLIF(newPackage);
17415                addedPkg = true;
17416                mDexManager.notifyPackageUpdated(newPackage.packageName,
17417                        newPackage.baseCodePath, newPackage.splitCodePaths);
17418            } catch (PackageManagerException e) {
17419                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17420            }
17421        }
17422
17423        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17424            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17425
17426            // Revert all internal state mutations and added folders for the failed install
17427            if (addedPkg) {
17428                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17429                        res.removedInfo, true, null);
17430            }
17431
17432            // Restore the old package
17433            if (deletedPkg) {
17434                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17435                File restoreFile = new File(deletedPackage.codePath);
17436                // Parse old package
17437                boolean oldExternal = isExternal(deletedPackage);
17438                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17439                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17440                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17441                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17442                try {
17443                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17444                            null);
17445                } catch (PackageManagerException e) {
17446                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17447                            + e.getMessage());
17448                    return;
17449                }
17450
17451                synchronized (mPackages) {
17452                    // Ensure the installer package name up to date
17453                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17454
17455                    // Update permissions for restored package
17456                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17457
17458                    mSettings.writeLPr();
17459                }
17460
17461                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17462            }
17463        } else {
17464            synchronized (mPackages) {
17465                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17466                if (ps != null) {
17467                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17468                    if (res.removedInfo.removedChildPackages != null) {
17469                        final int childCount = res.removedInfo.removedChildPackages.size();
17470                        // Iterate in reverse as we may modify the collection
17471                        for (int i = childCount - 1; i >= 0; i--) {
17472                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17473                            if (res.addedChildPackages.containsKey(childPackageName)) {
17474                                res.removedInfo.removedChildPackages.removeAt(i);
17475                            } else {
17476                                PackageRemovedInfo childInfo = res.removedInfo
17477                                        .removedChildPackages.valueAt(i);
17478                                childInfo.removedForAllUsers = mPackages.get(
17479                                        childInfo.removedPackage) == null;
17480                            }
17481                        }
17482                    }
17483                }
17484            }
17485        }
17486    }
17487
17488    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17489            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17490            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17491            int installReason) {
17492        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17493                + ", old=" + deletedPackage);
17494
17495        final boolean disabledSystem;
17496
17497        // Remove existing system package
17498        removePackageLI(deletedPackage, true);
17499
17500        synchronized (mPackages) {
17501            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17502        }
17503        if (!disabledSystem) {
17504            // We didn't need to disable the .apk as a current system package,
17505            // which means we are replacing another update that is already
17506            // installed.  We need to make sure to delete the older one's .apk.
17507            res.removedInfo.args = createInstallArgsForExisting(0,
17508                    deletedPackage.applicationInfo.getCodePath(),
17509                    deletedPackage.applicationInfo.getResourcePath(),
17510                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17511        } else {
17512            res.removedInfo.args = null;
17513        }
17514
17515        // Successfully disabled the old package. Now proceed with re-installation
17516        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17517                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17518        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17519
17520        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17521        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17522                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17523
17524        PackageParser.Package newPackage = null;
17525        try {
17526            // Add the package to the internal data structures
17527            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17528
17529            // Set the update and install times
17530            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17531            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17532                    System.currentTimeMillis());
17533
17534            // Update the package dynamic state if succeeded
17535            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17536                // Now that the install succeeded make sure we remove data
17537                // directories for any child package the update removed.
17538                final int deletedChildCount = (deletedPackage.childPackages != null)
17539                        ? deletedPackage.childPackages.size() : 0;
17540                final int newChildCount = (newPackage.childPackages != null)
17541                        ? newPackage.childPackages.size() : 0;
17542                for (int i = 0; i < deletedChildCount; i++) {
17543                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17544                    boolean childPackageDeleted = true;
17545                    for (int j = 0; j < newChildCount; j++) {
17546                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17547                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17548                            childPackageDeleted = false;
17549                            break;
17550                        }
17551                    }
17552                    if (childPackageDeleted) {
17553                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17554                                deletedChildPkg.packageName);
17555                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17556                            PackageRemovedInfo removedChildRes = res.removedInfo
17557                                    .removedChildPackages.get(deletedChildPkg.packageName);
17558                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17559                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17560                        }
17561                    }
17562                }
17563
17564                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17565                        installReason);
17566                prepareAppDataAfterInstallLIF(newPackage);
17567
17568                mDexManager.notifyPackageUpdated(newPackage.packageName,
17569                            newPackage.baseCodePath, newPackage.splitCodePaths);
17570            }
17571        } catch (PackageManagerException e) {
17572            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17573            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17574        }
17575
17576        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17577            // Re installation failed. Restore old information
17578            // Remove new pkg information
17579            if (newPackage != null) {
17580                removeInstalledPackageLI(newPackage, true);
17581            }
17582            // Add back the old system package
17583            try {
17584                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17585            } catch (PackageManagerException e) {
17586                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17587            }
17588
17589            synchronized (mPackages) {
17590                if (disabledSystem) {
17591                    enableSystemPackageLPw(deletedPackage);
17592                }
17593
17594                // Ensure the installer package name up to date
17595                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17596
17597                // Update permissions for restored package
17598                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17599
17600                mSettings.writeLPr();
17601            }
17602
17603            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17604                    + " after failed upgrade");
17605        }
17606    }
17607
17608    /**
17609     * Checks whether the parent or any of the child packages have a change shared
17610     * user. For a package to be a valid update the shred users of the parent and
17611     * the children should match. We may later support changing child shared users.
17612     * @param oldPkg The updated package.
17613     * @param newPkg The update package.
17614     * @return The shared user that change between the versions.
17615     */
17616    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17617            PackageParser.Package newPkg) {
17618        // Check parent shared user
17619        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17620            return newPkg.packageName;
17621        }
17622        // Check child shared users
17623        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17624        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17625        for (int i = 0; i < newChildCount; i++) {
17626            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17627            // If this child was present, did it have the same shared user?
17628            for (int j = 0; j < oldChildCount; j++) {
17629                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17630                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17631                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17632                    return newChildPkg.packageName;
17633                }
17634            }
17635        }
17636        return null;
17637    }
17638
17639    private void removeNativeBinariesLI(PackageSetting ps) {
17640        // Remove the lib path for the parent package
17641        if (ps != null) {
17642            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17643            // Remove the lib path for the child packages
17644            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17645            for (int i = 0; i < childCount; i++) {
17646                PackageSetting childPs = null;
17647                synchronized (mPackages) {
17648                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17649                }
17650                if (childPs != null) {
17651                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17652                            .legacyNativeLibraryPathString);
17653                }
17654            }
17655        }
17656    }
17657
17658    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17659        // Enable the parent package
17660        mSettings.enableSystemPackageLPw(pkg.packageName);
17661        // Enable the child packages
17662        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17663        for (int i = 0; i < childCount; i++) {
17664            PackageParser.Package childPkg = pkg.childPackages.get(i);
17665            mSettings.enableSystemPackageLPw(childPkg.packageName);
17666        }
17667    }
17668
17669    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17670            PackageParser.Package newPkg) {
17671        // Disable the parent package (parent always replaced)
17672        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17673        // Disable the child packages
17674        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17675        for (int i = 0; i < childCount; i++) {
17676            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17677            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17678            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17679        }
17680        return disabled;
17681    }
17682
17683    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17684            String installerPackageName) {
17685        // Enable the parent package
17686        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17687        // Enable the child packages
17688        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17689        for (int i = 0; i < childCount; i++) {
17690            PackageParser.Package childPkg = pkg.childPackages.get(i);
17691            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17692        }
17693    }
17694
17695    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17696        // Collect all used permissions in the UID
17697        ArraySet<String> usedPermissions = new ArraySet<>();
17698        final int packageCount = su.packages.size();
17699        for (int i = 0; i < packageCount; i++) {
17700            PackageSetting ps = su.packages.valueAt(i);
17701            if (ps.pkg == null) {
17702                continue;
17703            }
17704            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17705            for (int j = 0; j < requestedPermCount; j++) {
17706                String permission = ps.pkg.requestedPermissions.get(j);
17707                BasePermission bp = mSettings.mPermissions.get(permission);
17708                if (bp != null) {
17709                    usedPermissions.add(permission);
17710                }
17711            }
17712        }
17713
17714        PermissionsState permissionsState = su.getPermissionsState();
17715        // Prune install permissions
17716        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17717        final int installPermCount = installPermStates.size();
17718        for (int i = installPermCount - 1; i >= 0;  i--) {
17719            PermissionState permissionState = installPermStates.get(i);
17720            if (!usedPermissions.contains(permissionState.getName())) {
17721                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17722                if (bp != null) {
17723                    permissionsState.revokeInstallPermission(bp);
17724                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17725                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17726                }
17727            }
17728        }
17729
17730        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17731
17732        // Prune runtime permissions
17733        for (int userId : allUserIds) {
17734            List<PermissionState> runtimePermStates = permissionsState
17735                    .getRuntimePermissionStates(userId);
17736            final int runtimePermCount = runtimePermStates.size();
17737            for (int i = runtimePermCount - 1; i >= 0; i--) {
17738                PermissionState permissionState = runtimePermStates.get(i);
17739                if (!usedPermissions.contains(permissionState.getName())) {
17740                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17741                    if (bp != null) {
17742                        permissionsState.revokeRuntimePermission(bp, userId);
17743                        permissionsState.updatePermissionFlags(bp, userId,
17744                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17745                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17746                                runtimePermissionChangedUserIds, userId);
17747                    }
17748                }
17749            }
17750        }
17751
17752        return runtimePermissionChangedUserIds;
17753    }
17754
17755    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17756            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17757        // Update the parent package setting
17758        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17759                res, user, installReason);
17760        // Update the child packages setting
17761        final int childCount = (newPackage.childPackages != null)
17762                ? newPackage.childPackages.size() : 0;
17763        for (int i = 0; i < childCount; i++) {
17764            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17765            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17766            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17767                    childRes.origUsers, childRes, user, installReason);
17768        }
17769    }
17770
17771    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17772            String installerPackageName, int[] allUsers, int[] installedForUsers,
17773            PackageInstalledInfo res, UserHandle user, int installReason) {
17774        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17775
17776        String pkgName = newPackage.packageName;
17777        synchronized (mPackages) {
17778            //write settings. the installStatus will be incomplete at this stage.
17779            //note that the new package setting would have already been
17780            //added to mPackages. It hasn't been persisted yet.
17781            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17782            // TODO: Remove this write? It's also written at the end of this method
17783            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17784            mSettings.writeLPr();
17785            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17786        }
17787
17788        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17789        synchronized (mPackages) {
17790            updatePermissionsLPw(newPackage.packageName, newPackage,
17791                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17792                            ? UPDATE_PERMISSIONS_ALL : 0));
17793            // For system-bundled packages, we assume that installing an upgraded version
17794            // of the package implies that the user actually wants to run that new code,
17795            // so we enable the package.
17796            PackageSetting ps = mSettings.mPackages.get(pkgName);
17797            final int userId = user.getIdentifier();
17798            if (ps != null) {
17799                if (isSystemApp(newPackage)) {
17800                    if (DEBUG_INSTALL) {
17801                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17802                    }
17803                    // Enable system package for requested users
17804                    if (res.origUsers != null) {
17805                        for (int origUserId : res.origUsers) {
17806                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17807                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17808                                        origUserId, installerPackageName);
17809                            }
17810                        }
17811                    }
17812                    // Also convey the prior install/uninstall state
17813                    if (allUsers != null && installedForUsers != null) {
17814                        for (int currentUserId : allUsers) {
17815                            final boolean installed = ArrayUtils.contains(
17816                                    installedForUsers, currentUserId);
17817                            if (DEBUG_INSTALL) {
17818                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17819                            }
17820                            ps.setInstalled(installed, currentUserId);
17821                        }
17822                        // these install state changes will be persisted in the
17823                        // upcoming call to mSettings.writeLPr().
17824                    }
17825                }
17826                // It's implied that when a user requests installation, they want the app to be
17827                // installed and enabled.
17828                if (userId != UserHandle.USER_ALL) {
17829                    ps.setInstalled(true, userId);
17830                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17831                }
17832
17833                // When replacing an existing package, preserve the original install reason for all
17834                // users that had the package installed before.
17835                final Set<Integer> previousUserIds = new ArraySet<>();
17836                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17837                    final int installReasonCount = res.removedInfo.installReasons.size();
17838                    for (int i = 0; i < installReasonCount; i++) {
17839                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17840                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17841                        ps.setInstallReason(previousInstallReason, previousUserId);
17842                        previousUserIds.add(previousUserId);
17843                    }
17844                }
17845
17846                // Set install reason for users that are having the package newly installed.
17847                if (userId == UserHandle.USER_ALL) {
17848                    for (int currentUserId : sUserManager.getUserIds()) {
17849                        if (!previousUserIds.contains(currentUserId)) {
17850                            ps.setInstallReason(installReason, currentUserId);
17851                        }
17852                    }
17853                } else if (!previousUserIds.contains(userId)) {
17854                    ps.setInstallReason(installReason, userId);
17855                }
17856                mSettings.writeKernelMappingLPr(ps);
17857            }
17858            res.name = pkgName;
17859            res.uid = newPackage.applicationInfo.uid;
17860            res.pkg = newPackage;
17861            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17862            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17863            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17864            //to update install status
17865            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17866            mSettings.writeLPr();
17867            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17868        }
17869
17870        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17871    }
17872
17873    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17874        try {
17875            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17876            installPackageLI(args, res);
17877        } finally {
17878            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17879        }
17880    }
17881
17882    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17883        final int installFlags = args.installFlags;
17884        final String installerPackageName = args.installerPackageName;
17885        final String volumeUuid = args.volumeUuid;
17886        final File tmpPackageFile = new File(args.getCodePath());
17887        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17888        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17889                || (args.volumeUuid != null));
17890        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17891        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17892        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17893        boolean replace = false;
17894        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17895        if (args.move != null) {
17896            // moving a complete application; perform an initial scan on the new install location
17897            scanFlags |= SCAN_INITIAL;
17898        }
17899        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17900            scanFlags |= SCAN_DONT_KILL_APP;
17901        }
17902        if (instantApp) {
17903            scanFlags |= SCAN_AS_INSTANT_APP;
17904        }
17905        if (fullApp) {
17906            scanFlags |= SCAN_AS_FULL_APP;
17907        }
17908
17909        // Result object to be returned
17910        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17911
17912        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17913
17914        // Sanity check
17915        if (instantApp && (forwardLocked || onExternal)) {
17916            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17917                    + " external=" + onExternal);
17918            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17919            return;
17920        }
17921
17922        // Retrieve PackageSettings and parse package
17923        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17924                | PackageParser.PARSE_ENFORCE_CODE
17925                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17926                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17927                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17928                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17929        PackageParser pp = new PackageParser();
17930        pp.setSeparateProcesses(mSeparateProcesses);
17931        pp.setDisplayMetrics(mMetrics);
17932        pp.setCallback(mPackageParserCallback);
17933
17934        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17935        final PackageParser.Package pkg;
17936        try {
17937            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17938        } catch (PackageParserException e) {
17939            res.setError("Failed parse during installPackageLI", e);
17940            return;
17941        } finally {
17942            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17943        }
17944
17945        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17946        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17947            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17948            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17949                    "Instant app package must target O");
17950            return;
17951        }
17952        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17953            Slog.w(TAG, "Instant app package " + pkg.packageName
17954                    + " does not target targetSandboxVersion 2");
17955            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17956                    "Instant app package must use targetSanboxVersion 2");
17957            return;
17958        }
17959
17960        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17961            // Static shared libraries have synthetic package names
17962            renameStaticSharedLibraryPackage(pkg);
17963
17964            // No static shared libs on external storage
17965            if (onExternal) {
17966                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17967                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17968                        "Packages declaring static-shared libs cannot be updated");
17969                return;
17970            }
17971        }
17972
17973        // If we are installing a clustered package add results for the children
17974        if (pkg.childPackages != null) {
17975            synchronized (mPackages) {
17976                final int childCount = pkg.childPackages.size();
17977                for (int i = 0; i < childCount; i++) {
17978                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17979                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17980                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17981                    childRes.pkg = childPkg;
17982                    childRes.name = childPkg.packageName;
17983                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17984                    if (childPs != null) {
17985                        childRes.origUsers = childPs.queryInstalledUsers(
17986                                sUserManager.getUserIds(), true);
17987                    }
17988                    if ((mPackages.containsKey(childPkg.packageName))) {
17989                        childRes.removedInfo = new PackageRemovedInfo(this);
17990                        childRes.removedInfo.removedPackage = childPkg.packageName;
17991                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17992                    }
17993                    if (res.addedChildPackages == null) {
17994                        res.addedChildPackages = new ArrayMap<>();
17995                    }
17996                    res.addedChildPackages.put(childPkg.packageName, childRes);
17997                }
17998            }
17999        }
18000
18001        // If package doesn't declare API override, mark that we have an install
18002        // time CPU ABI override.
18003        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18004            pkg.cpuAbiOverride = args.abiOverride;
18005        }
18006
18007        String pkgName = res.name = pkg.packageName;
18008        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18009            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18010                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18011                return;
18012            }
18013        }
18014
18015        try {
18016            // either use what we've been given or parse directly from the APK
18017            if (args.certificates != null) {
18018                try {
18019                    PackageParser.populateCertificates(pkg, args.certificates);
18020                } catch (PackageParserException e) {
18021                    // there was something wrong with the certificates we were given;
18022                    // try to pull them from the APK
18023                    PackageParser.collectCertificates(pkg, parseFlags);
18024                }
18025            } else {
18026                PackageParser.collectCertificates(pkg, parseFlags);
18027            }
18028        } catch (PackageParserException e) {
18029            res.setError("Failed collect during installPackageLI", e);
18030            return;
18031        }
18032
18033        // Get rid of all references to package scan path via parser.
18034        pp = null;
18035        String oldCodePath = null;
18036        boolean systemApp = false;
18037        synchronized (mPackages) {
18038            // Check if installing already existing package
18039            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18040                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18041                if (pkg.mOriginalPackages != null
18042                        && pkg.mOriginalPackages.contains(oldName)
18043                        && mPackages.containsKey(oldName)) {
18044                    // This package is derived from an original package,
18045                    // and this device has been updating from that original
18046                    // name.  We must continue using the original name, so
18047                    // rename the new package here.
18048                    pkg.setPackageName(oldName);
18049                    pkgName = pkg.packageName;
18050                    replace = true;
18051                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18052                            + oldName + " pkgName=" + pkgName);
18053                } else if (mPackages.containsKey(pkgName)) {
18054                    // This package, under its official name, already exists
18055                    // on the device; we should replace it.
18056                    replace = true;
18057                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18058                }
18059
18060                // Child packages are installed through the parent package
18061                if (pkg.parentPackage != null) {
18062                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18063                            "Package " + pkg.packageName + " is child of package "
18064                                    + pkg.parentPackage.parentPackage + ". Child packages "
18065                                    + "can be updated only through the parent package.");
18066                    return;
18067                }
18068
18069                if (replace) {
18070                    // Prevent apps opting out from runtime permissions
18071                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18072                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18073                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18074                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18075                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18076                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18077                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18078                                        + " doesn't support runtime permissions but the old"
18079                                        + " target SDK " + oldTargetSdk + " does.");
18080                        return;
18081                    }
18082                    // Prevent apps from downgrading their targetSandbox.
18083                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18084                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18085                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18086                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18087                                "Package " + pkg.packageName + " new target sandbox "
18088                                + newTargetSandbox + " is incompatible with the previous value of"
18089                                + oldTargetSandbox + ".");
18090                        return;
18091                    }
18092
18093                    // Prevent installing of child packages
18094                    if (oldPackage.parentPackage != null) {
18095                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18096                                "Package " + pkg.packageName + " is child of package "
18097                                        + oldPackage.parentPackage + ". Child packages "
18098                                        + "can be updated only through the parent package.");
18099                        return;
18100                    }
18101                }
18102            }
18103
18104            PackageSetting ps = mSettings.mPackages.get(pkgName);
18105            if (ps != null) {
18106                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18107
18108                // Static shared libs have same package with different versions where
18109                // we internally use a synthetic package name to allow multiple versions
18110                // of the same package, therefore we need to compare signatures against
18111                // the package setting for the latest library version.
18112                PackageSetting signatureCheckPs = ps;
18113                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18114                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18115                    if (libraryEntry != null) {
18116                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18117                    }
18118                }
18119
18120                // Quick sanity check that we're signed correctly if updating;
18121                // we'll check this again later when scanning, but we want to
18122                // bail early here before tripping over redefined permissions.
18123                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18124                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18125                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18126                                + pkg.packageName + " upgrade keys do not match the "
18127                                + "previously installed version");
18128                        return;
18129                    }
18130                } else {
18131                    try {
18132                        verifySignaturesLP(signatureCheckPs, pkg);
18133                    } catch (PackageManagerException e) {
18134                        res.setError(e.error, e.getMessage());
18135                        return;
18136                    }
18137                }
18138
18139                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18140                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18141                    systemApp = (ps.pkg.applicationInfo.flags &
18142                            ApplicationInfo.FLAG_SYSTEM) != 0;
18143                }
18144                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18145            }
18146
18147            int N = pkg.permissions.size();
18148            for (int i = N-1; i >= 0; i--) {
18149                PackageParser.Permission perm = pkg.permissions.get(i);
18150                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18151
18152                // Don't allow anyone but the system to define ephemeral permissions.
18153                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18154                        && !systemApp) {
18155                    Slog.w(TAG, "Non-System package " + pkg.packageName
18156                            + " attempting to delcare ephemeral permission "
18157                            + perm.info.name + "; Removing ephemeral.");
18158                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18159                }
18160                // Check whether the newly-scanned package wants to define an already-defined perm
18161                if (bp != null) {
18162                    // If the defining package is signed with our cert, it's okay.  This
18163                    // also includes the "updating the same package" case, of course.
18164                    // "updating same package" could also involve key-rotation.
18165                    final boolean sigsOk;
18166                    if (bp.sourcePackage.equals(pkg.packageName)
18167                            && (bp.packageSetting instanceof PackageSetting)
18168                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18169                                    scanFlags))) {
18170                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18171                    } else {
18172                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18173                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18174                    }
18175                    if (!sigsOk) {
18176                        // If the owning package is the system itself, we log but allow
18177                        // install to proceed; we fail the install on all other permission
18178                        // redefinitions.
18179                        if (!bp.sourcePackage.equals("android")) {
18180                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18181                                    + pkg.packageName + " attempting to redeclare permission "
18182                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18183                            res.origPermission = perm.info.name;
18184                            res.origPackage = bp.sourcePackage;
18185                            return;
18186                        } else {
18187                            Slog.w(TAG, "Package " + pkg.packageName
18188                                    + " attempting to redeclare system permission "
18189                                    + perm.info.name + "; ignoring new declaration");
18190                            pkg.permissions.remove(i);
18191                        }
18192                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18193                        // Prevent apps to change protection level to dangerous from any other
18194                        // type as this would allow a privilege escalation where an app adds a
18195                        // normal/signature permission in other app's group and later redefines
18196                        // it as dangerous leading to the group auto-grant.
18197                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18198                                == PermissionInfo.PROTECTION_DANGEROUS) {
18199                            if (bp != null && !bp.isRuntime()) {
18200                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18201                                        + "non-runtime permission " + perm.info.name
18202                                        + " to runtime; keeping old protection level");
18203                                perm.info.protectionLevel = bp.protectionLevel;
18204                            }
18205                        }
18206                    }
18207                }
18208            }
18209        }
18210
18211        if (systemApp) {
18212            if (onExternal) {
18213                // Abort update; system app can't be replaced with app on sdcard
18214                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18215                        "Cannot install updates to system apps on sdcard");
18216                return;
18217            } else if (instantApp) {
18218                // Abort update; system app can't be replaced with an instant app
18219                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18220                        "Cannot update a system app with an instant app");
18221                return;
18222            }
18223        }
18224
18225        if (args.move != null) {
18226            // We did an in-place move, so dex is ready to roll
18227            scanFlags |= SCAN_NO_DEX;
18228            scanFlags |= SCAN_MOVE;
18229
18230            synchronized (mPackages) {
18231                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18232                if (ps == null) {
18233                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18234                            "Missing settings for moved package " + pkgName);
18235                }
18236
18237                // We moved the entire application as-is, so bring over the
18238                // previously derived ABI information.
18239                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18240                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18241            }
18242
18243        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18244            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18245            scanFlags |= SCAN_NO_DEX;
18246
18247            try {
18248                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18249                    args.abiOverride : pkg.cpuAbiOverride);
18250                final boolean extractNativeLibs = !pkg.isLibrary();
18251                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18252                        extractNativeLibs, mAppLib32InstallDir);
18253            } catch (PackageManagerException pme) {
18254                Slog.e(TAG, "Error deriving application ABI", pme);
18255                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18256                return;
18257            }
18258
18259            // Shared libraries for the package need to be updated.
18260            synchronized (mPackages) {
18261                try {
18262                    updateSharedLibrariesLPr(pkg, null);
18263                } catch (PackageManagerException e) {
18264                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18265                }
18266            }
18267        }
18268
18269        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18270            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18271            return;
18272        }
18273
18274        // Verify if we need to dexopt the app.
18275        //
18276        // NOTE: it is *important* to call dexopt after doRename which will sync the
18277        // package data from PackageParser.Package and its corresponding ApplicationInfo.
18278        //
18279        // We only need to dexopt if the package meets ALL of the following conditions:
18280        //   1) it is not forward locked.
18281        //   2) it is not on on an external ASEC container.
18282        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18283        //
18284        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18285        // complete, so we skip this step during installation. Instead, we'll take extra time
18286        // the first time the instant app starts. It's preferred to do it this way to provide
18287        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18288        // middle of running an instant app. The default behaviour can be overridden
18289        // via gservices.
18290        final boolean performDexopt = !forwardLocked
18291            && !pkg.applicationInfo.isExternalAsec()
18292            && (!instantApp || Global.getInt(mContext.getContentResolver(),
18293                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18294
18295        if (performDexopt) {
18296            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18297            // Do not run PackageDexOptimizer through the local performDexOpt
18298            // method because `pkg` may not be in `mPackages` yet.
18299            //
18300            // Also, don't fail application installs if the dexopt step fails.
18301            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18302                REASON_INSTALL,
18303                DexoptOptions.DEXOPT_BOOT_COMPLETE);
18304            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18305                null /* instructionSets */,
18306                getOrCreateCompilerPackageStats(pkg),
18307                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18308                dexoptOptions);
18309            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18310        }
18311
18312        // Notify BackgroundDexOptService that the package has been changed.
18313        // If this is an update of a package which used to fail to compile,
18314        // BackgroundDexOptService will remove it from its blacklist.
18315        // TODO: Layering violation
18316        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18317
18318        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18319
18320        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18321                "installPackageLI")) {
18322            if (replace) {
18323                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18324                    // Static libs have a synthetic package name containing the version
18325                    // and cannot be updated as an update would get a new package name,
18326                    // unless this is the exact same version code which is useful for
18327                    // development.
18328                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18329                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18330                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18331                                + "static-shared libs cannot be updated");
18332                        return;
18333                    }
18334                }
18335                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18336                        installerPackageName, res, args.installReason);
18337            } else {
18338                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18339                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18340            }
18341        }
18342
18343        synchronized (mPackages) {
18344            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18345            if (ps != null) {
18346                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18347                ps.setUpdateAvailable(false /*updateAvailable*/);
18348            }
18349
18350            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18351            for (int i = 0; i < childCount; i++) {
18352                PackageParser.Package childPkg = pkg.childPackages.get(i);
18353                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18354                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18355                if (childPs != null) {
18356                    childRes.newUsers = childPs.queryInstalledUsers(
18357                            sUserManager.getUserIds(), true);
18358                }
18359            }
18360
18361            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18362                updateSequenceNumberLP(ps, res.newUsers);
18363                updateInstantAppInstallerLocked(pkgName);
18364            }
18365        }
18366    }
18367
18368    private void startIntentFilterVerifications(int userId, boolean replacing,
18369            PackageParser.Package pkg) {
18370        if (mIntentFilterVerifierComponent == null) {
18371            Slog.w(TAG, "No IntentFilter verification will not be done as "
18372                    + "there is no IntentFilterVerifier available!");
18373            return;
18374        }
18375
18376        final int verifierUid = getPackageUid(
18377                mIntentFilterVerifierComponent.getPackageName(),
18378                MATCH_DEBUG_TRIAGED_MISSING,
18379                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18380
18381        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18382        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18383        mHandler.sendMessage(msg);
18384
18385        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18386        for (int i = 0; i < childCount; i++) {
18387            PackageParser.Package childPkg = pkg.childPackages.get(i);
18388            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18389            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18390            mHandler.sendMessage(msg);
18391        }
18392    }
18393
18394    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18395            PackageParser.Package pkg) {
18396        int size = pkg.activities.size();
18397        if (size == 0) {
18398            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18399                    "No activity, so no need to verify any IntentFilter!");
18400            return;
18401        }
18402
18403        final boolean hasDomainURLs = hasDomainURLs(pkg);
18404        if (!hasDomainURLs) {
18405            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18406                    "No domain URLs, so no need to verify any IntentFilter!");
18407            return;
18408        }
18409
18410        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18411                + " if any IntentFilter from the " + size
18412                + " Activities needs verification ...");
18413
18414        int count = 0;
18415        final String packageName = pkg.packageName;
18416
18417        synchronized (mPackages) {
18418            // If this is a new install and we see that we've already run verification for this
18419            // package, we have nothing to do: it means the state was restored from backup.
18420            if (!replacing) {
18421                IntentFilterVerificationInfo ivi =
18422                        mSettings.getIntentFilterVerificationLPr(packageName);
18423                if (ivi != null) {
18424                    if (DEBUG_DOMAIN_VERIFICATION) {
18425                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18426                                + ivi.getStatusString());
18427                    }
18428                    return;
18429                }
18430            }
18431
18432            // If any filters need to be verified, then all need to be.
18433            boolean needToVerify = false;
18434            for (PackageParser.Activity a : pkg.activities) {
18435                for (ActivityIntentInfo filter : a.intents) {
18436                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18437                        if (DEBUG_DOMAIN_VERIFICATION) {
18438                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18439                        }
18440                        needToVerify = true;
18441                        break;
18442                    }
18443                }
18444            }
18445
18446            if (needToVerify) {
18447                final int verificationId = mIntentFilterVerificationToken++;
18448                for (PackageParser.Activity a : pkg.activities) {
18449                    for (ActivityIntentInfo filter : a.intents) {
18450                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18451                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18452                                    "Verification needed for IntentFilter:" + filter.toString());
18453                            mIntentFilterVerifier.addOneIntentFilterVerification(
18454                                    verifierUid, userId, verificationId, filter, packageName);
18455                            count++;
18456                        }
18457                    }
18458                }
18459            }
18460        }
18461
18462        if (count > 0) {
18463            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18464                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18465                    +  " for userId:" + userId);
18466            mIntentFilterVerifier.startVerifications(userId);
18467        } else {
18468            if (DEBUG_DOMAIN_VERIFICATION) {
18469                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18470            }
18471        }
18472    }
18473
18474    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18475        final ComponentName cn  = filter.activity.getComponentName();
18476        final String packageName = cn.getPackageName();
18477
18478        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18479                packageName);
18480        if (ivi == null) {
18481            return true;
18482        }
18483        int status = ivi.getStatus();
18484        switch (status) {
18485            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18486            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18487                return true;
18488
18489            default:
18490                // Nothing to do
18491                return false;
18492        }
18493    }
18494
18495    private static boolean isMultiArch(ApplicationInfo info) {
18496        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18497    }
18498
18499    private static boolean isExternal(PackageParser.Package pkg) {
18500        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18501    }
18502
18503    private static boolean isExternal(PackageSetting ps) {
18504        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18505    }
18506
18507    private static boolean isSystemApp(PackageParser.Package pkg) {
18508        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18509    }
18510
18511    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18512        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18513    }
18514
18515    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18516        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18517    }
18518
18519    private static boolean isSystemApp(PackageSetting ps) {
18520        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18521    }
18522
18523    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18524        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18525    }
18526
18527    private int packageFlagsToInstallFlags(PackageSetting ps) {
18528        int installFlags = 0;
18529        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18530            // This existing package was an external ASEC install when we have
18531            // the external flag without a UUID
18532            installFlags |= PackageManager.INSTALL_EXTERNAL;
18533        }
18534        if (ps.isForwardLocked()) {
18535            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18536        }
18537        return installFlags;
18538    }
18539
18540    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18541        if (isExternal(pkg)) {
18542            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18543                return StorageManager.UUID_PRIMARY_PHYSICAL;
18544            } else {
18545                return pkg.volumeUuid;
18546            }
18547        } else {
18548            return StorageManager.UUID_PRIVATE_INTERNAL;
18549        }
18550    }
18551
18552    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18553        if (isExternal(pkg)) {
18554            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18555                return mSettings.getExternalVersion();
18556            } else {
18557                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18558            }
18559        } else {
18560            return mSettings.getInternalVersion();
18561        }
18562    }
18563
18564    private void deleteTempPackageFiles() {
18565        final FilenameFilter filter = new FilenameFilter() {
18566            public boolean accept(File dir, String name) {
18567                return name.startsWith("vmdl") && name.endsWith(".tmp");
18568            }
18569        };
18570        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18571            file.delete();
18572        }
18573    }
18574
18575    @Override
18576    public void deletePackageAsUser(String packageName, int versionCode,
18577            IPackageDeleteObserver observer, int userId, int flags) {
18578        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18579                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18580    }
18581
18582    @Override
18583    public void deletePackageVersioned(VersionedPackage versionedPackage,
18584            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18585        final int callingUid = Binder.getCallingUid();
18586        mContext.enforceCallingOrSelfPermission(
18587                android.Manifest.permission.DELETE_PACKAGES, null);
18588        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18589        Preconditions.checkNotNull(versionedPackage);
18590        Preconditions.checkNotNull(observer);
18591        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18592                PackageManager.VERSION_CODE_HIGHEST,
18593                Integer.MAX_VALUE, "versionCode must be >= -1");
18594
18595        final String packageName = versionedPackage.getPackageName();
18596        final int versionCode = versionedPackage.getVersionCode();
18597        final String internalPackageName;
18598        synchronized (mPackages) {
18599            // Normalize package name to handle renamed packages and static libs
18600            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18601                    versionedPackage.getVersionCode());
18602        }
18603
18604        final int uid = Binder.getCallingUid();
18605        if (!isOrphaned(internalPackageName)
18606                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18607            try {
18608                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18609                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18610                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18611                observer.onUserActionRequired(intent);
18612            } catch (RemoteException re) {
18613            }
18614            return;
18615        }
18616        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18617        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18618        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18619            mContext.enforceCallingOrSelfPermission(
18620                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18621                    "deletePackage for user " + userId);
18622        }
18623
18624        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18625            try {
18626                observer.onPackageDeleted(packageName,
18627                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18628            } catch (RemoteException re) {
18629            }
18630            return;
18631        }
18632
18633        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18634            try {
18635                observer.onPackageDeleted(packageName,
18636                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18637            } catch (RemoteException re) {
18638            }
18639            return;
18640        }
18641
18642        if (DEBUG_REMOVE) {
18643            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18644                    + " deleteAllUsers: " + deleteAllUsers + " version="
18645                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18646                    ? "VERSION_CODE_HIGHEST" : versionCode));
18647        }
18648        // Queue up an async operation since the package deletion may take a little while.
18649        mHandler.post(new Runnable() {
18650            public void run() {
18651                mHandler.removeCallbacks(this);
18652                int returnCode;
18653                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18654                boolean doDeletePackage = true;
18655                if (ps != null) {
18656                    final boolean targetIsInstantApp =
18657                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18658                    doDeletePackage = !targetIsInstantApp
18659                            || canViewInstantApps;
18660                }
18661                if (doDeletePackage) {
18662                    if (!deleteAllUsers) {
18663                        returnCode = deletePackageX(internalPackageName, versionCode,
18664                                userId, deleteFlags);
18665                    } else {
18666                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18667                                internalPackageName, users);
18668                        // If nobody is blocking uninstall, proceed with delete for all users
18669                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18670                            returnCode = deletePackageX(internalPackageName, versionCode,
18671                                    userId, deleteFlags);
18672                        } else {
18673                            // Otherwise uninstall individually for users with blockUninstalls=false
18674                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18675                            for (int userId : users) {
18676                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18677                                    returnCode = deletePackageX(internalPackageName, versionCode,
18678                                            userId, userFlags);
18679                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18680                                        Slog.w(TAG, "Package delete failed for user " + userId
18681                                                + ", returnCode " + returnCode);
18682                                    }
18683                                }
18684                            }
18685                            // The app has only been marked uninstalled for certain users.
18686                            // We still need to report that delete was blocked
18687                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18688                        }
18689                    }
18690                } else {
18691                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18692                }
18693                try {
18694                    observer.onPackageDeleted(packageName, returnCode, null);
18695                } catch (RemoteException e) {
18696                    Log.i(TAG, "Observer no longer exists.");
18697                } //end catch
18698            } //end run
18699        });
18700    }
18701
18702    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18703        if (pkg.staticSharedLibName != null) {
18704            return pkg.manifestPackageName;
18705        }
18706        return pkg.packageName;
18707    }
18708
18709    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18710        // Handle renamed packages
18711        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18712        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18713
18714        // Is this a static library?
18715        SparseArray<SharedLibraryEntry> versionedLib =
18716                mStaticLibsByDeclaringPackage.get(packageName);
18717        if (versionedLib == null || versionedLib.size() <= 0) {
18718            return packageName;
18719        }
18720
18721        // Figure out which lib versions the caller can see
18722        SparseIntArray versionsCallerCanSee = null;
18723        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18724        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18725                && callingAppId != Process.ROOT_UID) {
18726            versionsCallerCanSee = new SparseIntArray();
18727            String libName = versionedLib.valueAt(0).info.getName();
18728            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18729            if (uidPackages != null) {
18730                for (String uidPackage : uidPackages) {
18731                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18732                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18733                    if (libIdx >= 0) {
18734                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18735                        versionsCallerCanSee.append(libVersion, libVersion);
18736                    }
18737                }
18738            }
18739        }
18740
18741        // Caller can see nothing - done
18742        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18743            return packageName;
18744        }
18745
18746        // Find the version the caller can see and the app version code
18747        SharedLibraryEntry highestVersion = null;
18748        final int versionCount = versionedLib.size();
18749        for (int i = 0; i < versionCount; i++) {
18750            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18751            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18752                    libEntry.info.getVersion()) < 0) {
18753                continue;
18754            }
18755            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18756            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18757                if (libVersionCode == versionCode) {
18758                    return libEntry.apk;
18759                }
18760            } else if (highestVersion == null) {
18761                highestVersion = libEntry;
18762            } else if (libVersionCode  > highestVersion.info
18763                    .getDeclaringPackage().getVersionCode()) {
18764                highestVersion = libEntry;
18765            }
18766        }
18767
18768        if (highestVersion != null) {
18769            return highestVersion.apk;
18770        }
18771
18772        return packageName;
18773    }
18774
18775    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18776        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18777              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18778            return true;
18779        }
18780        final int callingUserId = UserHandle.getUserId(callingUid);
18781        // If the caller installed the pkgName, then allow it to silently uninstall.
18782        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18783            return true;
18784        }
18785
18786        // Allow package verifier to silently uninstall.
18787        if (mRequiredVerifierPackage != null &&
18788                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18789            return true;
18790        }
18791
18792        // Allow package uninstaller to silently uninstall.
18793        if (mRequiredUninstallerPackage != null &&
18794                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18795            return true;
18796        }
18797
18798        // Allow storage manager to silently uninstall.
18799        if (mStorageManagerPackage != null &&
18800                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18801            return true;
18802        }
18803
18804        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18805        // uninstall for device owner provisioning.
18806        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18807                == PERMISSION_GRANTED) {
18808            return true;
18809        }
18810
18811        return false;
18812    }
18813
18814    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18815        int[] result = EMPTY_INT_ARRAY;
18816        for (int userId : userIds) {
18817            if (getBlockUninstallForUser(packageName, userId)) {
18818                result = ArrayUtils.appendInt(result, userId);
18819            }
18820        }
18821        return result;
18822    }
18823
18824    @Override
18825    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18826        final int callingUid = Binder.getCallingUid();
18827        if (getInstantAppPackageName(callingUid) != null
18828                && !isCallerSameApp(packageName, callingUid)) {
18829            return false;
18830        }
18831        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18832    }
18833
18834    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18835        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18836                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18837        try {
18838            if (dpm != null) {
18839                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18840                        /* callingUserOnly =*/ false);
18841                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18842                        : deviceOwnerComponentName.getPackageName();
18843                // Does the package contains the device owner?
18844                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18845                // this check is probably not needed, since DO should be registered as a device
18846                // admin on some user too. (Original bug for this: b/17657954)
18847                if (packageName.equals(deviceOwnerPackageName)) {
18848                    return true;
18849                }
18850                // Does it contain a device admin for any user?
18851                int[] users;
18852                if (userId == UserHandle.USER_ALL) {
18853                    users = sUserManager.getUserIds();
18854                } else {
18855                    users = new int[]{userId};
18856                }
18857                for (int i = 0; i < users.length; ++i) {
18858                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18859                        return true;
18860                    }
18861                }
18862            }
18863        } catch (RemoteException e) {
18864        }
18865        return false;
18866    }
18867
18868    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18869        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18870    }
18871
18872    /**
18873     *  This method is an internal method that could be get invoked either
18874     *  to delete an installed package or to clean up a failed installation.
18875     *  After deleting an installed package, a broadcast is sent to notify any
18876     *  listeners that the package has been removed. For cleaning up a failed
18877     *  installation, the broadcast is not necessary since the package's
18878     *  installation wouldn't have sent the initial broadcast either
18879     *  The key steps in deleting a package are
18880     *  deleting the package information in internal structures like mPackages,
18881     *  deleting the packages base directories through installd
18882     *  updating mSettings to reflect current status
18883     *  persisting settings for later use
18884     *  sending a broadcast if necessary
18885     */
18886    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18887        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18888        final boolean res;
18889
18890        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18891                ? UserHandle.USER_ALL : userId;
18892
18893        if (isPackageDeviceAdmin(packageName, removeUser)) {
18894            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18895            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18896        }
18897
18898        PackageSetting uninstalledPs = null;
18899        PackageParser.Package pkg = null;
18900
18901        // for the uninstall-updates case and restricted profiles, remember the per-
18902        // user handle installed state
18903        int[] allUsers;
18904        synchronized (mPackages) {
18905            uninstalledPs = mSettings.mPackages.get(packageName);
18906            if (uninstalledPs == null) {
18907                Slog.w(TAG, "Not removing non-existent package " + packageName);
18908                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18909            }
18910
18911            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18912                    && uninstalledPs.versionCode != versionCode) {
18913                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18914                        + uninstalledPs.versionCode + " != " + versionCode);
18915                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18916            }
18917
18918            // Static shared libs can be declared by any package, so let us not
18919            // allow removing a package if it provides a lib others depend on.
18920            pkg = mPackages.get(packageName);
18921
18922            allUsers = sUserManager.getUserIds();
18923
18924            if (pkg != null && pkg.staticSharedLibName != null) {
18925                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18926                        pkg.staticSharedLibVersion);
18927                if (libEntry != null) {
18928                    for (int currUserId : allUsers) {
18929                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18930                            continue;
18931                        }
18932                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18933                                libEntry.info, 0, currUserId);
18934                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18935                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18936                                    + " hosting lib " + libEntry.info.getName() + " version "
18937                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18938                                    + " for user " + currUserId);
18939                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18940                        }
18941                    }
18942                }
18943            }
18944
18945            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18946        }
18947
18948        final int freezeUser;
18949        if (isUpdatedSystemApp(uninstalledPs)
18950                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18951            // We're downgrading a system app, which will apply to all users, so
18952            // freeze them all during the downgrade
18953            freezeUser = UserHandle.USER_ALL;
18954        } else {
18955            freezeUser = removeUser;
18956        }
18957
18958        synchronized (mInstallLock) {
18959            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18960            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18961                    deleteFlags, "deletePackageX")) {
18962                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18963                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18964            }
18965            synchronized (mPackages) {
18966                if (res) {
18967                    if (pkg != null) {
18968                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18969                    }
18970                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18971                    updateInstantAppInstallerLocked(packageName);
18972                }
18973            }
18974        }
18975
18976        if (res) {
18977            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18978            info.sendPackageRemovedBroadcasts(killApp);
18979            info.sendSystemPackageUpdatedBroadcasts();
18980            info.sendSystemPackageAppearedBroadcasts();
18981        }
18982        // Force a gc here.
18983        Runtime.getRuntime().gc();
18984        // Delete the resources here after sending the broadcast to let
18985        // other processes clean up before deleting resources.
18986        if (info.args != null) {
18987            synchronized (mInstallLock) {
18988                info.args.doPostDeleteLI(true);
18989            }
18990        }
18991
18992        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18993    }
18994
18995    static class PackageRemovedInfo {
18996        final PackageSender packageSender;
18997        String removedPackage;
18998        String installerPackageName;
18999        int uid = -1;
19000        int removedAppId = -1;
19001        int[] origUsers;
19002        int[] removedUsers = null;
19003        int[] broadcastUsers = null;
19004        SparseArray<Integer> installReasons;
19005        boolean isRemovedPackageSystemUpdate = false;
19006        boolean isUpdate;
19007        boolean dataRemoved;
19008        boolean removedForAllUsers;
19009        boolean isStaticSharedLib;
19010        // Clean up resources deleted packages.
19011        InstallArgs args = null;
19012        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19013        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19014
19015        PackageRemovedInfo(PackageSender packageSender) {
19016            this.packageSender = packageSender;
19017        }
19018
19019        void sendPackageRemovedBroadcasts(boolean killApp) {
19020            sendPackageRemovedBroadcastInternal(killApp);
19021            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19022            for (int i = 0; i < childCount; i++) {
19023                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19024                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19025            }
19026        }
19027
19028        void sendSystemPackageUpdatedBroadcasts() {
19029            if (isRemovedPackageSystemUpdate) {
19030                sendSystemPackageUpdatedBroadcastsInternal();
19031                final int childCount = (removedChildPackages != null)
19032                        ? removedChildPackages.size() : 0;
19033                for (int i = 0; i < childCount; i++) {
19034                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19035                    if (childInfo.isRemovedPackageSystemUpdate) {
19036                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19037                    }
19038                }
19039            }
19040        }
19041
19042        void sendSystemPackageAppearedBroadcasts() {
19043            final int packageCount = (appearedChildPackages != null)
19044                    ? appearedChildPackages.size() : 0;
19045            for (int i = 0; i < packageCount; i++) {
19046                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19047                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19048                    true, UserHandle.getAppId(installedInfo.uid),
19049                    installedInfo.newUsers);
19050            }
19051        }
19052
19053        private void sendSystemPackageUpdatedBroadcastsInternal() {
19054            Bundle extras = new Bundle(2);
19055            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19056            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19057            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19058                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19059            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19060                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19061            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19062                null, null, 0, removedPackage, null, null);
19063            if (installerPackageName != null) {
19064                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19065                        removedPackage, extras, 0 /*flags*/,
19066                        installerPackageName, null, null);
19067                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19068                        removedPackage, extras, 0 /*flags*/,
19069                        installerPackageName, null, null);
19070            }
19071        }
19072
19073        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19074            // Don't send static shared library removal broadcasts as these
19075            // libs are visible only the the apps that depend on them an one
19076            // cannot remove the library if it has a dependency.
19077            if (isStaticSharedLib) {
19078                return;
19079            }
19080            Bundle extras = new Bundle(2);
19081            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19082            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19083            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19084            if (isUpdate || isRemovedPackageSystemUpdate) {
19085                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19086            }
19087            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19088            if (removedPackage != null) {
19089                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19090                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19091                if (installerPackageName != null) {
19092                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19093                            removedPackage, extras, 0 /*flags*/,
19094                            installerPackageName, null, broadcastUsers);
19095                }
19096                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19097                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19098                        removedPackage, extras,
19099                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19100                        null, null, broadcastUsers);
19101                }
19102            }
19103            if (removedAppId >= 0) {
19104                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19105                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19106                    null, null, broadcastUsers);
19107            }
19108        }
19109
19110        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19111            removedUsers = userIds;
19112            if (removedUsers == null) {
19113                broadcastUsers = null;
19114                return;
19115            }
19116
19117            broadcastUsers = EMPTY_INT_ARRAY;
19118            for (int i = userIds.length - 1; i >= 0; --i) {
19119                final int userId = userIds[i];
19120                if (deletedPackageSetting.getInstantApp(userId)) {
19121                    continue;
19122                }
19123                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19124            }
19125        }
19126    }
19127
19128    /*
19129     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19130     * flag is not set, the data directory is removed as well.
19131     * make sure this flag is set for partially installed apps. If not its meaningless to
19132     * delete a partially installed application.
19133     */
19134    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19135            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19136        String packageName = ps.name;
19137        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19138        // Retrieve object to delete permissions for shared user later on
19139        final PackageParser.Package deletedPkg;
19140        final PackageSetting deletedPs;
19141        // reader
19142        synchronized (mPackages) {
19143            deletedPkg = mPackages.get(packageName);
19144            deletedPs = mSettings.mPackages.get(packageName);
19145            if (outInfo != null) {
19146                outInfo.removedPackage = packageName;
19147                outInfo.installerPackageName = ps.installerPackageName;
19148                outInfo.isStaticSharedLib = deletedPkg != null
19149                        && deletedPkg.staticSharedLibName != null;
19150                outInfo.populateUsers(deletedPs == null ? null
19151                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19152            }
19153        }
19154
19155        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19156
19157        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19158            final PackageParser.Package resolvedPkg;
19159            if (deletedPkg != null) {
19160                resolvedPkg = deletedPkg;
19161            } else {
19162                // We don't have a parsed package when it lives on an ejected
19163                // adopted storage device, so fake something together
19164                resolvedPkg = new PackageParser.Package(ps.name);
19165                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19166            }
19167            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19168                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19169            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19170            if (outInfo != null) {
19171                outInfo.dataRemoved = true;
19172            }
19173            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19174        }
19175
19176        int removedAppId = -1;
19177
19178        // writer
19179        synchronized (mPackages) {
19180            boolean installedStateChanged = false;
19181            if (deletedPs != null) {
19182                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19183                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19184                    clearDefaultBrowserIfNeeded(packageName);
19185                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19186                    removedAppId = mSettings.removePackageLPw(packageName);
19187                    if (outInfo != null) {
19188                        outInfo.removedAppId = removedAppId;
19189                    }
19190                    updatePermissionsLPw(deletedPs.name, null, 0);
19191                    if (deletedPs.sharedUser != null) {
19192                        // Remove permissions associated with package. Since runtime
19193                        // permissions are per user we have to kill the removed package
19194                        // or packages running under the shared user of the removed
19195                        // package if revoking the permissions requested only by the removed
19196                        // package is successful and this causes a change in gids.
19197                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19198                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19199                                    userId);
19200                            if (userIdToKill == UserHandle.USER_ALL
19201                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19202                                // If gids changed for this user, kill all affected packages.
19203                                mHandler.post(new Runnable() {
19204                                    @Override
19205                                    public void run() {
19206                                        // This has to happen with no lock held.
19207                                        killApplication(deletedPs.name, deletedPs.appId,
19208                                                KILL_APP_REASON_GIDS_CHANGED);
19209                                    }
19210                                });
19211                                break;
19212                            }
19213                        }
19214                    }
19215                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19216                }
19217                // make sure to preserve per-user disabled state if this removal was just
19218                // a downgrade of a system app to the factory package
19219                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19220                    if (DEBUG_REMOVE) {
19221                        Slog.d(TAG, "Propagating install state across downgrade");
19222                    }
19223                    for (int userId : allUserHandles) {
19224                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19225                        if (DEBUG_REMOVE) {
19226                            Slog.d(TAG, "    user " + userId + " => " + installed);
19227                        }
19228                        if (installed != ps.getInstalled(userId)) {
19229                            installedStateChanged = true;
19230                        }
19231                        ps.setInstalled(installed, userId);
19232                    }
19233                }
19234            }
19235            // can downgrade to reader
19236            if (writeSettings) {
19237                // Save settings now
19238                mSettings.writeLPr();
19239            }
19240            if (installedStateChanged) {
19241                mSettings.writeKernelMappingLPr(ps);
19242            }
19243        }
19244        if (removedAppId != -1) {
19245            // A user ID was deleted here. Go through all users and remove it
19246            // from KeyStore.
19247            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19248        }
19249    }
19250
19251    static boolean locationIsPrivileged(File path) {
19252        try {
19253            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19254                    .getCanonicalPath();
19255            return path.getCanonicalPath().startsWith(privilegedAppDir);
19256        } catch (IOException e) {
19257            Slog.e(TAG, "Unable to access code path " + path);
19258        }
19259        return false;
19260    }
19261
19262    /*
19263     * Tries to delete system package.
19264     */
19265    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19266            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19267            boolean writeSettings) {
19268        if (deletedPs.parentPackageName != null) {
19269            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19270            return false;
19271        }
19272
19273        final boolean applyUserRestrictions
19274                = (allUserHandles != null) && (outInfo.origUsers != null);
19275        final PackageSetting disabledPs;
19276        // Confirm if the system package has been updated
19277        // An updated system app can be deleted. This will also have to restore
19278        // the system pkg from system partition
19279        // reader
19280        synchronized (mPackages) {
19281            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19282        }
19283
19284        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19285                + " disabledPs=" + disabledPs);
19286
19287        if (disabledPs == null) {
19288            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19289            return false;
19290        } else if (DEBUG_REMOVE) {
19291            Slog.d(TAG, "Deleting system pkg from data partition");
19292        }
19293
19294        if (DEBUG_REMOVE) {
19295            if (applyUserRestrictions) {
19296                Slog.d(TAG, "Remembering install states:");
19297                for (int userId : allUserHandles) {
19298                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19299                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19300                }
19301            }
19302        }
19303
19304        // Delete the updated package
19305        outInfo.isRemovedPackageSystemUpdate = true;
19306        if (outInfo.removedChildPackages != null) {
19307            final int childCount = (deletedPs.childPackageNames != null)
19308                    ? deletedPs.childPackageNames.size() : 0;
19309            for (int i = 0; i < childCount; i++) {
19310                String childPackageName = deletedPs.childPackageNames.get(i);
19311                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19312                        .contains(childPackageName)) {
19313                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19314                            childPackageName);
19315                    if (childInfo != null) {
19316                        childInfo.isRemovedPackageSystemUpdate = true;
19317                    }
19318                }
19319            }
19320        }
19321
19322        if (disabledPs.versionCode < deletedPs.versionCode) {
19323            // Delete data for downgrades
19324            flags &= ~PackageManager.DELETE_KEEP_DATA;
19325        } else {
19326            // Preserve data by setting flag
19327            flags |= PackageManager.DELETE_KEEP_DATA;
19328        }
19329
19330        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19331                outInfo, writeSettings, disabledPs.pkg);
19332        if (!ret) {
19333            return false;
19334        }
19335
19336        // writer
19337        synchronized (mPackages) {
19338            // Reinstate the old system package
19339            enableSystemPackageLPw(disabledPs.pkg);
19340            // Remove any native libraries from the upgraded package.
19341            removeNativeBinariesLI(deletedPs);
19342        }
19343
19344        // Install the system package
19345        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19346        int parseFlags = mDefParseFlags
19347                | PackageParser.PARSE_MUST_BE_APK
19348                | PackageParser.PARSE_IS_SYSTEM
19349                | PackageParser.PARSE_IS_SYSTEM_DIR;
19350        if (locationIsPrivileged(disabledPs.codePath)) {
19351            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19352        }
19353
19354        final PackageParser.Package newPkg;
19355        try {
19356            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19357                0 /* currentTime */, null);
19358        } catch (PackageManagerException e) {
19359            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19360                    + e.getMessage());
19361            return false;
19362        }
19363
19364        try {
19365            // update shared libraries for the newly re-installed system package
19366            updateSharedLibrariesLPr(newPkg, null);
19367        } catch (PackageManagerException e) {
19368            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19369        }
19370
19371        prepareAppDataAfterInstallLIF(newPkg);
19372
19373        // writer
19374        synchronized (mPackages) {
19375            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19376
19377            // Propagate the permissions state as we do not want to drop on the floor
19378            // runtime permissions. The update permissions method below will take
19379            // care of removing obsolete permissions and grant install permissions.
19380            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19381            updatePermissionsLPw(newPkg.packageName, newPkg,
19382                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19383
19384            if (applyUserRestrictions) {
19385                boolean installedStateChanged = false;
19386                if (DEBUG_REMOVE) {
19387                    Slog.d(TAG, "Propagating install state across reinstall");
19388                }
19389                for (int userId : allUserHandles) {
19390                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19391                    if (DEBUG_REMOVE) {
19392                        Slog.d(TAG, "    user " + userId + " => " + installed);
19393                    }
19394                    if (installed != ps.getInstalled(userId)) {
19395                        installedStateChanged = true;
19396                    }
19397                    ps.setInstalled(installed, userId);
19398
19399                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19400                }
19401                // Regardless of writeSettings we need to ensure that this restriction
19402                // state propagation is persisted
19403                mSettings.writeAllUsersPackageRestrictionsLPr();
19404                if (installedStateChanged) {
19405                    mSettings.writeKernelMappingLPr(ps);
19406                }
19407            }
19408            // can downgrade to reader here
19409            if (writeSettings) {
19410                mSettings.writeLPr();
19411            }
19412        }
19413        return true;
19414    }
19415
19416    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19417            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19418            PackageRemovedInfo outInfo, boolean writeSettings,
19419            PackageParser.Package replacingPackage) {
19420        synchronized (mPackages) {
19421            if (outInfo != null) {
19422                outInfo.uid = ps.appId;
19423            }
19424
19425            if (outInfo != null && outInfo.removedChildPackages != null) {
19426                final int childCount = (ps.childPackageNames != null)
19427                        ? ps.childPackageNames.size() : 0;
19428                for (int i = 0; i < childCount; i++) {
19429                    String childPackageName = ps.childPackageNames.get(i);
19430                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19431                    if (childPs == null) {
19432                        return false;
19433                    }
19434                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19435                            childPackageName);
19436                    if (childInfo != null) {
19437                        childInfo.uid = childPs.appId;
19438                    }
19439                }
19440            }
19441        }
19442
19443        // Delete package data from internal structures and also remove data if flag is set
19444        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19445
19446        // Delete the child packages data
19447        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19448        for (int i = 0; i < childCount; i++) {
19449            PackageSetting childPs;
19450            synchronized (mPackages) {
19451                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19452            }
19453            if (childPs != null) {
19454                PackageRemovedInfo childOutInfo = (outInfo != null
19455                        && outInfo.removedChildPackages != null)
19456                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19457                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19458                        && (replacingPackage != null
19459                        && !replacingPackage.hasChildPackage(childPs.name))
19460                        ? flags & ~DELETE_KEEP_DATA : flags;
19461                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19462                        deleteFlags, writeSettings);
19463            }
19464        }
19465
19466        // Delete application code and resources only for parent packages
19467        if (ps.parentPackageName == null) {
19468            if (deleteCodeAndResources && (outInfo != null)) {
19469                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19470                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19471                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19472            }
19473        }
19474
19475        return true;
19476    }
19477
19478    @Override
19479    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19480            int userId) {
19481        mContext.enforceCallingOrSelfPermission(
19482                android.Manifest.permission.DELETE_PACKAGES, null);
19483        synchronized (mPackages) {
19484            // Cannot block uninstall of static shared libs as they are
19485            // considered a part of the using app (emulating static linking).
19486            // Also static libs are installed always on internal storage.
19487            PackageParser.Package pkg = mPackages.get(packageName);
19488            if (pkg != null && pkg.staticSharedLibName != null) {
19489                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19490                        + " providing static shared library: " + pkg.staticSharedLibName);
19491                return false;
19492            }
19493            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19494            mSettings.writePackageRestrictionsLPr(userId);
19495        }
19496        return true;
19497    }
19498
19499    @Override
19500    public boolean getBlockUninstallForUser(String packageName, int userId) {
19501        synchronized (mPackages) {
19502            final PackageSetting ps = mSettings.mPackages.get(packageName);
19503            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19504                return false;
19505            }
19506            return mSettings.getBlockUninstallLPr(userId, packageName);
19507        }
19508    }
19509
19510    @Override
19511    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19512        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19513        synchronized (mPackages) {
19514            PackageSetting ps = mSettings.mPackages.get(packageName);
19515            if (ps == null) {
19516                Log.w(TAG, "Package doesn't exist: " + packageName);
19517                return false;
19518            }
19519            if (systemUserApp) {
19520                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19521            } else {
19522                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19523            }
19524            mSettings.writeLPr();
19525        }
19526        return true;
19527    }
19528
19529    /*
19530     * This method handles package deletion in general
19531     */
19532    private boolean deletePackageLIF(String packageName, UserHandle user,
19533            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19534            PackageRemovedInfo outInfo, boolean writeSettings,
19535            PackageParser.Package replacingPackage) {
19536        if (packageName == null) {
19537            Slog.w(TAG, "Attempt to delete null packageName.");
19538            return false;
19539        }
19540
19541        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19542
19543        PackageSetting ps;
19544        synchronized (mPackages) {
19545            ps = mSettings.mPackages.get(packageName);
19546            if (ps == null) {
19547                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19548                return false;
19549            }
19550
19551            if (ps.parentPackageName != null && (!isSystemApp(ps)
19552                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19553                if (DEBUG_REMOVE) {
19554                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19555                            + ((user == null) ? UserHandle.USER_ALL : user));
19556                }
19557                final int removedUserId = (user != null) ? user.getIdentifier()
19558                        : UserHandle.USER_ALL;
19559                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19560                    return false;
19561                }
19562                markPackageUninstalledForUserLPw(ps, user);
19563                scheduleWritePackageRestrictionsLocked(user);
19564                return true;
19565            }
19566        }
19567
19568        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19569                && user.getIdentifier() != UserHandle.USER_ALL)) {
19570            // The caller is asking that the package only be deleted for a single
19571            // user.  To do this, we just mark its uninstalled state and delete
19572            // its data. If this is a system app, we only allow this to happen if
19573            // they have set the special DELETE_SYSTEM_APP which requests different
19574            // semantics than normal for uninstalling system apps.
19575            markPackageUninstalledForUserLPw(ps, user);
19576
19577            if (!isSystemApp(ps)) {
19578                // Do not uninstall the APK if an app should be cached
19579                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19580                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19581                    // Other user still have this package installed, so all
19582                    // we need to do is clear this user's data and save that
19583                    // it is uninstalled.
19584                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19585                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19586                        return false;
19587                    }
19588                    scheduleWritePackageRestrictionsLocked(user);
19589                    return true;
19590                } else {
19591                    // We need to set it back to 'installed' so the uninstall
19592                    // broadcasts will be sent correctly.
19593                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19594                    ps.setInstalled(true, user.getIdentifier());
19595                    mSettings.writeKernelMappingLPr(ps);
19596                }
19597            } else {
19598                // This is a system app, so we assume that the
19599                // other users still have this package installed, so all
19600                // we need to do is clear this user's data and save that
19601                // it is uninstalled.
19602                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19603                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19604                    return false;
19605                }
19606                scheduleWritePackageRestrictionsLocked(user);
19607                return true;
19608            }
19609        }
19610
19611        // If we are deleting a composite package for all users, keep track
19612        // of result for each child.
19613        if (ps.childPackageNames != null && outInfo != null) {
19614            synchronized (mPackages) {
19615                final int childCount = ps.childPackageNames.size();
19616                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19617                for (int i = 0; i < childCount; i++) {
19618                    String childPackageName = ps.childPackageNames.get(i);
19619                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19620                    childInfo.removedPackage = childPackageName;
19621                    childInfo.installerPackageName = ps.installerPackageName;
19622                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19623                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19624                    if (childPs != null) {
19625                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19626                    }
19627                }
19628            }
19629        }
19630
19631        boolean ret = false;
19632        if (isSystemApp(ps)) {
19633            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19634            // When an updated system application is deleted we delete the existing resources
19635            // as well and fall back to existing code in system partition
19636            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19637        } else {
19638            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19639            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19640                    outInfo, writeSettings, replacingPackage);
19641        }
19642
19643        // Take a note whether we deleted the package for all users
19644        if (outInfo != null) {
19645            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19646            if (outInfo.removedChildPackages != null) {
19647                synchronized (mPackages) {
19648                    final int childCount = outInfo.removedChildPackages.size();
19649                    for (int i = 0; i < childCount; i++) {
19650                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19651                        if (childInfo != null) {
19652                            childInfo.removedForAllUsers = mPackages.get(
19653                                    childInfo.removedPackage) == null;
19654                        }
19655                    }
19656                }
19657            }
19658            // If we uninstalled an update to a system app there may be some
19659            // child packages that appeared as they are declared in the system
19660            // app but were not declared in the update.
19661            if (isSystemApp(ps)) {
19662                synchronized (mPackages) {
19663                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19664                    final int childCount = (updatedPs.childPackageNames != null)
19665                            ? updatedPs.childPackageNames.size() : 0;
19666                    for (int i = 0; i < childCount; i++) {
19667                        String childPackageName = updatedPs.childPackageNames.get(i);
19668                        if (outInfo.removedChildPackages == null
19669                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19670                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19671                            if (childPs == null) {
19672                                continue;
19673                            }
19674                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19675                            installRes.name = childPackageName;
19676                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19677                            installRes.pkg = mPackages.get(childPackageName);
19678                            installRes.uid = childPs.pkg.applicationInfo.uid;
19679                            if (outInfo.appearedChildPackages == null) {
19680                                outInfo.appearedChildPackages = new ArrayMap<>();
19681                            }
19682                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19683                        }
19684                    }
19685                }
19686            }
19687        }
19688
19689        return ret;
19690    }
19691
19692    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19693        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19694                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19695        for (int nextUserId : userIds) {
19696            if (DEBUG_REMOVE) {
19697                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19698            }
19699            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19700                    false /*installed*/,
19701                    true /*stopped*/,
19702                    true /*notLaunched*/,
19703                    false /*hidden*/,
19704                    false /*suspended*/,
19705                    false /*instantApp*/,
19706                    null /*lastDisableAppCaller*/,
19707                    null /*enabledComponents*/,
19708                    null /*disabledComponents*/,
19709                    ps.readUserState(nextUserId).domainVerificationStatus,
19710                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19711        }
19712        mSettings.writeKernelMappingLPr(ps);
19713    }
19714
19715    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19716            PackageRemovedInfo outInfo) {
19717        final PackageParser.Package pkg;
19718        synchronized (mPackages) {
19719            pkg = mPackages.get(ps.name);
19720        }
19721
19722        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19723                : new int[] {userId};
19724        for (int nextUserId : userIds) {
19725            if (DEBUG_REMOVE) {
19726                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19727                        + nextUserId);
19728            }
19729
19730            destroyAppDataLIF(pkg, userId,
19731                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19732            destroyAppProfilesLIF(pkg, userId);
19733            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19734            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19735            schedulePackageCleaning(ps.name, nextUserId, false);
19736            synchronized (mPackages) {
19737                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19738                    scheduleWritePackageRestrictionsLocked(nextUserId);
19739                }
19740                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19741            }
19742        }
19743
19744        if (outInfo != null) {
19745            outInfo.removedPackage = ps.name;
19746            outInfo.installerPackageName = ps.installerPackageName;
19747            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19748            outInfo.removedAppId = ps.appId;
19749            outInfo.removedUsers = userIds;
19750            outInfo.broadcastUsers = userIds;
19751        }
19752
19753        return true;
19754    }
19755
19756    private final class ClearStorageConnection implements ServiceConnection {
19757        IMediaContainerService mContainerService;
19758
19759        @Override
19760        public void onServiceConnected(ComponentName name, IBinder service) {
19761            synchronized (this) {
19762                mContainerService = IMediaContainerService.Stub
19763                        .asInterface(Binder.allowBlocking(service));
19764                notifyAll();
19765            }
19766        }
19767
19768        @Override
19769        public void onServiceDisconnected(ComponentName name) {
19770        }
19771    }
19772
19773    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19774        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19775
19776        final boolean mounted;
19777        if (Environment.isExternalStorageEmulated()) {
19778            mounted = true;
19779        } else {
19780            final String status = Environment.getExternalStorageState();
19781
19782            mounted = status.equals(Environment.MEDIA_MOUNTED)
19783                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19784        }
19785
19786        if (!mounted) {
19787            return;
19788        }
19789
19790        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19791        int[] users;
19792        if (userId == UserHandle.USER_ALL) {
19793            users = sUserManager.getUserIds();
19794        } else {
19795            users = new int[] { userId };
19796        }
19797        final ClearStorageConnection conn = new ClearStorageConnection();
19798        if (mContext.bindServiceAsUser(
19799                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19800            try {
19801                for (int curUser : users) {
19802                    long timeout = SystemClock.uptimeMillis() + 5000;
19803                    synchronized (conn) {
19804                        long now;
19805                        while (conn.mContainerService == null &&
19806                                (now = SystemClock.uptimeMillis()) < timeout) {
19807                            try {
19808                                conn.wait(timeout - now);
19809                            } catch (InterruptedException e) {
19810                            }
19811                        }
19812                    }
19813                    if (conn.mContainerService == null) {
19814                        return;
19815                    }
19816
19817                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19818                    clearDirectory(conn.mContainerService,
19819                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19820                    if (allData) {
19821                        clearDirectory(conn.mContainerService,
19822                                userEnv.buildExternalStorageAppDataDirs(packageName));
19823                        clearDirectory(conn.mContainerService,
19824                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19825                    }
19826                }
19827            } finally {
19828                mContext.unbindService(conn);
19829            }
19830        }
19831    }
19832
19833    @Override
19834    public void clearApplicationProfileData(String packageName) {
19835        enforceSystemOrRoot("Only the system can clear all profile data");
19836
19837        final PackageParser.Package pkg;
19838        synchronized (mPackages) {
19839            pkg = mPackages.get(packageName);
19840        }
19841
19842        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19843            synchronized (mInstallLock) {
19844                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19845            }
19846        }
19847    }
19848
19849    @Override
19850    public void clearApplicationUserData(final String packageName,
19851            final IPackageDataObserver observer, final int userId) {
19852        mContext.enforceCallingOrSelfPermission(
19853                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19854
19855        final int callingUid = Binder.getCallingUid();
19856        enforceCrossUserPermission(callingUid, userId,
19857                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19858
19859        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19860        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19861            return;
19862        }
19863        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19864            throw new SecurityException("Cannot clear data for a protected package: "
19865                    + packageName);
19866        }
19867        // Queue up an async operation since the package deletion may take a little while.
19868        mHandler.post(new Runnable() {
19869            public void run() {
19870                mHandler.removeCallbacks(this);
19871                final boolean succeeded;
19872                try (PackageFreezer freezer = freezePackage(packageName,
19873                        "clearApplicationUserData")) {
19874                    synchronized (mInstallLock) {
19875                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19876                    }
19877                    clearExternalStorageDataSync(packageName, userId, true);
19878                    synchronized (mPackages) {
19879                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19880                                packageName, userId);
19881                    }
19882                }
19883                if (succeeded) {
19884                    // invoke DeviceStorageMonitor's update method to clear any notifications
19885                    DeviceStorageMonitorInternal dsm = LocalServices
19886                            .getService(DeviceStorageMonitorInternal.class);
19887                    if (dsm != null) {
19888                        dsm.checkMemory();
19889                    }
19890                }
19891                if(observer != null) {
19892                    try {
19893                        observer.onRemoveCompleted(packageName, succeeded);
19894                    } catch (RemoteException e) {
19895                        Log.i(TAG, "Observer no longer exists.");
19896                    }
19897                } //end if observer
19898            } //end run
19899        });
19900    }
19901
19902    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19903        if (packageName == null) {
19904            Slog.w(TAG, "Attempt to delete null packageName.");
19905            return false;
19906        }
19907
19908        // Try finding details about the requested package
19909        PackageParser.Package pkg;
19910        synchronized (mPackages) {
19911            pkg = mPackages.get(packageName);
19912            if (pkg == null) {
19913                final PackageSetting ps = mSettings.mPackages.get(packageName);
19914                if (ps != null) {
19915                    pkg = ps.pkg;
19916                }
19917            }
19918
19919            if (pkg == null) {
19920                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19921                return false;
19922            }
19923
19924            PackageSetting ps = (PackageSetting) pkg.mExtras;
19925            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19926        }
19927
19928        clearAppDataLIF(pkg, userId,
19929                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19930
19931        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19932        removeKeystoreDataIfNeeded(userId, appId);
19933
19934        UserManagerInternal umInternal = getUserManagerInternal();
19935        final int flags;
19936        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19937            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19938        } else if (umInternal.isUserRunning(userId)) {
19939            flags = StorageManager.FLAG_STORAGE_DE;
19940        } else {
19941            flags = 0;
19942        }
19943        prepareAppDataContentsLIF(pkg, userId, flags);
19944
19945        return true;
19946    }
19947
19948    /**
19949     * Reverts user permission state changes (permissions and flags) in
19950     * all packages for a given user.
19951     *
19952     * @param userId The device user for which to do a reset.
19953     */
19954    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19955        final int packageCount = mPackages.size();
19956        for (int i = 0; i < packageCount; i++) {
19957            PackageParser.Package pkg = mPackages.valueAt(i);
19958            PackageSetting ps = (PackageSetting) pkg.mExtras;
19959            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19960        }
19961    }
19962
19963    private void resetNetworkPolicies(int userId) {
19964        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19965    }
19966
19967    /**
19968     * Reverts user permission state changes (permissions and flags).
19969     *
19970     * @param ps The package for which to reset.
19971     * @param userId The device user for which to do a reset.
19972     */
19973    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19974            final PackageSetting ps, final int userId) {
19975        if (ps.pkg == null) {
19976            return;
19977        }
19978
19979        // These are flags that can change base on user actions.
19980        final int userSettableMask = FLAG_PERMISSION_USER_SET
19981                | FLAG_PERMISSION_USER_FIXED
19982                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19983                | FLAG_PERMISSION_REVIEW_REQUIRED;
19984
19985        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19986                | FLAG_PERMISSION_POLICY_FIXED;
19987
19988        boolean writeInstallPermissions = false;
19989        boolean writeRuntimePermissions = false;
19990
19991        final int permissionCount = ps.pkg.requestedPermissions.size();
19992        for (int i = 0; i < permissionCount; i++) {
19993            String permission = ps.pkg.requestedPermissions.get(i);
19994
19995            BasePermission bp = mSettings.mPermissions.get(permission);
19996            if (bp == null) {
19997                continue;
19998            }
19999
20000            // If shared user we just reset the state to which only this app contributed.
20001            if (ps.sharedUser != null) {
20002                boolean used = false;
20003                final int packageCount = ps.sharedUser.packages.size();
20004                for (int j = 0; j < packageCount; j++) {
20005                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20006                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20007                            && pkg.pkg.requestedPermissions.contains(permission)) {
20008                        used = true;
20009                        break;
20010                    }
20011                }
20012                if (used) {
20013                    continue;
20014                }
20015            }
20016
20017            PermissionsState permissionsState = ps.getPermissionsState();
20018
20019            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20020
20021            // Always clear the user settable flags.
20022            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20023                    bp.name) != null;
20024            // If permission review is enabled and this is a legacy app, mark the
20025            // permission as requiring a review as this is the initial state.
20026            int flags = 0;
20027            if (mPermissionReviewRequired
20028                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20029                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20030            }
20031            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20032                if (hasInstallState) {
20033                    writeInstallPermissions = true;
20034                } else {
20035                    writeRuntimePermissions = true;
20036                }
20037            }
20038
20039            // Below is only runtime permission handling.
20040            if (!bp.isRuntime()) {
20041                continue;
20042            }
20043
20044            // Never clobber system or policy.
20045            if ((oldFlags & policyOrSystemFlags) != 0) {
20046                continue;
20047            }
20048
20049            // If this permission was granted by default, make sure it is.
20050            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20051                if (permissionsState.grantRuntimePermission(bp, userId)
20052                        != PERMISSION_OPERATION_FAILURE) {
20053                    writeRuntimePermissions = true;
20054                }
20055            // If permission review is enabled the permissions for a legacy apps
20056            // are represented as constantly granted runtime ones, so don't revoke.
20057            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20058                // Otherwise, reset the permission.
20059                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20060                switch (revokeResult) {
20061                    case PERMISSION_OPERATION_SUCCESS:
20062                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20063                        writeRuntimePermissions = true;
20064                        final int appId = ps.appId;
20065                        mHandler.post(new Runnable() {
20066                            @Override
20067                            public void run() {
20068                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20069                            }
20070                        });
20071                    } break;
20072                }
20073            }
20074        }
20075
20076        // Synchronously write as we are taking permissions away.
20077        if (writeRuntimePermissions) {
20078            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20079        }
20080
20081        // Synchronously write as we are taking permissions away.
20082        if (writeInstallPermissions) {
20083            mSettings.writeLPr();
20084        }
20085    }
20086
20087    /**
20088     * Remove entries from the keystore daemon. Will only remove it if the
20089     * {@code appId} is valid.
20090     */
20091    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20092        if (appId < 0) {
20093            return;
20094        }
20095
20096        final KeyStore keyStore = KeyStore.getInstance();
20097        if (keyStore != null) {
20098            if (userId == UserHandle.USER_ALL) {
20099                for (final int individual : sUserManager.getUserIds()) {
20100                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20101                }
20102            } else {
20103                keyStore.clearUid(UserHandle.getUid(userId, appId));
20104            }
20105        } else {
20106            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20107        }
20108    }
20109
20110    @Override
20111    public void deleteApplicationCacheFiles(final String packageName,
20112            final IPackageDataObserver observer) {
20113        final int userId = UserHandle.getCallingUserId();
20114        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20115    }
20116
20117    @Override
20118    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20119            final IPackageDataObserver observer) {
20120        final int callingUid = Binder.getCallingUid();
20121        mContext.enforceCallingOrSelfPermission(
20122                android.Manifest.permission.DELETE_CACHE_FILES, null);
20123        enforceCrossUserPermission(callingUid, userId,
20124                /* requireFullPermission= */ true, /* checkShell= */ false,
20125                "delete application cache files");
20126        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20127                android.Manifest.permission.ACCESS_INSTANT_APPS);
20128
20129        final PackageParser.Package pkg;
20130        synchronized (mPackages) {
20131            pkg = mPackages.get(packageName);
20132        }
20133
20134        // Queue up an async operation since the package deletion may take a little while.
20135        mHandler.post(new Runnable() {
20136            public void run() {
20137                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20138                boolean doClearData = true;
20139                if (ps != null) {
20140                    final boolean targetIsInstantApp =
20141                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20142                    doClearData = !targetIsInstantApp
20143                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20144                }
20145                if (doClearData) {
20146                    synchronized (mInstallLock) {
20147                        final int flags = StorageManager.FLAG_STORAGE_DE
20148                                | StorageManager.FLAG_STORAGE_CE;
20149                        // We're only clearing cache files, so we don't care if the
20150                        // app is unfrozen and still able to run
20151                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20152                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20153                    }
20154                    clearExternalStorageDataSync(packageName, userId, false);
20155                }
20156                if (observer != null) {
20157                    try {
20158                        observer.onRemoveCompleted(packageName, true);
20159                    } catch (RemoteException e) {
20160                        Log.i(TAG, "Observer no longer exists.");
20161                    }
20162                }
20163            }
20164        });
20165    }
20166
20167    @Override
20168    public void getPackageSizeInfo(final String packageName, int userHandle,
20169            final IPackageStatsObserver observer) {
20170        throw new UnsupportedOperationException(
20171                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20172    }
20173
20174    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20175        final PackageSetting ps;
20176        synchronized (mPackages) {
20177            ps = mSettings.mPackages.get(packageName);
20178            if (ps == null) {
20179                Slog.w(TAG, "Failed to find settings for " + packageName);
20180                return false;
20181            }
20182        }
20183
20184        final String[] packageNames = { packageName };
20185        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20186        final String[] codePaths = { ps.codePathString };
20187
20188        try {
20189            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20190                    ps.appId, ceDataInodes, codePaths, stats);
20191
20192            // For now, ignore code size of packages on system partition
20193            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20194                stats.codeSize = 0;
20195            }
20196
20197            // External clients expect these to be tracked separately
20198            stats.dataSize -= stats.cacheSize;
20199
20200        } catch (InstallerException e) {
20201            Slog.w(TAG, String.valueOf(e));
20202            return false;
20203        }
20204
20205        return true;
20206    }
20207
20208    private int getUidTargetSdkVersionLockedLPr(int uid) {
20209        Object obj = mSettings.getUserIdLPr(uid);
20210        if (obj instanceof SharedUserSetting) {
20211            final SharedUserSetting sus = (SharedUserSetting) obj;
20212            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20213            final Iterator<PackageSetting> it = sus.packages.iterator();
20214            while (it.hasNext()) {
20215                final PackageSetting ps = it.next();
20216                if (ps.pkg != null) {
20217                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20218                    if (v < vers) vers = v;
20219                }
20220            }
20221            return vers;
20222        } else if (obj instanceof PackageSetting) {
20223            final PackageSetting ps = (PackageSetting) obj;
20224            if (ps.pkg != null) {
20225                return ps.pkg.applicationInfo.targetSdkVersion;
20226            }
20227        }
20228        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20229    }
20230
20231    @Override
20232    public void addPreferredActivity(IntentFilter filter, int match,
20233            ComponentName[] set, ComponentName activity, int userId) {
20234        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20235                "Adding preferred");
20236    }
20237
20238    private void addPreferredActivityInternal(IntentFilter filter, int match,
20239            ComponentName[] set, ComponentName activity, boolean always, int userId,
20240            String opname) {
20241        // writer
20242        int callingUid = Binder.getCallingUid();
20243        enforceCrossUserPermission(callingUid, userId,
20244                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20245        if (filter.countActions() == 0) {
20246            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20247            return;
20248        }
20249        synchronized (mPackages) {
20250            if (mContext.checkCallingOrSelfPermission(
20251                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20252                    != PackageManager.PERMISSION_GRANTED) {
20253                if (getUidTargetSdkVersionLockedLPr(callingUid)
20254                        < Build.VERSION_CODES.FROYO) {
20255                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20256                            + callingUid);
20257                    return;
20258                }
20259                mContext.enforceCallingOrSelfPermission(
20260                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20261            }
20262
20263            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20264            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20265                    + userId + ":");
20266            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20267            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20268            scheduleWritePackageRestrictionsLocked(userId);
20269            postPreferredActivityChangedBroadcast(userId);
20270        }
20271    }
20272
20273    private void postPreferredActivityChangedBroadcast(int userId) {
20274        mHandler.post(() -> {
20275            final IActivityManager am = ActivityManager.getService();
20276            if (am == null) {
20277                return;
20278            }
20279
20280            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20281            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20282            try {
20283                am.broadcastIntent(null, intent, null, null,
20284                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20285                        null, false, false, userId);
20286            } catch (RemoteException e) {
20287            }
20288        });
20289    }
20290
20291    @Override
20292    public void replacePreferredActivity(IntentFilter filter, int match,
20293            ComponentName[] set, ComponentName activity, int userId) {
20294        if (filter.countActions() != 1) {
20295            throw new IllegalArgumentException(
20296                    "replacePreferredActivity expects filter to have only 1 action.");
20297        }
20298        if (filter.countDataAuthorities() != 0
20299                || filter.countDataPaths() != 0
20300                || filter.countDataSchemes() > 1
20301                || filter.countDataTypes() != 0) {
20302            throw new IllegalArgumentException(
20303                    "replacePreferredActivity expects filter to have no data authorities, " +
20304                    "paths, or types; and at most one scheme.");
20305        }
20306
20307        final int callingUid = Binder.getCallingUid();
20308        enforceCrossUserPermission(callingUid, userId,
20309                true /* requireFullPermission */, false /* checkShell */,
20310                "replace preferred activity");
20311        synchronized (mPackages) {
20312            if (mContext.checkCallingOrSelfPermission(
20313                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20314                    != PackageManager.PERMISSION_GRANTED) {
20315                if (getUidTargetSdkVersionLockedLPr(callingUid)
20316                        < Build.VERSION_CODES.FROYO) {
20317                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20318                            + Binder.getCallingUid());
20319                    return;
20320                }
20321                mContext.enforceCallingOrSelfPermission(
20322                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20323            }
20324
20325            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20326            if (pir != null) {
20327                // Get all of the existing entries that exactly match this filter.
20328                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20329                if (existing != null && existing.size() == 1) {
20330                    PreferredActivity cur = existing.get(0);
20331                    if (DEBUG_PREFERRED) {
20332                        Slog.i(TAG, "Checking replace of preferred:");
20333                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20334                        if (!cur.mPref.mAlways) {
20335                            Slog.i(TAG, "  -- CUR; not mAlways!");
20336                        } else {
20337                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20338                            Slog.i(TAG, "  -- CUR: mSet="
20339                                    + Arrays.toString(cur.mPref.mSetComponents));
20340                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20341                            Slog.i(TAG, "  -- NEW: mMatch="
20342                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20343                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20344                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20345                        }
20346                    }
20347                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20348                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20349                            && cur.mPref.sameSet(set)) {
20350                        // Setting the preferred activity to what it happens to be already
20351                        if (DEBUG_PREFERRED) {
20352                            Slog.i(TAG, "Replacing with same preferred activity "
20353                                    + cur.mPref.mShortComponent + " for user "
20354                                    + userId + ":");
20355                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20356                        }
20357                        return;
20358                    }
20359                }
20360
20361                if (existing != null) {
20362                    if (DEBUG_PREFERRED) {
20363                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20364                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20365                    }
20366                    for (int i = 0; i < existing.size(); i++) {
20367                        PreferredActivity pa = existing.get(i);
20368                        if (DEBUG_PREFERRED) {
20369                            Slog.i(TAG, "Removing existing preferred activity "
20370                                    + pa.mPref.mComponent + ":");
20371                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20372                        }
20373                        pir.removeFilter(pa);
20374                    }
20375                }
20376            }
20377            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20378                    "Replacing preferred");
20379        }
20380    }
20381
20382    @Override
20383    public void clearPackagePreferredActivities(String packageName) {
20384        final int callingUid = Binder.getCallingUid();
20385        if (getInstantAppPackageName(callingUid) != null) {
20386            return;
20387        }
20388        // writer
20389        synchronized (mPackages) {
20390            PackageParser.Package pkg = mPackages.get(packageName);
20391            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20392                if (mContext.checkCallingOrSelfPermission(
20393                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20394                        != PackageManager.PERMISSION_GRANTED) {
20395                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20396                            < Build.VERSION_CODES.FROYO) {
20397                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20398                                + callingUid);
20399                        return;
20400                    }
20401                    mContext.enforceCallingOrSelfPermission(
20402                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20403                }
20404            }
20405            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20406            if (ps != null
20407                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20408                return;
20409            }
20410            int user = UserHandle.getCallingUserId();
20411            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20412                scheduleWritePackageRestrictionsLocked(user);
20413            }
20414        }
20415    }
20416
20417    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20418    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20419        ArrayList<PreferredActivity> removed = null;
20420        boolean changed = false;
20421        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20422            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20423            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20424            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20425                continue;
20426            }
20427            Iterator<PreferredActivity> it = pir.filterIterator();
20428            while (it.hasNext()) {
20429                PreferredActivity pa = it.next();
20430                // Mark entry for removal only if it matches the package name
20431                // and the entry is of type "always".
20432                if (packageName == null ||
20433                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20434                                && pa.mPref.mAlways)) {
20435                    if (removed == null) {
20436                        removed = new ArrayList<PreferredActivity>();
20437                    }
20438                    removed.add(pa);
20439                }
20440            }
20441            if (removed != null) {
20442                for (int j=0; j<removed.size(); j++) {
20443                    PreferredActivity pa = removed.get(j);
20444                    pir.removeFilter(pa);
20445                }
20446                changed = true;
20447            }
20448        }
20449        if (changed) {
20450            postPreferredActivityChangedBroadcast(userId);
20451        }
20452        return changed;
20453    }
20454
20455    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20456    private void clearIntentFilterVerificationsLPw(int userId) {
20457        final int packageCount = mPackages.size();
20458        for (int i = 0; i < packageCount; i++) {
20459            PackageParser.Package pkg = mPackages.valueAt(i);
20460            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20461        }
20462    }
20463
20464    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20465    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20466        if (userId == UserHandle.USER_ALL) {
20467            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20468                    sUserManager.getUserIds())) {
20469                for (int oneUserId : sUserManager.getUserIds()) {
20470                    scheduleWritePackageRestrictionsLocked(oneUserId);
20471                }
20472            }
20473        } else {
20474            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20475                scheduleWritePackageRestrictionsLocked(userId);
20476            }
20477        }
20478    }
20479
20480    /** Clears state for all users, and touches intent filter verification policy */
20481    void clearDefaultBrowserIfNeeded(String packageName) {
20482        for (int oneUserId : sUserManager.getUserIds()) {
20483            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20484        }
20485    }
20486
20487    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20488        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20489        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20490            if (packageName.equals(defaultBrowserPackageName)) {
20491                setDefaultBrowserPackageName(null, userId);
20492            }
20493        }
20494    }
20495
20496    @Override
20497    public void resetApplicationPreferences(int userId) {
20498        mContext.enforceCallingOrSelfPermission(
20499                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20500        final long identity = Binder.clearCallingIdentity();
20501        // writer
20502        try {
20503            synchronized (mPackages) {
20504                clearPackagePreferredActivitiesLPw(null, userId);
20505                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20506                // TODO: We have to reset the default SMS and Phone. This requires
20507                // significant refactoring to keep all default apps in the package
20508                // manager (cleaner but more work) or have the services provide
20509                // callbacks to the package manager to request a default app reset.
20510                applyFactoryDefaultBrowserLPw(userId);
20511                clearIntentFilterVerificationsLPw(userId);
20512                primeDomainVerificationsLPw(userId);
20513                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20514                scheduleWritePackageRestrictionsLocked(userId);
20515            }
20516            resetNetworkPolicies(userId);
20517        } finally {
20518            Binder.restoreCallingIdentity(identity);
20519        }
20520    }
20521
20522    @Override
20523    public int getPreferredActivities(List<IntentFilter> outFilters,
20524            List<ComponentName> outActivities, String packageName) {
20525        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20526            return 0;
20527        }
20528        int num = 0;
20529        final int userId = UserHandle.getCallingUserId();
20530        // reader
20531        synchronized (mPackages) {
20532            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20533            if (pir != null) {
20534                final Iterator<PreferredActivity> it = pir.filterIterator();
20535                while (it.hasNext()) {
20536                    final PreferredActivity pa = it.next();
20537                    if (packageName == null
20538                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20539                                    && pa.mPref.mAlways)) {
20540                        if (outFilters != null) {
20541                            outFilters.add(new IntentFilter(pa));
20542                        }
20543                        if (outActivities != null) {
20544                            outActivities.add(pa.mPref.mComponent);
20545                        }
20546                    }
20547                }
20548            }
20549        }
20550
20551        return num;
20552    }
20553
20554    @Override
20555    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20556            int userId) {
20557        int callingUid = Binder.getCallingUid();
20558        if (callingUid != Process.SYSTEM_UID) {
20559            throw new SecurityException(
20560                    "addPersistentPreferredActivity can only be run by the system");
20561        }
20562        if (filter.countActions() == 0) {
20563            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20564            return;
20565        }
20566        synchronized (mPackages) {
20567            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20568                    ":");
20569            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20570            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20571                    new PersistentPreferredActivity(filter, activity));
20572            scheduleWritePackageRestrictionsLocked(userId);
20573            postPreferredActivityChangedBroadcast(userId);
20574        }
20575    }
20576
20577    @Override
20578    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20579        int callingUid = Binder.getCallingUid();
20580        if (callingUid != Process.SYSTEM_UID) {
20581            throw new SecurityException(
20582                    "clearPackagePersistentPreferredActivities can only be run by the system");
20583        }
20584        ArrayList<PersistentPreferredActivity> removed = null;
20585        boolean changed = false;
20586        synchronized (mPackages) {
20587            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20588                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20589                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20590                        .valueAt(i);
20591                if (userId != thisUserId) {
20592                    continue;
20593                }
20594                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20595                while (it.hasNext()) {
20596                    PersistentPreferredActivity ppa = it.next();
20597                    // Mark entry for removal only if it matches the package name.
20598                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20599                        if (removed == null) {
20600                            removed = new ArrayList<PersistentPreferredActivity>();
20601                        }
20602                        removed.add(ppa);
20603                    }
20604                }
20605                if (removed != null) {
20606                    for (int j=0; j<removed.size(); j++) {
20607                        PersistentPreferredActivity ppa = removed.get(j);
20608                        ppir.removeFilter(ppa);
20609                    }
20610                    changed = true;
20611                }
20612            }
20613
20614            if (changed) {
20615                scheduleWritePackageRestrictionsLocked(userId);
20616                postPreferredActivityChangedBroadcast(userId);
20617            }
20618        }
20619    }
20620
20621    /**
20622     * Common machinery for picking apart a restored XML blob and passing
20623     * it to a caller-supplied functor to be applied to the running system.
20624     */
20625    private void restoreFromXml(XmlPullParser parser, int userId,
20626            String expectedStartTag, BlobXmlRestorer functor)
20627            throws IOException, XmlPullParserException {
20628        int type;
20629        while ((type = parser.next()) != XmlPullParser.START_TAG
20630                && type != XmlPullParser.END_DOCUMENT) {
20631        }
20632        if (type != XmlPullParser.START_TAG) {
20633            // oops didn't find a start tag?!
20634            if (DEBUG_BACKUP) {
20635                Slog.e(TAG, "Didn't find start tag during restore");
20636            }
20637            return;
20638        }
20639Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20640        // this is supposed to be TAG_PREFERRED_BACKUP
20641        if (!expectedStartTag.equals(parser.getName())) {
20642            if (DEBUG_BACKUP) {
20643                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20644            }
20645            return;
20646        }
20647
20648        // skip interfering stuff, then we're aligned with the backing implementation
20649        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20650Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20651        functor.apply(parser, userId);
20652    }
20653
20654    private interface BlobXmlRestorer {
20655        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20656    }
20657
20658    /**
20659     * Non-Binder method, support for the backup/restore mechanism: write the
20660     * full set of preferred activities in its canonical XML format.  Returns the
20661     * XML output as a byte array, or null if there is none.
20662     */
20663    @Override
20664    public byte[] getPreferredActivityBackup(int userId) {
20665        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20666            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20667        }
20668
20669        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20670        try {
20671            final XmlSerializer serializer = new FastXmlSerializer();
20672            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20673            serializer.startDocument(null, true);
20674            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20675
20676            synchronized (mPackages) {
20677                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20678            }
20679
20680            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20681            serializer.endDocument();
20682            serializer.flush();
20683        } catch (Exception e) {
20684            if (DEBUG_BACKUP) {
20685                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20686            }
20687            return null;
20688        }
20689
20690        return dataStream.toByteArray();
20691    }
20692
20693    @Override
20694    public void restorePreferredActivities(byte[] backup, int userId) {
20695        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20696            throw new SecurityException("Only the system may call restorePreferredActivities()");
20697        }
20698
20699        try {
20700            final XmlPullParser parser = Xml.newPullParser();
20701            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20702            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20703                    new BlobXmlRestorer() {
20704                        @Override
20705                        public void apply(XmlPullParser parser, int userId)
20706                                throws XmlPullParserException, IOException {
20707                            synchronized (mPackages) {
20708                                mSettings.readPreferredActivitiesLPw(parser, userId);
20709                            }
20710                        }
20711                    } );
20712        } catch (Exception e) {
20713            if (DEBUG_BACKUP) {
20714                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20715            }
20716        }
20717    }
20718
20719    /**
20720     * Non-Binder method, support for the backup/restore mechanism: write the
20721     * default browser (etc) settings in its canonical XML format.  Returns the default
20722     * browser XML representation as a byte array, or null if there is none.
20723     */
20724    @Override
20725    public byte[] getDefaultAppsBackup(int userId) {
20726        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20727            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20728        }
20729
20730        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20731        try {
20732            final XmlSerializer serializer = new FastXmlSerializer();
20733            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20734            serializer.startDocument(null, true);
20735            serializer.startTag(null, TAG_DEFAULT_APPS);
20736
20737            synchronized (mPackages) {
20738                mSettings.writeDefaultAppsLPr(serializer, userId);
20739            }
20740
20741            serializer.endTag(null, TAG_DEFAULT_APPS);
20742            serializer.endDocument();
20743            serializer.flush();
20744        } catch (Exception e) {
20745            if (DEBUG_BACKUP) {
20746                Slog.e(TAG, "Unable to write default apps for backup", e);
20747            }
20748            return null;
20749        }
20750
20751        return dataStream.toByteArray();
20752    }
20753
20754    @Override
20755    public void restoreDefaultApps(byte[] backup, int userId) {
20756        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20757            throw new SecurityException("Only the system may call restoreDefaultApps()");
20758        }
20759
20760        try {
20761            final XmlPullParser parser = Xml.newPullParser();
20762            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20763            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20764                    new BlobXmlRestorer() {
20765                        @Override
20766                        public void apply(XmlPullParser parser, int userId)
20767                                throws XmlPullParserException, IOException {
20768                            synchronized (mPackages) {
20769                                mSettings.readDefaultAppsLPw(parser, userId);
20770                            }
20771                        }
20772                    } );
20773        } catch (Exception e) {
20774            if (DEBUG_BACKUP) {
20775                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20776            }
20777        }
20778    }
20779
20780    @Override
20781    public byte[] getIntentFilterVerificationBackup(int userId) {
20782        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20783            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20784        }
20785
20786        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20787        try {
20788            final XmlSerializer serializer = new FastXmlSerializer();
20789            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20790            serializer.startDocument(null, true);
20791            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20792
20793            synchronized (mPackages) {
20794                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20795            }
20796
20797            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20798            serializer.endDocument();
20799            serializer.flush();
20800        } catch (Exception e) {
20801            if (DEBUG_BACKUP) {
20802                Slog.e(TAG, "Unable to write default apps for backup", e);
20803            }
20804            return null;
20805        }
20806
20807        return dataStream.toByteArray();
20808    }
20809
20810    @Override
20811    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20812        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20813            throw new SecurityException("Only the system may call restorePreferredActivities()");
20814        }
20815
20816        try {
20817            final XmlPullParser parser = Xml.newPullParser();
20818            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20819            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20820                    new BlobXmlRestorer() {
20821                        @Override
20822                        public void apply(XmlPullParser parser, int userId)
20823                                throws XmlPullParserException, IOException {
20824                            synchronized (mPackages) {
20825                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20826                                mSettings.writeLPr();
20827                            }
20828                        }
20829                    } );
20830        } catch (Exception e) {
20831            if (DEBUG_BACKUP) {
20832                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20833            }
20834        }
20835    }
20836
20837    @Override
20838    public byte[] getPermissionGrantBackup(int userId) {
20839        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20840            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20841        }
20842
20843        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20844        try {
20845            final XmlSerializer serializer = new FastXmlSerializer();
20846            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20847            serializer.startDocument(null, true);
20848            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20849
20850            synchronized (mPackages) {
20851                serializeRuntimePermissionGrantsLPr(serializer, userId);
20852            }
20853
20854            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20855            serializer.endDocument();
20856            serializer.flush();
20857        } catch (Exception e) {
20858            if (DEBUG_BACKUP) {
20859                Slog.e(TAG, "Unable to write default apps for backup", e);
20860            }
20861            return null;
20862        }
20863
20864        return dataStream.toByteArray();
20865    }
20866
20867    @Override
20868    public void restorePermissionGrants(byte[] backup, int userId) {
20869        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20870            throw new SecurityException("Only the system may call restorePermissionGrants()");
20871        }
20872
20873        try {
20874            final XmlPullParser parser = Xml.newPullParser();
20875            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20876            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20877                    new BlobXmlRestorer() {
20878                        @Override
20879                        public void apply(XmlPullParser parser, int userId)
20880                                throws XmlPullParserException, IOException {
20881                            synchronized (mPackages) {
20882                                processRestoredPermissionGrantsLPr(parser, userId);
20883                            }
20884                        }
20885                    } );
20886        } catch (Exception e) {
20887            if (DEBUG_BACKUP) {
20888                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20889            }
20890        }
20891    }
20892
20893    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20894            throws IOException {
20895        serializer.startTag(null, TAG_ALL_GRANTS);
20896
20897        final int N = mSettings.mPackages.size();
20898        for (int i = 0; i < N; i++) {
20899            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20900            boolean pkgGrantsKnown = false;
20901
20902            PermissionsState packagePerms = ps.getPermissionsState();
20903
20904            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20905                final int grantFlags = state.getFlags();
20906                // only look at grants that are not system/policy fixed
20907                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20908                    final boolean isGranted = state.isGranted();
20909                    // And only back up the user-twiddled state bits
20910                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20911                        final String packageName = mSettings.mPackages.keyAt(i);
20912                        if (!pkgGrantsKnown) {
20913                            serializer.startTag(null, TAG_GRANT);
20914                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20915                            pkgGrantsKnown = true;
20916                        }
20917
20918                        final boolean userSet =
20919                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20920                        final boolean userFixed =
20921                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20922                        final boolean revoke =
20923                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20924
20925                        serializer.startTag(null, TAG_PERMISSION);
20926                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20927                        if (isGranted) {
20928                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20929                        }
20930                        if (userSet) {
20931                            serializer.attribute(null, ATTR_USER_SET, "true");
20932                        }
20933                        if (userFixed) {
20934                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20935                        }
20936                        if (revoke) {
20937                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20938                        }
20939                        serializer.endTag(null, TAG_PERMISSION);
20940                    }
20941                }
20942            }
20943
20944            if (pkgGrantsKnown) {
20945                serializer.endTag(null, TAG_GRANT);
20946            }
20947        }
20948
20949        serializer.endTag(null, TAG_ALL_GRANTS);
20950    }
20951
20952    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20953            throws XmlPullParserException, IOException {
20954        String pkgName = null;
20955        int outerDepth = parser.getDepth();
20956        int type;
20957        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20958                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20959            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20960                continue;
20961            }
20962
20963            final String tagName = parser.getName();
20964            if (tagName.equals(TAG_GRANT)) {
20965                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20966                if (DEBUG_BACKUP) {
20967                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20968                }
20969            } else if (tagName.equals(TAG_PERMISSION)) {
20970
20971                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20972                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20973
20974                int newFlagSet = 0;
20975                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20976                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20977                }
20978                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20979                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20980                }
20981                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20982                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20983                }
20984                if (DEBUG_BACKUP) {
20985                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20986                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20987                }
20988                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20989                if (ps != null) {
20990                    // Already installed so we apply the grant immediately
20991                    if (DEBUG_BACKUP) {
20992                        Slog.v(TAG, "        + already installed; applying");
20993                    }
20994                    PermissionsState perms = ps.getPermissionsState();
20995                    BasePermission bp = mSettings.mPermissions.get(permName);
20996                    if (bp != null) {
20997                        if (isGranted) {
20998                            perms.grantRuntimePermission(bp, userId);
20999                        }
21000                        if (newFlagSet != 0) {
21001                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21002                        }
21003                    }
21004                } else {
21005                    // Need to wait for post-restore install to apply the grant
21006                    if (DEBUG_BACKUP) {
21007                        Slog.v(TAG, "        - not yet installed; saving for later");
21008                    }
21009                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21010                            isGranted, newFlagSet, userId);
21011                }
21012            } else {
21013                PackageManagerService.reportSettingsProblem(Log.WARN,
21014                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21015                XmlUtils.skipCurrentTag(parser);
21016            }
21017        }
21018
21019        scheduleWriteSettingsLocked();
21020        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21021    }
21022
21023    @Override
21024    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21025            int sourceUserId, int targetUserId, int flags) {
21026        mContext.enforceCallingOrSelfPermission(
21027                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21028        int callingUid = Binder.getCallingUid();
21029        enforceOwnerRights(ownerPackage, callingUid);
21030        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21031        if (intentFilter.countActions() == 0) {
21032            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21033            return;
21034        }
21035        synchronized (mPackages) {
21036            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21037                    ownerPackage, targetUserId, flags);
21038            CrossProfileIntentResolver resolver =
21039                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21040            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21041            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21042            if (existing != null) {
21043                int size = existing.size();
21044                for (int i = 0; i < size; i++) {
21045                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21046                        return;
21047                    }
21048                }
21049            }
21050            resolver.addFilter(newFilter);
21051            scheduleWritePackageRestrictionsLocked(sourceUserId);
21052        }
21053    }
21054
21055    @Override
21056    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21057        mContext.enforceCallingOrSelfPermission(
21058                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21059        final int callingUid = Binder.getCallingUid();
21060        enforceOwnerRights(ownerPackage, callingUid);
21061        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21062        synchronized (mPackages) {
21063            CrossProfileIntentResolver resolver =
21064                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21065            ArraySet<CrossProfileIntentFilter> set =
21066                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21067            for (CrossProfileIntentFilter filter : set) {
21068                if (filter.getOwnerPackage().equals(ownerPackage)) {
21069                    resolver.removeFilter(filter);
21070                }
21071            }
21072            scheduleWritePackageRestrictionsLocked(sourceUserId);
21073        }
21074    }
21075
21076    // Enforcing that callingUid is owning pkg on userId
21077    private void enforceOwnerRights(String pkg, int callingUid) {
21078        // The system owns everything.
21079        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21080            return;
21081        }
21082        final int callingUserId = UserHandle.getUserId(callingUid);
21083        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21084        if (pi == null) {
21085            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21086                    + callingUserId);
21087        }
21088        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21089            throw new SecurityException("Calling uid " + callingUid
21090                    + " does not own package " + pkg);
21091        }
21092    }
21093
21094    @Override
21095    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21096        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21097            return null;
21098        }
21099        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21100    }
21101
21102    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21103        UserManagerService ums = UserManagerService.getInstance();
21104        if (ums != null) {
21105            final UserInfo parent = ums.getProfileParent(userId);
21106            final int launcherUid = (parent != null) ? parent.id : userId;
21107            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21108            if (launcherComponent != null) {
21109                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21110                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21111                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21112                        .setPackage(launcherComponent.getPackageName());
21113                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21114            }
21115        }
21116    }
21117
21118    /**
21119     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21120     * then reports the most likely home activity or null if there are more than one.
21121     */
21122    private ComponentName getDefaultHomeActivity(int userId) {
21123        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21124        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21125        if (cn != null) {
21126            return cn;
21127        }
21128
21129        // Find the launcher with the highest priority and return that component if there are no
21130        // other home activity with the same priority.
21131        int lastPriority = Integer.MIN_VALUE;
21132        ComponentName lastComponent = null;
21133        final int size = allHomeCandidates.size();
21134        for (int i = 0; i < size; i++) {
21135            final ResolveInfo ri = allHomeCandidates.get(i);
21136            if (ri.priority > lastPriority) {
21137                lastComponent = ri.activityInfo.getComponentName();
21138                lastPriority = ri.priority;
21139            } else if (ri.priority == lastPriority) {
21140                // Two components found with same priority.
21141                lastComponent = null;
21142            }
21143        }
21144        return lastComponent;
21145    }
21146
21147    private Intent getHomeIntent() {
21148        Intent intent = new Intent(Intent.ACTION_MAIN);
21149        intent.addCategory(Intent.CATEGORY_HOME);
21150        intent.addCategory(Intent.CATEGORY_DEFAULT);
21151        return intent;
21152    }
21153
21154    private IntentFilter getHomeFilter() {
21155        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21156        filter.addCategory(Intent.CATEGORY_HOME);
21157        filter.addCategory(Intent.CATEGORY_DEFAULT);
21158        return filter;
21159    }
21160
21161    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21162            int userId) {
21163        Intent intent  = getHomeIntent();
21164        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21165                PackageManager.GET_META_DATA, userId);
21166        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21167                true, false, false, userId);
21168
21169        allHomeCandidates.clear();
21170        if (list != null) {
21171            for (ResolveInfo ri : list) {
21172                allHomeCandidates.add(ri);
21173            }
21174        }
21175        return (preferred == null || preferred.activityInfo == null)
21176                ? null
21177                : new ComponentName(preferred.activityInfo.packageName,
21178                        preferred.activityInfo.name);
21179    }
21180
21181    @Override
21182    public void setHomeActivity(ComponentName comp, int userId) {
21183        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21184            return;
21185        }
21186        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21187        getHomeActivitiesAsUser(homeActivities, userId);
21188
21189        boolean found = false;
21190
21191        final int size = homeActivities.size();
21192        final ComponentName[] set = new ComponentName[size];
21193        for (int i = 0; i < size; i++) {
21194            final ResolveInfo candidate = homeActivities.get(i);
21195            final ActivityInfo info = candidate.activityInfo;
21196            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21197            set[i] = activityName;
21198            if (!found && activityName.equals(comp)) {
21199                found = true;
21200            }
21201        }
21202        if (!found) {
21203            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21204                    + userId);
21205        }
21206        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21207                set, comp, userId);
21208    }
21209
21210    private @Nullable String getSetupWizardPackageName() {
21211        final Intent intent = new Intent(Intent.ACTION_MAIN);
21212        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21213
21214        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21215                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21216                        | MATCH_DISABLED_COMPONENTS,
21217                UserHandle.myUserId());
21218        if (matches.size() == 1) {
21219            return matches.get(0).getComponentInfo().packageName;
21220        } else {
21221            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21222                    + ": matches=" + matches);
21223            return null;
21224        }
21225    }
21226
21227    private @Nullable String getStorageManagerPackageName() {
21228        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21229
21230        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21231                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21232                        | MATCH_DISABLED_COMPONENTS,
21233                UserHandle.myUserId());
21234        if (matches.size() == 1) {
21235            return matches.get(0).getComponentInfo().packageName;
21236        } else {
21237            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21238                    + matches.size() + ": matches=" + matches);
21239            return null;
21240        }
21241    }
21242
21243    @Override
21244    public void setApplicationEnabledSetting(String appPackageName,
21245            int newState, int flags, int userId, String callingPackage) {
21246        if (!sUserManager.exists(userId)) return;
21247        if (callingPackage == null) {
21248            callingPackage = Integer.toString(Binder.getCallingUid());
21249        }
21250        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21251    }
21252
21253    @Override
21254    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21255        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21256        synchronized (mPackages) {
21257            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21258            if (pkgSetting != null) {
21259                pkgSetting.setUpdateAvailable(updateAvailable);
21260            }
21261        }
21262    }
21263
21264    @Override
21265    public void setComponentEnabledSetting(ComponentName componentName,
21266            int newState, int flags, int userId) {
21267        if (!sUserManager.exists(userId)) return;
21268        setEnabledSetting(componentName.getPackageName(),
21269                componentName.getClassName(), newState, flags, userId, null);
21270    }
21271
21272    private void setEnabledSetting(final String packageName, String className, int newState,
21273            final int flags, int userId, String callingPackage) {
21274        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21275              || newState == COMPONENT_ENABLED_STATE_ENABLED
21276              || newState == COMPONENT_ENABLED_STATE_DISABLED
21277              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21278              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21279            throw new IllegalArgumentException("Invalid new component state: "
21280                    + newState);
21281        }
21282        PackageSetting pkgSetting;
21283        final int callingUid = Binder.getCallingUid();
21284        final int permission;
21285        if (callingUid == Process.SYSTEM_UID) {
21286            permission = PackageManager.PERMISSION_GRANTED;
21287        } else {
21288            permission = mContext.checkCallingOrSelfPermission(
21289                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21290        }
21291        enforceCrossUserPermission(callingUid, userId,
21292                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21293        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21294        boolean sendNow = false;
21295        boolean isApp = (className == null);
21296        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21297        String componentName = isApp ? packageName : className;
21298        int packageUid = -1;
21299        ArrayList<String> components;
21300
21301        // reader
21302        synchronized (mPackages) {
21303            pkgSetting = mSettings.mPackages.get(packageName);
21304            if (pkgSetting == null) {
21305                if (!isCallerInstantApp) {
21306                    if (className == null) {
21307                        throw new IllegalArgumentException("Unknown package: " + packageName);
21308                    }
21309                    throw new IllegalArgumentException(
21310                            "Unknown component: " + packageName + "/" + className);
21311                } else {
21312                    // throw SecurityException to prevent leaking package information
21313                    throw new SecurityException(
21314                            "Attempt to change component state; "
21315                            + "pid=" + Binder.getCallingPid()
21316                            + ", uid=" + callingUid
21317                            + (className == null
21318                                    ? ", package=" + packageName
21319                                    : ", component=" + packageName + "/" + className));
21320                }
21321            }
21322        }
21323
21324        // Limit who can change which apps
21325        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21326            // Don't allow apps that don't have permission to modify other apps
21327            if (!allowedByPermission
21328                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21329                throw new SecurityException(
21330                        "Attempt to change component state; "
21331                        + "pid=" + Binder.getCallingPid()
21332                        + ", uid=" + callingUid
21333                        + (className == null
21334                                ? ", package=" + packageName
21335                                : ", component=" + packageName + "/" + className));
21336            }
21337            // Don't allow changing protected packages.
21338            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21339                throw new SecurityException("Cannot disable a protected package: " + packageName);
21340            }
21341        }
21342
21343        synchronized (mPackages) {
21344            if (callingUid == Process.SHELL_UID
21345                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21346                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21347                // unless it is a test package.
21348                int oldState = pkgSetting.getEnabled(userId);
21349                if (className == null
21350                    &&
21351                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21352                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21353                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21354                    &&
21355                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21356                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21357                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21358                    // ok
21359                } else {
21360                    throw new SecurityException(
21361                            "Shell cannot change component state for " + packageName + "/"
21362                            + className + " to " + newState);
21363                }
21364            }
21365            if (className == null) {
21366                // We're dealing with an application/package level state change
21367                if (pkgSetting.getEnabled(userId) == newState) {
21368                    // Nothing to do
21369                    return;
21370                }
21371                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21372                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21373                    // Don't care about who enables an app.
21374                    callingPackage = null;
21375                }
21376                pkgSetting.setEnabled(newState, userId, callingPackage);
21377                // pkgSetting.pkg.mSetEnabled = newState;
21378            } else {
21379                // We're dealing with a component level state change
21380                // First, verify that this is a valid class name.
21381                PackageParser.Package pkg = pkgSetting.pkg;
21382                if (pkg == null || !pkg.hasComponentClassName(className)) {
21383                    if (pkg != null &&
21384                            pkg.applicationInfo.targetSdkVersion >=
21385                                    Build.VERSION_CODES.JELLY_BEAN) {
21386                        throw new IllegalArgumentException("Component class " + className
21387                                + " does not exist in " + packageName);
21388                    } else {
21389                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21390                                + className + " does not exist in " + packageName);
21391                    }
21392                }
21393                switch (newState) {
21394                case COMPONENT_ENABLED_STATE_ENABLED:
21395                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21396                        return;
21397                    }
21398                    break;
21399                case COMPONENT_ENABLED_STATE_DISABLED:
21400                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21401                        return;
21402                    }
21403                    break;
21404                case COMPONENT_ENABLED_STATE_DEFAULT:
21405                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21406                        return;
21407                    }
21408                    break;
21409                default:
21410                    Slog.e(TAG, "Invalid new component state: " + newState);
21411                    return;
21412                }
21413            }
21414            scheduleWritePackageRestrictionsLocked(userId);
21415            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21416            final long callingId = Binder.clearCallingIdentity();
21417            try {
21418                updateInstantAppInstallerLocked(packageName);
21419            } finally {
21420                Binder.restoreCallingIdentity(callingId);
21421            }
21422            components = mPendingBroadcasts.get(userId, packageName);
21423            final boolean newPackage = components == null;
21424            if (newPackage) {
21425                components = new ArrayList<String>();
21426            }
21427            if (!components.contains(componentName)) {
21428                components.add(componentName);
21429            }
21430            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21431                sendNow = true;
21432                // Purge entry from pending broadcast list if another one exists already
21433                // since we are sending one right away.
21434                mPendingBroadcasts.remove(userId, packageName);
21435            } else {
21436                if (newPackage) {
21437                    mPendingBroadcasts.put(userId, packageName, components);
21438                }
21439                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21440                    // Schedule a message
21441                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21442                }
21443            }
21444        }
21445
21446        long callingId = Binder.clearCallingIdentity();
21447        try {
21448            if (sendNow) {
21449                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21450                sendPackageChangedBroadcast(packageName,
21451                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21452            }
21453        } finally {
21454            Binder.restoreCallingIdentity(callingId);
21455        }
21456    }
21457
21458    @Override
21459    public void flushPackageRestrictionsAsUser(int userId) {
21460        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21461            return;
21462        }
21463        if (!sUserManager.exists(userId)) {
21464            return;
21465        }
21466        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21467                false /* checkShell */, "flushPackageRestrictions");
21468        synchronized (mPackages) {
21469            mSettings.writePackageRestrictionsLPr(userId);
21470            mDirtyUsers.remove(userId);
21471            if (mDirtyUsers.isEmpty()) {
21472                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21473            }
21474        }
21475    }
21476
21477    private void sendPackageChangedBroadcast(String packageName,
21478            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21479        if (DEBUG_INSTALL)
21480            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21481                    + componentNames);
21482        Bundle extras = new Bundle(4);
21483        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21484        String nameList[] = new String[componentNames.size()];
21485        componentNames.toArray(nameList);
21486        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21487        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21488        extras.putInt(Intent.EXTRA_UID, packageUid);
21489        // If this is not reporting a change of the overall package, then only send it
21490        // to registered receivers.  We don't want to launch a swath of apps for every
21491        // little component state change.
21492        final int flags = !componentNames.contains(packageName)
21493                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21494        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21495                new int[] {UserHandle.getUserId(packageUid)});
21496    }
21497
21498    @Override
21499    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21500        if (!sUserManager.exists(userId)) return;
21501        final int callingUid = Binder.getCallingUid();
21502        if (getInstantAppPackageName(callingUid) != null) {
21503            return;
21504        }
21505        final int permission = mContext.checkCallingOrSelfPermission(
21506                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21507        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21508        enforceCrossUserPermission(callingUid, userId,
21509                true /* requireFullPermission */, true /* checkShell */, "stop package");
21510        // writer
21511        synchronized (mPackages) {
21512            final PackageSetting ps = mSettings.mPackages.get(packageName);
21513            if (!filterAppAccessLPr(ps, callingUid, userId)
21514                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21515                            allowedByPermission, callingUid, userId)) {
21516                scheduleWritePackageRestrictionsLocked(userId);
21517            }
21518        }
21519    }
21520
21521    @Override
21522    public String getInstallerPackageName(String packageName) {
21523        final int callingUid = Binder.getCallingUid();
21524        if (getInstantAppPackageName(callingUid) != null) {
21525            return null;
21526        }
21527        // reader
21528        synchronized (mPackages) {
21529            final PackageSetting ps = mSettings.mPackages.get(packageName);
21530            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21531                return null;
21532            }
21533            return mSettings.getInstallerPackageNameLPr(packageName);
21534        }
21535    }
21536
21537    public boolean isOrphaned(String packageName) {
21538        // reader
21539        synchronized (mPackages) {
21540            return mSettings.isOrphaned(packageName);
21541        }
21542    }
21543
21544    @Override
21545    public int getApplicationEnabledSetting(String packageName, int userId) {
21546        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21547        int callingUid = Binder.getCallingUid();
21548        enforceCrossUserPermission(callingUid, userId,
21549                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21550        // reader
21551        synchronized (mPackages) {
21552            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21553                return COMPONENT_ENABLED_STATE_DISABLED;
21554            }
21555            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21556        }
21557    }
21558
21559    @Override
21560    public int getComponentEnabledSetting(ComponentName component, int userId) {
21561        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21562        int callingUid = Binder.getCallingUid();
21563        enforceCrossUserPermission(callingUid, userId,
21564                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21565        synchronized (mPackages) {
21566            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21567                    component, TYPE_UNKNOWN, userId)) {
21568                return COMPONENT_ENABLED_STATE_DISABLED;
21569            }
21570            return mSettings.getComponentEnabledSettingLPr(component, userId);
21571        }
21572    }
21573
21574    @Override
21575    public void enterSafeMode() {
21576        enforceSystemOrRoot("Only the system can request entering safe mode");
21577
21578        if (!mSystemReady) {
21579            mSafeMode = true;
21580        }
21581    }
21582
21583    @Override
21584    public void systemReady() {
21585        enforceSystemOrRoot("Only the system can claim the system is ready");
21586
21587        mSystemReady = true;
21588        final ContentResolver resolver = mContext.getContentResolver();
21589        ContentObserver co = new ContentObserver(mHandler) {
21590            @Override
21591            public void onChange(boolean selfChange) {
21592                mEphemeralAppsDisabled =
21593                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21594                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21595            }
21596        };
21597        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21598                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21599                false, co, UserHandle.USER_SYSTEM);
21600        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21601                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21602        co.onChange(true);
21603
21604        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21605        // disabled after already being started.
21606        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21607                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21608
21609        // Read the compatibilty setting when the system is ready.
21610        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21611                mContext.getContentResolver(),
21612                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21613        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21614        if (DEBUG_SETTINGS) {
21615            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21616        }
21617
21618        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21619
21620        synchronized (mPackages) {
21621            // Verify that all of the preferred activity components actually
21622            // exist.  It is possible for applications to be updated and at
21623            // that point remove a previously declared activity component that
21624            // had been set as a preferred activity.  We try to clean this up
21625            // the next time we encounter that preferred activity, but it is
21626            // possible for the user flow to never be able to return to that
21627            // situation so here we do a sanity check to make sure we haven't
21628            // left any junk around.
21629            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21630            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21631                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21632                removed.clear();
21633                for (PreferredActivity pa : pir.filterSet()) {
21634                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21635                        removed.add(pa);
21636                    }
21637                }
21638                if (removed.size() > 0) {
21639                    for (int r=0; r<removed.size(); r++) {
21640                        PreferredActivity pa = removed.get(r);
21641                        Slog.w(TAG, "Removing dangling preferred activity: "
21642                                + pa.mPref.mComponent);
21643                        pir.removeFilter(pa);
21644                    }
21645                    mSettings.writePackageRestrictionsLPr(
21646                            mSettings.mPreferredActivities.keyAt(i));
21647                }
21648            }
21649
21650            for (int userId : UserManagerService.getInstance().getUserIds()) {
21651                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21652                    grantPermissionsUserIds = ArrayUtils.appendInt(
21653                            grantPermissionsUserIds, userId);
21654                }
21655            }
21656        }
21657        sUserManager.systemReady();
21658
21659        // If we upgraded grant all default permissions before kicking off.
21660        for (int userId : grantPermissionsUserIds) {
21661            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21662        }
21663
21664        // If we did not grant default permissions, we preload from this the
21665        // default permission exceptions lazily to ensure we don't hit the
21666        // disk on a new user creation.
21667        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21668            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21669        }
21670
21671        // Kick off any messages waiting for system ready
21672        if (mPostSystemReadyMessages != null) {
21673            for (Message msg : mPostSystemReadyMessages) {
21674                msg.sendToTarget();
21675            }
21676            mPostSystemReadyMessages = null;
21677        }
21678
21679        // Watch for external volumes that come and go over time
21680        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21681        storage.registerListener(mStorageListener);
21682
21683        mInstallerService.systemReady();
21684        mPackageDexOptimizer.systemReady();
21685
21686        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21687                StorageManagerInternal.class);
21688        StorageManagerInternal.addExternalStoragePolicy(
21689                new StorageManagerInternal.ExternalStorageMountPolicy() {
21690            @Override
21691            public int getMountMode(int uid, String packageName) {
21692                if (Process.isIsolated(uid)) {
21693                    return Zygote.MOUNT_EXTERNAL_NONE;
21694                }
21695                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21696                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21697                }
21698                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21699                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21700                }
21701                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21702                    return Zygote.MOUNT_EXTERNAL_READ;
21703                }
21704                return Zygote.MOUNT_EXTERNAL_WRITE;
21705            }
21706
21707            @Override
21708            public boolean hasExternalStorage(int uid, String packageName) {
21709                return true;
21710            }
21711        });
21712
21713        // Now that we're mostly running, clean up stale users and apps
21714        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21715        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21716
21717        if (mPrivappPermissionsViolations != null) {
21718            Slog.wtf(TAG,"Signature|privileged permissions not in "
21719                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21720            mPrivappPermissionsViolations = null;
21721        }
21722    }
21723
21724    public void waitForAppDataPrepared() {
21725        if (mPrepareAppDataFuture == null) {
21726            return;
21727        }
21728        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21729        mPrepareAppDataFuture = null;
21730    }
21731
21732    @Override
21733    public boolean isSafeMode() {
21734        // allow instant applications
21735        return mSafeMode;
21736    }
21737
21738    @Override
21739    public boolean hasSystemUidErrors() {
21740        // allow instant applications
21741        return mHasSystemUidErrors;
21742    }
21743
21744    static String arrayToString(int[] array) {
21745        StringBuffer buf = new StringBuffer(128);
21746        buf.append('[');
21747        if (array != null) {
21748            for (int i=0; i<array.length; i++) {
21749                if (i > 0) buf.append(", ");
21750                buf.append(array[i]);
21751            }
21752        }
21753        buf.append(']');
21754        return buf.toString();
21755    }
21756
21757    static class DumpState {
21758        public static final int DUMP_LIBS = 1 << 0;
21759        public static final int DUMP_FEATURES = 1 << 1;
21760        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21761        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21762        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21763        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21764        public static final int DUMP_PERMISSIONS = 1 << 6;
21765        public static final int DUMP_PACKAGES = 1 << 7;
21766        public static final int DUMP_SHARED_USERS = 1 << 8;
21767        public static final int DUMP_MESSAGES = 1 << 9;
21768        public static final int DUMP_PROVIDERS = 1 << 10;
21769        public static final int DUMP_VERIFIERS = 1 << 11;
21770        public static final int DUMP_PREFERRED = 1 << 12;
21771        public static final int DUMP_PREFERRED_XML = 1 << 13;
21772        public static final int DUMP_KEYSETS = 1 << 14;
21773        public static final int DUMP_VERSION = 1 << 15;
21774        public static final int DUMP_INSTALLS = 1 << 16;
21775        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21776        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21777        public static final int DUMP_FROZEN = 1 << 19;
21778        public static final int DUMP_DEXOPT = 1 << 20;
21779        public static final int DUMP_COMPILER_STATS = 1 << 21;
21780        public static final int DUMP_CHANGES = 1 << 22;
21781
21782        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21783
21784        private int mTypes;
21785
21786        private int mOptions;
21787
21788        private boolean mTitlePrinted;
21789
21790        private SharedUserSetting mSharedUser;
21791
21792        public boolean isDumping(int type) {
21793            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21794                return true;
21795            }
21796
21797            return (mTypes & type) != 0;
21798        }
21799
21800        public void setDump(int type) {
21801            mTypes |= type;
21802        }
21803
21804        public boolean isOptionEnabled(int option) {
21805            return (mOptions & option) != 0;
21806        }
21807
21808        public void setOptionEnabled(int option) {
21809            mOptions |= option;
21810        }
21811
21812        public boolean onTitlePrinted() {
21813            final boolean printed = mTitlePrinted;
21814            mTitlePrinted = true;
21815            return printed;
21816        }
21817
21818        public boolean getTitlePrinted() {
21819            return mTitlePrinted;
21820        }
21821
21822        public void setTitlePrinted(boolean enabled) {
21823            mTitlePrinted = enabled;
21824        }
21825
21826        public SharedUserSetting getSharedUser() {
21827            return mSharedUser;
21828        }
21829
21830        public void setSharedUser(SharedUserSetting user) {
21831            mSharedUser = user;
21832        }
21833    }
21834
21835    @Override
21836    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21837            FileDescriptor err, String[] args, ShellCallback callback,
21838            ResultReceiver resultReceiver) {
21839        (new PackageManagerShellCommand(this)).exec(
21840                this, in, out, err, args, callback, resultReceiver);
21841    }
21842
21843    @Override
21844    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21845        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21846
21847        DumpState dumpState = new DumpState();
21848        boolean fullPreferred = false;
21849        boolean checkin = false;
21850
21851        String packageName = null;
21852        ArraySet<String> permissionNames = null;
21853
21854        int opti = 0;
21855        while (opti < args.length) {
21856            String opt = args[opti];
21857            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21858                break;
21859            }
21860            opti++;
21861
21862            if ("-a".equals(opt)) {
21863                // Right now we only know how to print all.
21864            } else if ("-h".equals(opt)) {
21865                pw.println("Package manager dump options:");
21866                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21867                pw.println("    --checkin: dump for a checkin");
21868                pw.println("    -f: print details of intent filters");
21869                pw.println("    -h: print this help");
21870                pw.println("  cmd may be one of:");
21871                pw.println("    l[ibraries]: list known shared libraries");
21872                pw.println("    f[eatures]: list device features");
21873                pw.println("    k[eysets]: print known keysets");
21874                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21875                pw.println("    perm[issions]: dump permissions");
21876                pw.println("    permission [name ...]: dump declaration and use of given permission");
21877                pw.println("    pref[erred]: print preferred package settings");
21878                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21879                pw.println("    prov[iders]: dump content providers");
21880                pw.println("    p[ackages]: dump installed packages");
21881                pw.println("    s[hared-users]: dump shared user IDs");
21882                pw.println("    m[essages]: print collected runtime messages");
21883                pw.println("    v[erifiers]: print package verifier info");
21884                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21885                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21886                pw.println("    version: print database version info");
21887                pw.println("    write: write current settings now");
21888                pw.println("    installs: details about install sessions");
21889                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21890                pw.println("    dexopt: dump dexopt state");
21891                pw.println("    compiler-stats: dump compiler statistics");
21892                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21893                pw.println("    <package.name>: info about given package");
21894                return;
21895            } else if ("--checkin".equals(opt)) {
21896                checkin = true;
21897            } else if ("-f".equals(opt)) {
21898                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21899            } else if ("--proto".equals(opt)) {
21900                dumpProto(fd);
21901                return;
21902            } else {
21903                pw.println("Unknown argument: " + opt + "; use -h for help");
21904            }
21905        }
21906
21907        // Is the caller requesting to dump a particular piece of data?
21908        if (opti < args.length) {
21909            String cmd = args[opti];
21910            opti++;
21911            // Is this a package name?
21912            if ("android".equals(cmd) || cmd.contains(".")) {
21913                packageName = cmd;
21914                // When dumping a single package, we always dump all of its
21915                // filter information since the amount of data will be reasonable.
21916                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21917            } else if ("check-permission".equals(cmd)) {
21918                if (opti >= args.length) {
21919                    pw.println("Error: check-permission missing permission argument");
21920                    return;
21921                }
21922                String perm = args[opti];
21923                opti++;
21924                if (opti >= args.length) {
21925                    pw.println("Error: check-permission missing package argument");
21926                    return;
21927                }
21928
21929                String pkg = args[opti];
21930                opti++;
21931                int user = UserHandle.getUserId(Binder.getCallingUid());
21932                if (opti < args.length) {
21933                    try {
21934                        user = Integer.parseInt(args[opti]);
21935                    } catch (NumberFormatException e) {
21936                        pw.println("Error: check-permission user argument is not a number: "
21937                                + args[opti]);
21938                        return;
21939                    }
21940                }
21941
21942                // Normalize package name to handle renamed packages and static libs
21943                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21944
21945                pw.println(checkPermission(perm, pkg, user));
21946                return;
21947            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21948                dumpState.setDump(DumpState.DUMP_LIBS);
21949            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21950                dumpState.setDump(DumpState.DUMP_FEATURES);
21951            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21952                if (opti >= args.length) {
21953                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21954                            | DumpState.DUMP_SERVICE_RESOLVERS
21955                            | DumpState.DUMP_RECEIVER_RESOLVERS
21956                            | DumpState.DUMP_CONTENT_RESOLVERS);
21957                } else {
21958                    while (opti < args.length) {
21959                        String name = args[opti];
21960                        if ("a".equals(name) || "activity".equals(name)) {
21961                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21962                        } else if ("s".equals(name) || "service".equals(name)) {
21963                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21964                        } else if ("r".equals(name) || "receiver".equals(name)) {
21965                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21966                        } else if ("c".equals(name) || "content".equals(name)) {
21967                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21968                        } else {
21969                            pw.println("Error: unknown resolver table type: " + name);
21970                            return;
21971                        }
21972                        opti++;
21973                    }
21974                }
21975            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21976                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21977            } else if ("permission".equals(cmd)) {
21978                if (opti >= args.length) {
21979                    pw.println("Error: permission requires permission name");
21980                    return;
21981                }
21982                permissionNames = new ArraySet<>();
21983                while (opti < args.length) {
21984                    permissionNames.add(args[opti]);
21985                    opti++;
21986                }
21987                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21988                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21989            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21990                dumpState.setDump(DumpState.DUMP_PREFERRED);
21991            } else if ("preferred-xml".equals(cmd)) {
21992                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21993                if (opti < args.length && "--full".equals(args[opti])) {
21994                    fullPreferred = true;
21995                    opti++;
21996                }
21997            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21998                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21999            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22000                dumpState.setDump(DumpState.DUMP_PACKAGES);
22001            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22002                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22003            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22004                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22005            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22006                dumpState.setDump(DumpState.DUMP_MESSAGES);
22007            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22008                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22009            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22010                    || "intent-filter-verifiers".equals(cmd)) {
22011                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22012            } else if ("version".equals(cmd)) {
22013                dumpState.setDump(DumpState.DUMP_VERSION);
22014            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22015                dumpState.setDump(DumpState.DUMP_KEYSETS);
22016            } else if ("installs".equals(cmd)) {
22017                dumpState.setDump(DumpState.DUMP_INSTALLS);
22018            } else if ("frozen".equals(cmd)) {
22019                dumpState.setDump(DumpState.DUMP_FROZEN);
22020            } else if ("dexopt".equals(cmd)) {
22021                dumpState.setDump(DumpState.DUMP_DEXOPT);
22022            } else if ("compiler-stats".equals(cmd)) {
22023                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22024            } else if ("changes".equals(cmd)) {
22025                dumpState.setDump(DumpState.DUMP_CHANGES);
22026            } else if ("write".equals(cmd)) {
22027                synchronized (mPackages) {
22028                    mSettings.writeLPr();
22029                    pw.println("Settings written.");
22030                    return;
22031                }
22032            }
22033        }
22034
22035        if (checkin) {
22036            pw.println("vers,1");
22037        }
22038
22039        // reader
22040        synchronized (mPackages) {
22041            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22042                if (!checkin) {
22043                    if (dumpState.onTitlePrinted())
22044                        pw.println();
22045                    pw.println("Database versions:");
22046                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22047                }
22048            }
22049
22050            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22051                if (!checkin) {
22052                    if (dumpState.onTitlePrinted())
22053                        pw.println();
22054                    pw.println("Verifiers:");
22055                    pw.print("  Required: ");
22056                    pw.print(mRequiredVerifierPackage);
22057                    pw.print(" (uid=");
22058                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22059                            UserHandle.USER_SYSTEM));
22060                    pw.println(")");
22061                } else if (mRequiredVerifierPackage != null) {
22062                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22063                    pw.print(",");
22064                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22065                            UserHandle.USER_SYSTEM));
22066                }
22067            }
22068
22069            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22070                    packageName == null) {
22071                if (mIntentFilterVerifierComponent != null) {
22072                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22073                    if (!checkin) {
22074                        if (dumpState.onTitlePrinted())
22075                            pw.println();
22076                        pw.println("Intent Filter Verifier:");
22077                        pw.print("  Using: ");
22078                        pw.print(verifierPackageName);
22079                        pw.print(" (uid=");
22080                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22081                                UserHandle.USER_SYSTEM));
22082                        pw.println(")");
22083                    } else if (verifierPackageName != null) {
22084                        pw.print("ifv,"); pw.print(verifierPackageName);
22085                        pw.print(",");
22086                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22087                                UserHandle.USER_SYSTEM));
22088                    }
22089                } else {
22090                    pw.println();
22091                    pw.println("No Intent Filter Verifier available!");
22092                }
22093            }
22094
22095            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22096                boolean printedHeader = false;
22097                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22098                while (it.hasNext()) {
22099                    String libName = it.next();
22100                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22101                    if (versionedLib == null) {
22102                        continue;
22103                    }
22104                    final int versionCount = versionedLib.size();
22105                    for (int i = 0; i < versionCount; i++) {
22106                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22107                        if (!checkin) {
22108                            if (!printedHeader) {
22109                                if (dumpState.onTitlePrinted())
22110                                    pw.println();
22111                                pw.println("Libraries:");
22112                                printedHeader = true;
22113                            }
22114                            pw.print("  ");
22115                        } else {
22116                            pw.print("lib,");
22117                        }
22118                        pw.print(libEntry.info.getName());
22119                        if (libEntry.info.isStatic()) {
22120                            pw.print(" version=" + libEntry.info.getVersion());
22121                        }
22122                        if (!checkin) {
22123                            pw.print(" -> ");
22124                        }
22125                        if (libEntry.path != null) {
22126                            pw.print(" (jar) ");
22127                            pw.print(libEntry.path);
22128                        } else {
22129                            pw.print(" (apk) ");
22130                            pw.print(libEntry.apk);
22131                        }
22132                        pw.println();
22133                    }
22134                }
22135            }
22136
22137            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22138                if (dumpState.onTitlePrinted())
22139                    pw.println();
22140                if (!checkin) {
22141                    pw.println("Features:");
22142                }
22143
22144                synchronized (mAvailableFeatures) {
22145                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22146                        if (checkin) {
22147                            pw.print("feat,");
22148                            pw.print(feat.name);
22149                            pw.print(",");
22150                            pw.println(feat.version);
22151                        } else {
22152                            pw.print("  ");
22153                            pw.print(feat.name);
22154                            if (feat.version > 0) {
22155                                pw.print(" version=");
22156                                pw.print(feat.version);
22157                            }
22158                            pw.println();
22159                        }
22160                    }
22161                }
22162            }
22163
22164            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22165                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22166                        : "Activity Resolver Table:", "  ", packageName,
22167                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22168                    dumpState.setTitlePrinted(true);
22169                }
22170            }
22171            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22172                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22173                        : "Receiver Resolver Table:", "  ", packageName,
22174                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22175                    dumpState.setTitlePrinted(true);
22176                }
22177            }
22178            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22179                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22180                        : "Service Resolver Table:", "  ", packageName,
22181                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22182                    dumpState.setTitlePrinted(true);
22183                }
22184            }
22185            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22186                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22187                        : "Provider Resolver Table:", "  ", packageName,
22188                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22189                    dumpState.setTitlePrinted(true);
22190                }
22191            }
22192
22193            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22194                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22195                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22196                    int user = mSettings.mPreferredActivities.keyAt(i);
22197                    if (pir.dump(pw,
22198                            dumpState.getTitlePrinted()
22199                                ? "\nPreferred Activities User " + user + ":"
22200                                : "Preferred Activities User " + user + ":", "  ",
22201                            packageName, true, false)) {
22202                        dumpState.setTitlePrinted(true);
22203                    }
22204                }
22205            }
22206
22207            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22208                pw.flush();
22209                FileOutputStream fout = new FileOutputStream(fd);
22210                BufferedOutputStream str = new BufferedOutputStream(fout);
22211                XmlSerializer serializer = new FastXmlSerializer();
22212                try {
22213                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22214                    serializer.startDocument(null, true);
22215                    serializer.setFeature(
22216                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22217                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22218                    serializer.endDocument();
22219                    serializer.flush();
22220                } catch (IllegalArgumentException e) {
22221                    pw.println("Failed writing: " + e);
22222                } catch (IllegalStateException e) {
22223                    pw.println("Failed writing: " + e);
22224                } catch (IOException e) {
22225                    pw.println("Failed writing: " + e);
22226                }
22227            }
22228
22229            if (!checkin
22230                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22231                    && packageName == null) {
22232                pw.println();
22233                int count = mSettings.mPackages.size();
22234                if (count == 0) {
22235                    pw.println("No applications!");
22236                    pw.println();
22237                } else {
22238                    final String prefix = "  ";
22239                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22240                    if (allPackageSettings.size() == 0) {
22241                        pw.println("No domain preferred apps!");
22242                        pw.println();
22243                    } else {
22244                        pw.println("App verification status:");
22245                        pw.println();
22246                        count = 0;
22247                        for (PackageSetting ps : allPackageSettings) {
22248                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22249                            if (ivi == null || ivi.getPackageName() == null) continue;
22250                            pw.println(prefix + "Package: " + ivi.getPackageName());
22251                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22252                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22253                            pw.println();
22254                            count++;
22255                        }
22256                        if (count == 0) {
22257                            pw.println(prefix + "No app verification established.");
22258                            pw.println();
22259                        }
22260                        for (int userId : sUserManager.getUserIds()) {
22261                            pw.println("App linkages for user " + userId + ":");
22262                            pw.println();
22263                            count = 0;
22264                            for (PackageSetting ps : allPackageSettings) {
22265                                final long status = ps.getDomainVerificationStatusForUser(userId);
22266                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22267                                        && !DEBUG_DOMAIN_VERIFICATION) {
22268                                    continue;
22269                                }
22270                                pw.println(prefix + "Package: " + ps.name);
22271                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22272                                String statusStr = IntentFilterVerificationInfo.
22273                                        getStatusStringFromValue(status);
22274                                pw.println(prefix + "Status:  " + statusStr);
22275                                pw.println();
22276                                count++;
22277                            }
22278                            if (count == 0) {
22279                                pw.println(prefix + "No configured app linkages.");
22280                                pw.println();
22281                            }
22282                        }
22283                    }
22284                }
22285            }
22286
22287            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22288                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22289                if (packageName == null && permissionNames == null) {
22290                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22291                        if (iperm == 0) {
22292                            if (dumpState.onTitlePrinted())
22293                                pw.println();
22294                            pw.println("AppOp Permissions:");
22295                        }
22296                        pw.print("  AppOp Permission ");
22297                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22298                        pw.println(":");
22299                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22300                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22301                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22302                        }
22303                    }
22304                }
22305            }
22306
22307            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22308                boolean printedSomething = false;
22309                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22310                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22311                        continue;
22312                    }
22313                    if (!printedSomething) {
22314                        if (dumpState.onTitlePrinted())
22315                            pw.println();
22316                        pw.println("Registered ContentProviders:");
22317                        printedSomething = true;
22318                    }
22319                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22320                    pw.print("    "); pw.println(p.toString());
22321                }
22322                printedSomething = false;
22323                for (Map.Entry<String, PackageParser.Provider> entry :
22324                        mProvidersByAuthority.entrySet()) {
22325                    PackageParser.Provider p = entry.getValue();
22326                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22327                        continue;
22328                    }
22329                    if (!printedSomething) {
22330                        if (dumpState.onTitlePrinted())
22331                            pw.println();
22332                        pw.println("ContentProvider Authorities:");
22333                        printedSomething = true;
22334                    }
22335                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22336                    pw.print("    "); pw.println(p.toString());
22337                    if (p.info != null && p.info.applicationInfo != null) {
22338                        final String appInfo = p.info.applicationInfo.toString();
22339                        pw.print("      applicationInfo="); pw.println(appInfo);
22340                    }
22341                }
22342            }
22343
22344            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22345                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22346            }
22347
22348            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22349                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22350            }
22351
22352            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22353                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22354            }
22355
22356            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22357                if (dumpState.onTitlePrinted()) pw.println();
22358                pw.println("Package Changes:");
22359                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22360                final int K = mChangedPackages.size();
22361                for (int i = 0; i < K; i++) {
22362                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22363                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22364                    final int N = changes.size();
22365                    if (N == 0) {
22366                        pw.print("    "); pw.println("No packages changed");
22367                    } else {
22368                        for (int j = 0; j < N; j++) {
22369                            final String pkgName = changes.valueAt(j);
22370                            final int sequenceNumber = changes.keyAt(j);
22371                            pw.print("    ");
22372                            pw.print("seq=");
22373                            pw.print(sequenceNumber);
22374                            pw.print(", package=");
22375                            pw.println(pkgName);
22376                        }
22377                    }
22378                }
22379            }
22380
22381            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22382                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22383            }
22384
22385            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22386                // XXX should handle packageName != null by dumping only install data that
22387                // the given package is involved with.
22388                if (dumpState.onTitlePrinted()) pw.println();
22389
22390                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22391                ipw.println();
22392                ipw.println("Frozen packages:");
22393                ipw.increaseIndent();
22394                if (mFrozenPackages.size() == 0) {
22395                    ipw.println("(none)");
22396                } else {
22397                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22398                        ipw.println(mFrozenPackages.valueAt(i));
22399                    }
22400                }
22401                ipw.decreaseIndent();
22402            }
22403
22404            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22405                if (dumpState.onTitlePrinted()) pw.println();
22406                dumpDexoptStateLPr(pw, packageName);
22407            }
22408
22409            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22410                if (dumpState.onTitlePrinted()) pw.println();
22411                dumpCompilerStatsLPr(pw, packageName);
22412            }
22413
22414            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22415                if (dumpState.onTitlePrinted()) pw.println();
22416                mSettings.dumpReadMessagesLPr(pw, dumpState);
22417
22418                pw.println();
22419                pw.println("Package warning messages:");
22420                BufferedReader in = null;
22421                String line = null;
22422                try {
22423                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22424                    while ((line = in.readLine()) != null) {
22425                        if (line.contains("ignored: updated version")) continue;
22426                        pw.println(line);
22427                    }
22428                } catch (IOException ignored) {
22429                } finally {
22430                    IoUtils.closeQuietly(in);
22431                }
22432            }
22433
22434            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22435                BufferedReader in = null;
22436                String line = null;
22437                try {
22438                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22439                    while ((line = in.readLine()) != null) {
22440                        if (line.contains("ignored: updated version")) continue;
22441                        pw.print("msg,");
22442                        pw.println(line);
22443                    }
22444                } catch (IOException ignored) {
22445                } finally {
22446                    IoUtils.closeQuietly(in);
22447                }
22448            }
22449        }
22450
22451        // PackageInstaller should be called outside of mPackages lock
22452        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22453            // XXX should handle packageName != null by dumping only install data that
22454            // the given package is involved with.
22455            if (dumpState.onTitlePrinted()) pw.println();
22456            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22457        }
22458    }
22459
22460    private void dumpProto(FileDescriptor fd) {
22461        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22462
22463        synchronized (mPackages) {
22464            final long requiredVerifierPackageToken =
22465                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22466            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22467            proto.write(
22468                    PackageServiceDumpProto.PackageShortProto.UID,
22469                    getPackageUid(
22470                            mRequiredVerifierPackage,
22471                            MATCH_DEBUG_TRIAGED_MISSING,
22472                            UserHandle.USER_SYSTEM));
22473            proto.end(requiredVerifierPackageToken);
22474
22475            if (mIntentFilterVerifierComponent != null) {
22476                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22477                final long verifierPackageToken =
22478                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22479                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22480                proto.write(
22481                        PackageServiceDumpProto.PackageShortProto.UID,
22482                        getPackageUid(
22483                                verifierPackageName,
22484                                MATCH_DEBUG_TRIAGED_MISSING,
22485                                UserHandle.USER_SYSTEM));
22486                proto.end(verifierPackageToken);
22487            }
22488
22489            dumpSharedLibrariesProto(proto);
22490            dumpFeaturesProto(proto);
22491            mSettings.dumpPackagesProto(proto);
22492            mSettings.dumpSharedUsersProto(proto);
22493            dumpMessagesProto(proto);
22494        }
22495        proto.flush();
22496    }
22497
22498    private void dumpMessagesProto(ProtoOutputStream proto) {
22499        BufferedReader in = null;
22500        String line = null;
22501        try {
22502            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22503            while ((line = in.readLine()) != null) {
22504                if (line.contains("ignored: updated version")) continue;
22505                proto.write(PackageServiceDumpProto.MESSAGES, line);
22506            }
22507        } catch (IOException ignored) {
22508        } finally {
22509            IoUtils.closeQuietly(in);
22510        }
22511    }
22512
22513    private void dumpFeaturesProto(ProtoOutputStream proto) {
22514        synchronized (mAvailableFeatures) {
22515            final int count = mAvailableFeatures.size();
22516            for (int i = 0; i < count; i++) {
22517                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22518                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22519                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22520                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22521                proto.end(featureToken);
22522            }
22523        }
22524    }
22525
22526    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22527        final int count = mSharedLibraries.size();
22528        for (int i = 0; i < count; i++) {
22529            final String libName = mSharedLibraries.keyAt(i);
22530            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22531            if (versionedLib == null) {
22532                continue;
22533            }
22534            final int versionCount = versionedLib.size();
22535            for (int j = 0; j < versionCount; j++) {
22536                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22537                final long sharedLibraryToken =
22538                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22539                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22540                final boolean isJar = (libEntry.path != null);
22541                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22542                if (isJar) {
22543                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22544                } else {
22545                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22546                }
22547                proto.end(sharedLibraryToken);
22548            }
22549        }
22550    }
22551
22552    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22553        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22554        ipw.println();
22555        ipw.println("Dexopt state:");
22556        ipw.increaseIndent();
22557        Collection<PackageParser.Package> packages = null;
22558        if (packageName != null) {
22559            PackageParser.Package targetPackage = mPackages.get(packageName);
22560            if (targetPackage != null) {
22561                packages = Collections.singletonList(targetPackage);
22562            } else {
22563                ipw.println("Unable to find package: " + packageName);
22564                return;
22565            }
22566        } else {
22567            packages = mPackages.values();
22568        }
22569
22570        for (PackageParser.Package pkg : packages) {
22571            ipw.println("[" + pkg.packageName + "]");
22572            ipw.increaseIndent();
22573            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
22574                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
22575            ipw.decreaseIndent();
22576        }
22577    }
22578
22579    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22580        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22581        ipw.println();
22582        ipw.println("Compiler stats:");
22583        ipw.increaseIndent();
22584        Collection<PackageParser.Package> packages = null;
22585        if (packageName != null) {
22586            PackageParser.Package targetPackage = mPackages.get(packageName);
22587            if (targetPackage != null) {
22588                packages = Collections.singletonList(targetPackage);
22589            } else {
22590                ipw.println("Unable to find package: " + packageName);
22591                return;
22592            }
22593        } else {
22594            packages = mPackages.values();
22595        }
22596
22597        for (PackageParser.Package pkg : packages) {
22598            ipw.println("[" + pkg.packageName + "]");
22599            ipw.increaseIndent();
22600
22601            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22602            if (stats == null) {
22603                ipw.println("(No recorded stats)");
22604            } else {
22605                stats.dump(ipw);
22606            }
22607            ipw.decreaseIndent();
22608        }
22609    }
22610
22611    private String dumpDomainString(String packageName) {
22612        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22613                .getList();
22614        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22615
22616        ArraySet<String> result = new ArraySet<>();
22617        if (iviList.size() > 0) {
22618            for (IntentFilterVerificationInfo ivi : iviList) {
22619                for (String host : ivi.getDomains()) {
22620                    result.add(host);
22621                }
22622            }
22623        }
22624        if (filters != null && filters.size() > 0) {
22625            for (IntentFilter filter : filters) {
22626                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22627                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22628                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22629                    result.addAll(filter.getHostsList());
22630                }
22631            }
22632        }
22633
22634        StringBuilder sb = new StringBuilder(result.size() * 16);
22635        for (String domain : result) {
22636            if (sb.length() > 0) sb.append(" ");
22637            sb.append(domain);
22638        }
22639        return sb.toString();
22640    }
22641
22642    // ------- apps on sdcard specific code -------
22643    static final boolean DEBUG_SD_INSTALL = false;
22644
22645    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22646
22647    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22648
22649    private boolean mMediaMounted = false;
22650
22651    static String getEncryptKey() {
22652        try {
22653            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22654                    SD_ENCRYPTION_KEYSTORE_NAME);
22655            if (sdEncKey == null) {
22656                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22657                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22658                if (sdEncKey == null) {
22659                    Slog.e(TAG, "Failed to create encryption keys");
22660                    return null;
22661                }
22662            }
22663            return sdEncKey;
22664        } catch (NoSuchAlgorithmException nsae) {
22665            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22666            return null;
22667        } catch (IOException ioe) {
22668            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22669            return null;
22670        }
22671    }
22672
22673    /*
22674     * Update media status on PackageManager.
22675     */
22676    @Override
22677    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22678        enforceSystemOrRoot("Media status can only be updated by the system");
22679        // reader; this apparently protects mMediaMounted, but should probably
22680        // be a different lock in that case.
22681        synchronized (mPackages) {
22682            Log.i(TAG, "Updating external media status from "
22683                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22684                    + (mediaStatus ? "mounted" : "unmounted"));
22685            if (DEBUG_SD_INSTALL)
22686                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22687                        + ", mMediaMounted=" + mMediaMounted);
22688            if (mediaStatus == mMediaMounted) {
22689                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22690                        : 0, -1);
22691                mHandler.sendMessage(msg);
22692                return;
22693            }
22694            mMediaMounted = mediaStatus;
22695        }
22696        // Queue up an async operation since the package installation may take a
22697        // little while.
22698        mHandler.post(new Runnable() {
22699            public void run() {
22700                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22701            }
22702        });
22703    }
22704
22705    /**
22706     * Called by StorageManagerService when the initial ASECs to scan are available.
22707     * Should block until all the ASEC containers are finished being scanned.
22708     */
22709    public void scanAvailableAsecs() {
22710        updateExternalMediaStatusInner(true, false, false);
22711    }
22712
22713    /*
22714     * Collect information of applications on external media, map them against
22715     * existing containers and update information based on current mount status.
22716     * Please note that we always have to report status if reportStatus has been
22717     * set to true especially when unloading packages.
22718     */
22719    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22720            boolean externalStorage) {
22721        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22722        int[] uidArr = EmptyArray.INT;
22723
22724        final String[] list = PackageHelper.getSecureContainerList();
22725        if (ArrayUtils.isEmpty(list)) {
22726            Log.i(TAG, "No secure containers found");
22727        } else {
22728            // Process list of secure containers and categorize them
22729            // as active or stale based on their package internal state.
22730
22731            // reader
22732            synchronized (mPackages) {
22733                for (String cid : list) {
22734                    // Leave stages untouched for now; installer service owns them
22735                    if (PackageInstallerService.isStageName(cid)) continue;
22736
22737                    if (DEBUG_SD_INSTALL)
22738                        Log.i(TAG, "Processing container " + cid);
22739                    String pkgName = getAsecPackageName(cid);
22740                    if (pkgName == null) {
22741                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22742                        continue;
22743                    }
22744                    if (DEBUG_SD_INSTALL)
22745                        Log.i(TAG, "Looking for pkg : " + pkgName);
22746
22747                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22748                    if (ps == null) {
22749                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22750                        continue;
22751                    }
22752
22753                    /*
22754                     * Skip packages that are not external if we're unmounting
22755                     * external storage.
22756                     */
22757                    if (externalStorage && !isMounted && !isExternal(ps)) {
22758                        continue;
22759                    }
22760
22761                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22762                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22763                    // The package status is changed only if the code path
22764                    // matches between settings and the container id.
22765                    if (ps.codePathString != null
22766                            && ps.codePathString.startsWith(args.getCodePath())) {
22767                        if (DEBUG_SD_INSTALL) {
22768                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22769                                    + " at code path: " + ps.codePathString);
22770                        }
22771
22772                        // We do have a valid package installed on sdcard
22773                        processCids.put(args, ps.codePathString);
22774                        final int uid = ps.appId;
22775                        if (uid != -1) {
22776                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22777                        }
22778                    } else {
22779                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22780                                + ps.codePathString);
22781                    }
22782                }
22783            }
22784
22785            Arrays.sort(uidArr);
22786        }
22787
22788        // Process packages with valid entries.
22789        if (isMounted) {
22790            if (DEBUG_SD_INSTALL)
22791                Log.i(TAG, "Loading packages");
22792            loadMediaPackages(processCids, uidArr, externalStorage);
22793            startCleaningPackages();
22794            mInstallerService.onSecureContainersAvailable();
22795        } else {
22796            if (DEBUG_SD_INSTALL)
22797                Log.i(TAG, "Unloading packages");
22798            unloadMediaPackages(processCids, uidArr, reportStatus);
22799        }
22800    }
22801
22802    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22803            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22804        final int size = infos.size();
22805        final String[] packageNames = new String[size];
22806        final int[] packageUids = new int[size];
22807        for (int i = 0; i < size; i++) {
22808            final ApplicationInfo info = infos.get(i);
22809            packageNames[i] = info.packageName;
22810            packageUids[i] = info.uid;
22811        }
22812        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22813                finishedReceiver);
22814    }
22815
22816    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22817            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22818        sendResourcesChangedBroadcast(mediaStatus, replacing,
22819                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22820    }
22821
22822    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22823            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22824        int size = pkgList.length;
22825        if (size > 0) {
22826            // Send broadcasts here
22827            Bundle extras = new Bundle();
22828            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22829            if (uidArr != null) {
22830                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22831            }
22832            if (replacing) {
22833                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22834            }
22835            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22836                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22837            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22838        }
22839    }
22840
22841   /*
22842     * Look at potentially valid container ids from processCids If package
22843     * information doesn't match the one on record or package scanning fails,
22844     * the cid is added to list of removeCids. We currently don't delete stale
22845     * containers.
22846     */
22847    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22848            boolean externalStorage) {
22849        ArrayList<String> pkgList = new ArrayList<String>();
22850        Set<AsecInstallArgs> keys = processCids.keySet();
22851
22852        for (AsecInstallArgs args : keys) {
22853            String codePath = processCids.get(args);
22854            if (DEBUG_SD_INSTALL)
22855                Log.i(TAG, "Loading container : " + args.cid);
22856            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22857            try {
22858                // Make sure there are no container errors first.
22859                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22860                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22861                            + " when installing from sdcard");
22862                    continue;
22863                }
22864                // Check code path here.
22865                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22866                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22867                            + " does not match one in settings " + codePath);
22868                    continue;
22869                }
22870                // Parse package
22871                int parseFlags = mDefParseFlags;
22872                if (args.isExternalAsec()) {
22873                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22874                }
22875                if (args.isFwdLocked()) {
22876                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22877                }
22878
22879                synchronized (mInstallLock) {
22880                    PackageParser.Package pkg = null;
22881                    try {
22882                        // Sadly we don't know the package name yet to freeze it
22883                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22884                                SCAN_IGNORE_FROZEN, 0, null);
22885                    } catch (PackageManagerException e) {
22886                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22887                    }
22888                    // Scan the package
22889                    if (pkg != null) {
22890                        /*
22891                         * TODO why is the lock being held? doPostInstall is
22892                         * called in other places without the lock. This needs
22893                         * to be straightened out.
22894                         */
22895                        // writer
22896                        synchronized (mPackages) {
22897                            retCode = PackageManager.INSTALL_SUCCEEDED;
22898                            pkgList.add(pkg.packageName);
22899                            // Post process args
22900                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22901                                    pkg.applicationInfo.uid);
22902                        }
22903                    } else {
22904                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22905                    }
22906                }
22907
22908            } finally {
22909                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22910                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22911                }
22912            }
22913        }
22914        // writer
22915        synchronized (mPackages) {
22916            // If the platform SDK has changed since the last time we booted,
22917            // we need to re-grant app permission to catch any new ones that
22918            // appear. This is really a hack, and means that apps can in some
22919            // cases get permissions that the user didn't initially explicitly
22920            // allow... it would be nice to have some better way to handle
22921            // this situation.
22922            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22923                    : mSettings.getInternalVersion();
22924            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22925                    : StorageManager.UUID_PRIVATE_INTERNAL;
22926
22927            int updateFlags = UPDATE_PERMISSIONS_ALL;
22928            if (ver.sdkVersion != mSdkVersion) {
22929                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22930                        + mSdkVersion + "; regranting permissions for external");
22931                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22932            }
22933            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22934
22935            // Yay, everything is now upgraded
22936            ver.forceCurrent();
22937
22938            // can downgrade to reader
22939            // Persist settings
22940            mSettings.writeLPr();
22941        }
22942        // Send a broadcast to let everyone know we are done processing
22943        if (pkgList.size() > 0) {
22944            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22945        }
22946    }
22947
22948   /*
22949     * Utility method to unload a list of specified containers
22950     */
22951    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22952        // Just unmount all valid containers.
22953        for (AsecInstallArgs arg : cidArgs) {
22954            synchronized (mInstallLock) {
22955                arg.doPostDeleteLI(false);
22956           }
22957       }
22958   }
22959
22960    /*
22961     * Unload packages mounted on external media. This involves deleting package
22962     * data from internal structures, sending broadcasts about disabled packages,
22963     * gc'ing to free up references, unmounting all secure containers
22964     * corresponding to packages on external media, and posting a
22965     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22966     * that we always have to post this message if status has been requested no
22967     * matter what.
22968     */
22969    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22970            final boolean reportStatus) {
22971        if (DEBUG_SD_INSTALL)
22972            Log.i(TAG, "unloading media packages");
22973        ArrayList<String> pkgList = new ArrayList<String>();
22974        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22975        final Set<AsecInstallArgs> keys = processCids.keySet();
22976        for (AsecInstallArgs args : keys) {
22977            String pkgName = args.getPackageName();
22978            if (DEBUG_SD_INSTALL)
22979                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22980            // Delete package internally
22981            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22982            synchronized (mInstallLock) {
22983                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22984                final boolean res;
22985                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22986                        "unloadMediaPackages")) {
22987                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22988                            null);
22989                }
22990                if (res) {
22991                    pkgList.add(pkgName);
22992                } else {
22993                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22994                    failedList.add(args);
22995                }
22996            }
22997        }
22998
22999        // reader
23000        synchronized (mPackages) {
23001            // We didn't update the settings after removing each package;
23002            // write them now for all packages.
23003            mSettings.writeLPr();
23004        }
23005
23006        // We have to absolutely send UPDATED_MEDIA_STATUS only
23007        // after confirming that all the receivers processed the ordered
23008        // broadcast when packages get disabled, force a gc to clean things up.
23009        // and unload all the containers.
23010        if (pkgList.size() > 0) {
23011            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23012                    new IIntentReceiver.Stub() {
23013                public void performReceive(Intent intent, int resultCode, String data,
23014                        Bundle extras, boolean ordered, boolean sticky,
23015                        int sendingUser) throws RemoteException {
23016                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23017                            reportStatus ? 1 : 0, 1, keys);
23018                    mHandler.sendMessage(msg);
23019                }
23020            });
23021        } else {
23022            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23023                    keys);
23024            mHandler.sendMessage(msg);
23025        }
23026    }
23027
23028    private void loadPrivatePackages(final VolumeInfo vol) {
23029        mHandler.post(new Runnable() {
23030            @Override
23031            public void run() {
23032                loadPrivatePackagesInner(vol);
23033            }
23034        });
23035    }
23036
23037    private void loadPrivatePackagesInner(VolumeInfo vol) {
23038        final String volumeUuid = vol.fsUuid;
23039        if (TextUtils.isEmpty(volumeUuid)) {
23040            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23041            return;
23042        }
23043
23044        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23045        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23046        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23047
23048        final VersionInfo ver;
23049        final List<PackageSetting> packages;
23050        synchronized (mPackages) {
23051            ver = mSettings.findOrCreateVersion(volumeUuid);
23052            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23053        }
23054
23055        for (PackageSetting ps : packages) {
23056            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23057            synchronized (mInstallLock) {
23058                final PackageParser.Package pkg;
23059                try {
23060                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23061                    loaded.add(pkg.applicationInfo);
23062
23063                } catch (PackageManagerException e) {
23064                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23065                }
23066
23067                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23068                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23069                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23070                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23071                }
23072            }
23073        }
23074
23075        // Reconcile app data for all started/unlocked users
23076        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23077        final UserManager um = mContext.getSystemService(UserManager.class);
23078        UserManagerInternal umInternal = getUserManagerInternal();
23079        for (UserInfo user : um.getUsers()) {
23080            final int flags;
23081            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23082                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23083            } else if (umInternal.isUserRunning(user.id)) {
23084                flags = StorageManager.FLAG_STORAGE_DE;
23085            } else {
23086                continue;
23087            }
23088
23089            try {
23090                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23091                synchronized (mInstallLock) {
23092                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23093                }
23094            } catch (IllegalStateException e) {
23095                // Device was probably ejected, and we'll process that event momentarily
23096                Slog.w(TAG, "Failed to prepare storage: " + e);
23097            }
23098        }
23099
23100        synchronized (mPackages) {
23101            int updateFlags = UPDATE_PERMISSIONS_ALL;
23102            if (ver.sdkVersion != mSdkVersion) {
23103                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23104                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23105                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23106            }
23107            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23108
23109            // Yay, everything is now upgraded
23110            ver.forceCurrent();
23111
23112            mSettings.writeLPr();
23113        }
23114
23115        for (PackageFreezer freezer : freezers) {
23116            freezer.close();
23117        }
23118
23119        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23120        sendResourcesChangedBroadcast(true, false, loaded, null);
23121    }
23122
23123    private void unloadPrivatePackages(final VolumeInfo vol) {
23124        mHandler.post(new Runnable() {
23125            @Override
23126            public void run() {
23127                unloadPrivatePackagesInner(vol);
23128            }
23129        });
23130    }
23131
23132    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23133        final String volumeUuid = vol.fsUuid;
23134        if (TextUtils.isEmpty(volumeUuid)) {
23135            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23136            return;
23137        }
23138
23139        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23140        synchronized (mInstallLock) {
23141        synchronized (mPackages) {
23142            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23143            for (PackageSetting ps : packages) {
23144                if (ps.pkg == null) continue;
23145
23146                final ApplicationInfo info = ps.pkg.applicationInfo;
23147                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23148                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23149
23150                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23151                        "unloadPrivatePackagesInner")) {
23152                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23153                            false, null)) {
23154                        unloaded.add(info);
23155                    } else {
23156                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23157                    }
23158                }
23159
23160                // Try very hard to release any references to this package
23161                // so we don't risk the system server being killed due to
23162                // open FDs
23163                AttributeCache.instance().removePackage(ps.name);
23164            }
23165
23166            mSettings.writeLPr();
23167        }
23168        }
23169
23170        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23171        sendResourcesChangedBroadcast(false, false, unloaded, null);
23172
23173        // Try very hard to release any references to this path so we don't risk
23174        // the system server being killed due to open FDs
23175        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23176
23177        for (int i = 0; i < 3; i++) {
23178            System.gc();
23179            System.runFinalization();
23180        }
23181    }
23182
23183    private void assertPackageKnown(String volumeUuid, String packageName)
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            }
23197        }
23198    }
23199
23200    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23201            throws PackageManagerException {
23202        synchronized (mPackages) {
23203            // Normalize package name to handle renamed packages
23204            packageName = normalizePackageNameLPr(packageName);
23205
23206            final PackageSetting ps = mSettings.mPackages.get(packageName);
23207            if (ps == null) {
23208                throw new PackageManagerException("Package " + packageName + " is unknown");
23209            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23210                throw new PackageManagerException(
23211                        "Package " + packageName + " found on unknown volume " + volumeUuid
23212                                + "; expected volume " + ps.volumeUuid);
23213            } else if (!ps.getInstalled(userId)) {
23214                throw new PackageManagerException(
23215                        "Package " + packageName + " not installed for user " + userId);
23216            }
23217        }
23218    }
23219
23220    private List<String> collectAbsoluteCodePaths() {
23221        synchronized (mPackages) {
23222            List<String> codePaths = new ArrayList<>();
23223            final int packageCount = mSettings.mPackages.size();
23224            for (int i = 0; i < packageCount; i++) {
23225                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23226                codePaths.add(ps.codePath.getAbsolutePath());
23227            }
23228            return codePaths;
23229        }
23230    }
23231
23232    /**
23233     * Examine all apps present on given mounted volume, and destroy apps that
23234     * aren't expected, either due to uninstallation or reinstallation on
23235     * another volume.
23236     */
23237    private void reconcileApps(String volumeUuid) {
23238        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23239        List<File> filesToDelete = null;
23240
23241        final File[] files = FileUtils.listFilesOrEmpty(
23242                Environment.getDataAppDirectory(volumeUuid));
23243        for (File file : files) {
23244            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23245                    && !PackageInstallerService.isStageName(file.getName());
23246            if (!isPackage) {
23247                // Ignore entries which are not packages
23248                continue;
23249            }
23250
23251            String absolutePath = file.getAbsolutePath();
23252
23253            boolean pathValid = false;
23254            final int absoluteCodePathCount = absoluteCodePaths.size();
23255            for (int i = 0; i < absoluteCodePathCount; i++) {
23256                String absoluteCodePath = absoluteCodePaths.get(i);
23257                if (absolutePath.startsWith(absoluteCodePath)) {
23258                    pathValid = true;
23259                    break;
23260                }
23261            }
23262
23263            if (!pathValid) {
23264                if (filesToDelete == null) {
23265                    filesToDelete = new ArrayList<>();
23266                }
23267                filesToDelete.add(file);
23268            }
23269        }
23270
23271        if (filesToDelete != null) {
23272            final int fileToDeleteCount = filesToDelete.size();
23273            for (int i = 0; i < fileToDeleteCount; i++) {
23274                File fileToDelete = filesToDelete.get(i);
23275                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23276                synchronized (mInstallLock) {
23277                    removeCodePathLI(fileToDelete);
23278                }
23279            }
23280        }
23281    }
23282
23283    /**
23284     * Reconcile all app data for the given user.
23285     * <p>
23286     * Verifies that directories exist and that ownership and labeling is
23287     * correct for all installed apps on all mounted volumes.
23288     */
23289    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23290        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23291        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23292            final String volumeUuid = vol.getFsUuid();
23293            synchronized (mInstallLock) {
23294                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23295            }
23296        }
23297    }
23298
23299    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23300            boolean migrateAppData) {
23301        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23302    }
23303
23304    /**
23305     * Reconcile all app data on given mounted volume.
23306     * <p>
23307     * Destroys app data that isn't expected, either due to uninstallation or
23308     * reinstallation on another volume.
23309     * <p>
23310     * Verifies that directories exist and that ownership and labeling is
23311     * correct for all installed apps.
23312     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23313     */
23314    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23315            boolean migrateAppData, boolean onlyCoreApps) {
23316        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23317                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23318        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23319
23320        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23321        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23322
23323        // First look for stale data that doesn't belong, and check if things
23324        // have changed since we did our last restorecon
23325        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23326            if (StorageManager.isFileEncryptedNativeOrEmulated()
23327                    && !StorageManager.isUserKeyUnlocked(userId)) {
23328                throw new RuntimeException(
23329                        "Yikes, someone asked us to reconcile CE storage while " + userId
23330                                + " was still locked; this would have caused massive data loss!");
23331            }
23332
23333            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
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_CE, 0);
23343                    } catch (InstallerException e2) {
23344                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23345                    }
23346                }
23347            }
23348        }
23349        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23350            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23351            for (File file : files) {
23352                final String packageName = file.getName();
23353                try {
23354                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23355                } catch (PackageManagerException e) {
23356                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23357                    try {
23358                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23359                                StorageManager.FLAG_STORAGE_DE, 0);
23360                    } catch (InstallerException e2) {
23361                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23362                    }
23363                }
23364            }
23365        }
23366
23367        // Ensure that data directories are ready to roll for all packages
23368        // installed for this volume and user
23369        final List<PackageSetting> packages;
23370        synchronized (mPackages) {
23371            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23372        }
23373        int preparedCount = 0;
23374        for (PackageSetting ps : packages) {
23375            final String packageName = ps.name;
23376            if (ps.pkg == null) {
23377                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23378                // TODO: might be due to legacy ASEC apps; we should circle back
23379                // and reconcile again once they're scanned
23380                continue;
23381            }
23382            // Skip non-core apps if requested
23383            if (onlyCoreApps && !ps.pkg.coreApp) {
23384                result.add(packageName);
23385                continue;
23386            }
23387
23388            if (ps.getInstalled(userId)) {
23389                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23390                preparedCount++;
23391            }
23392        }
23393
23394        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23395        return result;
23396    }
23397
23398    /**
23399     * Prepare app data for the given app just after it was installed or
23400     * upgraded. This method carefully only touches users that it's installed
23401     * for, and it forces a restorecon to handle any seinfo changes.
23402     * <p>
23403     * Verifies that directories exist and that ownership and labeling is
23404     * correct for all installed apps. If there is an ownership mismatch, it
23405     * will try recovering system apps by wiping data; third-party app data is
23406     * left intact.
23407     * <p>
23408     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23409     */
23410    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23411        final PackageSetting ps;
23412        synchronized (mPackages) {
23413            ps = mSettings.mPackages.get(pkg.packageName);
23414            mSettings.writeKernelMappingLPr(ps);
23415        }
23416
23417        final UserManager um = mContext.getSystemService(UserManager.class);
23418        UserManagerInternal umInternal = getUserManagerInternal();
23419        for (UserInfo user : um.getUsers()) {
23420            final int flags;
23421            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23422                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23423            } else if (umInternal.isUserRunning(user.id)) {
23424                flags = StorageManager.FLAG_STORAGE_DE;
23425            } else {
23426                continue;
23427            }
23428
23429            if (ps.getInstalled(user.id)) {
23430                // TODO: when user data is locked, mark that we're still dirty
23431                prepareAppDataLIF(pkg, user.id, flags);
23432            }
23433        }
23434    }
23435
23436    /**
23437     * Prepare app data for the given app.
23438     * <p>
23439     * Verifies that directories exist and that ownership and labeling is
23440     * correct for all installed apps. If there is an ownership mismatch, this
23441     * will try recovering system apps by wiping data; third-party app data is
23442     * left intact.
23443     */
23444    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23445        if (pkg == null) {
23446            Slog.wtf(TAG, "Package was null!", new Throwable());
23447            return;
23448        }
23449        prepareAppDataLeafLIF(pkg, userId, flags);
23450        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23451        for (int i = 0; i < childCount; i++) {
23452            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23453        }
23454    }
23455
23456    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23457            boolean maybeMigrateAppData) {
23458        prepareAppDataLIF(pkg, userId, flags);
23459
23460        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23461            // We may have just shuffled around app data directories, so
23462            // prepare them one more time
23463            prepareAppDataLIF(pkg, userId, flags);
23464        }
23465    }
23466
23467    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23468        if (DEBUG_APP_DATA) {
23469            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23470                    + Integer.toHexString(flags));
23471        }
23472
23473        final String volumeUuid = pkg.volumeUuid;
23474        final String packageName = pkg.packageName;
23475        final ApplicationInfo app = pkg.applicationInfo;
23476        final int appId = UserHandle.getAppId(app.uid);
23477
23478        Preconditions.checkNotNull(app.seInfo);
23479
23480        long ceDataInode = -1;
23481        try {
23482            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23483                    appId, app.seInfo, app.targetSdkVersion);
23484        } catch (InstallerException e) {
23485            if (app.isSystemApp()) {
23486                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23487                        + ", but trying to recover: " + e);
23488                destroyAppDataLeafLIF(pkg, userId, flags);
23489                try {
23490                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23491                            appId, app.seInfo, app.targetSdkVersion);
23492                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23493                } catch (InstallerException e2) {
23494                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23495                }
23496            } else {
23497                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23498            }
23499        }
23500
23501        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23502            // TODO: mark this structure as dirty so we persist it!
23503            synchronized (mPackages) {
23504                final PackageSetting ps = mSettings.mPackages.get(packageName);
23505                if (ps != null) {
23506                    ps.setCeDataInode(ceDataInode, userId);
23507                }
23508            }
23509        }
23510
23511        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23512    }
23513
23514    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23515        if (pkg == null) {
23516            Slog.wtf(TAG, "Package was null!", new Throwable());
23517            return;
23518        }
23519        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23520        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23521        for (int i = 0; i < childCount; i++) {
23522            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23523        }
23524    }
23525
23526    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23527        final String volumeUuid = pkg.volumeUuid;
23528        final String packageName = pkg.packageName;
23529        final ApplicationInfo app = pkg.applicationInfo;
23530
23531        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23532            // Create a native library symlink only if we have native libraries
23533            // and if the native libraries are 32 bit libraries. We do not provide
23534            // this symlink for 64 bit libraries.
23535            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23536                final String nativeLibPath = app.nativeLibraryDir;
23537                try {
23538                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23539                            nativeLibPath, userId);
23540                } catch (InstallerException e) {
23541                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23542                }
23543            }
23544        }
23545    }
23546
23547    /**
23548     * For system apps on non-FBE devices, this method migrates any existing
23549     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23550     * requested by the app.
23551     */
23552    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23553        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23554                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23555            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23556                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23557            try {
23558                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23559                        storageTarget);
23560            } catch (InstallerException e) {
23561                logCriticalInfo(Log.WARN,
23562                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23563            }
23564            return true;
23565        } else {
23566            return false;
23567        }
23568    }
23569
23570    public PackageFreezer freezePackage(String packageName, String killReason) {
23571        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23572    }
23573
23574    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23575        return new PackageFreezer(packageName, userId, killReason);
23576    }
23577
23578    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23579            String killReason) {
23580        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23581    }
23582
23583    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23584            String killReason) {
23585        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23586            return new PackageFreezer();
23587        } else {
23588            return freezePackage(packageName, userId, killReason);
23589        }
23590    }
23591
23592    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23593            String killReason) {
23594        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23595    }
23596
23597    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23598            String killReason) {
23599        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23600            return new PackageFreezer();
23601        } else {
23602            return freezePackage(packageName, userId, killReason);
23603        }
23604    }
23605
23606    /**
23607     * Class that freezes and kills the given package upon creation, and
23608     * unfreezes it upon closing. This is typically used when doing surgery on
23609     * app code/data to prevent the app from running while you're working.
23610     */
23611    private class PackageFreezer implements AutoCloseable {
23612        private final String mPackageName;
23613        private final PackageFreezer[] mChildren;
23614
23615        private final boolean mWeFroze;
23616
23617        private final AtomicBoolean mClosed = new AtomicBoolean();
23618        private final CloseGuard mCloseGuard = CloseGuard.get();
23619
23620        /**
23621         * Create and return a stub freezer that doesn't actually do anything,
23622         * typically used when someone requested
23623         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23624         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23625         */
23626        public PackageFreezer() {
23627            mPackageName = null;
23628            mChildren = null;
23629            mWeFroze = false;
23630            mCloseGuard.open("close");
23631        }
23632
23633        public PackageFreezer(String packageName, int userId, String killReason) {
23634            synchronized (mPackages) {
23635                mPackageName = packageName;
23636                mWeFroze = mFrozenPackages.add(mPackageName);
23637
23638                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23639                if (ps != null) {
23640                    killApplication(ps.name, ps.appId, userId, killReason);
23641                }
23642
23643                final PackageParser.Package p = mPackages.get(packageName);
23644                if (p != null && p.childPackages != null) {
23645                    final int N = p.childPackages.size();
23646                    mChildren = new PackageFreezer[N];
23647                    for (int i = 0; i < N; i++) {
23648                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23649                                userId, killReason);
23650                    }
23651                } else {
23652                    mChildren = null;
23653                }
23654            }
23655            mCloseGuard.open("close");
23656        }
23657
23658        @Override
23659        protected void finalize() throws Throwable {
23660            try {
23661                if (mCloseGuard != null) {
23662                    mCloseGuard.warnIfOpen();
23663                }
23664
23665                close();
23666            } finally {
23667                super.finalize();
23668            }
23669        }
23670
23671        @Override
23672        public void close() {
23673            mCloseGuard.close();
23674            if (mClosed.compareAndSet(false, true)) {
23675                synchronized (mPackages) {
23676                    if (mWeFroze) {
23677                        mFrozenPackages.remove(mPackageName);
23678                    }
23679
23680                    if (mChildren != null) {
23681                        for (PackageFreezer freezer : mChildren) {
23682                            freezer.close();
23683                        }
23684                    }
23685                }
23686            }
23687        }
23688    }
23689
23690    /**
23691     * Verify that given package is currently frozen.
23692     */
23693    private void checkPackageFrozen(String packageName) {
23694        synchronized (mPackages) {
23695            if (!mFrozenPackages.contains(packageName)) {
23696                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23697            }
23698        }
23699    }
23700
23701    @Override
23702    public int movePackage(final String packageName, final String volumeUuid) {
23703        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23704
23705        final int callingUid = Binder.getCallingUid();
23706        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23707        final int moveId = mNextMoveId.getAndIncrement();
23708        mHandler.post(new Runnable() {
23709            @Override
23710            public void run() {
23711                try {
23712                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23713                } catch (PackageManagerException e) {
23714                    Slog.w(TAG, "Failed to move " + packageName, e);
23715                    mMoveCallbacks.notifyStatusChanged(moveId,
23716                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23717                }
23718            }
23719        });
23720        return moveId;
23721    }
23722
23723    private void movePackageInternal(final String packageName, final String volumeUuid,
23724            final int moveId, final int callingUid, UserHandle user)
23725                    throws PackageManagerException {
23726        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23727        final PackageManager pm = mContext.getPackageManager();
23728
23729        final boolean currentAsec;
23730        final String currentVolumeUuid;
23731        final File codeFile;
23732        final String installerPackageName;
23733        final String packageAbiOverride;
23734        final int appId;
23735        final String seinfo;
23736        final String label;
23737        final int targetSdkVersion;
23738        final PackageFreezer freezer;
23739        final int[] installedUserIds;
23740
23741        // reader
23742        synchronized (mPackages) {
23743            final PackageParser.Package pkg = mPackages.get(packageName);
23744            final PackageSetting ps = mSettings.mPackages.get(packageName);
23745            if (pkg == null
23746                    || ps == null
23747                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23748                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23749            }
23750            if (pkg.applicationInfo.isSystemApp()) {
23751                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23752                        "Cannot move system application");
23753            }
23754
23755            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23756            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23757                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23758            if (isInternalStorage && !allow3rdPartyOnInternal) {
23759                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23760                        "3rd party apps are not allowed on internal storage");
23761            }
23762
23763            if (pkg.applicationInfo.isExternalAsec()) {
23764                currentAsec = true;
23765                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23766            } else if (pkg.applicationInfo.isForwardLocked()) {
23767                currentAsec = true;
23768                currentVolumeUuid = "forward_locked";
23769            } else {
23770                currentAsec = false;
23771                currentVolumeUuid = ps.volumeUuid;
23772
23773                final File probe = new File(pkg.codePath);
23774                final File probeOat = new File(probe, "oat");
23775                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23776                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23777                            "Move only supported for modern cluster style installs");
23778                }
23779            }
23780
23781            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23782                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23783                        "Package already moved to " + volumeUuid);
23784            }
23785            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23786                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23787                        "Device admin cannot be moved");
23788            }
23789
23790            if (mFrozenPackages.contains(packageName)) {
23791                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23792                        "Failed to move already frozen package");
23793            }
23794
23795            codeFile = new File(pkg.codePath);
23796            installerPackageName = ps.installerPackageName;
23797            packageAbiOverride = ps.cpuAbiOverrideString;
23798            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23799            seinfo = pkg.applicationInfo.seInfo;
23800            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23801            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23802            freezer = freezePackage(packageName, "movePackageInternal");
23803            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23804        }
23805
23806        final Bundle extras = new Bundle();
23807        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23808        extras.putString(Intent.EXTRA_TITLE, label);
23809        mMoveCallbacks.notifyCreated(moveId, extras);
23810
23811        int installFlags;
23812        final boolean moveCompleteApp;
23813        final File measurePath;
23814
23815        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23816            installFlags = INSTALL_INTERNAL;
23817            moveCompleteApp = !currentAsec;
23818            measurePath = Environment.getDataAppDirectory(volumeUuid);
23819        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23820            installFlags = INSTALL_EXTERNAL;
23821            moveCompleteApp = false;
23822            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23823        } else {
23824            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23825            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23826                    || !volume.isMountedWritable()) {
23827                freezer.close();
23828                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23829                        "Move location not mounted private volume");
23830            }
23831
23832            Preconditions.checkState(!currentAsec);
23833
23834            installFlags = INSTALL_INTERNAL;
23835            moveCompleteApp = true;
23836            measurePath = Environment.getDataAppDirectory(volumeUuid);
23837        }
23838
23839        final PackageStats stats = new PackageStats(null, -1);
23840        synchronized (mInstaller) {
23841            for (int userId : installedUserIds) {
23842                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23843                    freezer.close();
23844                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23845                            "Failed to measure package size");
23846                }
23847            }
23848        }
23849
23850        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23851                + stats.dataSize);
23852
23853        final long startFreeBytes = measurePath.getUsableSpace();
23854        final long sizeBytes;
23855        if (moveCompleteApp) {
23856            sizeBytes = stats.codeSize + stats.dataSize;
23857        } else {
23858            sizeBytes = stats.codeSize;
23859        }
23860
23861        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23862            freezer.close();
23863            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23864                    "Not enough free space to move");
23865        }
23866
23867        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23868
23869        final CountDownLatch installedLatch = new CountDownLatch(1);
23870        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23871            @Override
23872            public void onUserActionRequired(Intent intent) throws RemoteException {
23873                throw new IllegalStateException();
23874            }
23875
23876            @Override
23877            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23878                    Bundle extras) throws RemoteException {
23879                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23880                        + PackageManager.installStatusToString(returnCode, msg));
23881
23882                installedLatch.countDown();
23883                freezer.close();
23884
23885                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23886                switch (status) {
23887                    case PackageInstaller.STATUS_SUCCESS:
23888                        mMoveCallbacks.notifyStatusChanged(moveId,
23889                                PackageManager.MOVE_SUCCEEDED);
23890                        break;
23891                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23892                        mMoveCallbacks.notifyStatusChanged(moveId,
23893                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23894                        break;
23895                    default:
23896                        mMoveCallbacks.notifyStatusChanged(moveId,
23897                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23898                        break;
23899                }
23900            }
23901        };
23902
23903        final MoveInfo move;
23904        if (moveCompleteApp) {
23905            // Kick off a thread to report progress estimates
23906            new Thread() {
23907                @Override
23908                public void run() {
23909                    while (true) {
23910                        try {
23911                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23912                                break;
23913                            }
23914                        } catch (InterruptedException ignored) {
23915                        }
23916
23917                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23918                        final int progress = 10 + (int) MathUtils.constrain(
23919                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23920                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23921                    }
23922                }
23923            }.start();
23924
23925            final String dataAppName = codeFile.getName();
23926            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23927                    dataAppName, appId, seinfo, targetSdkVersion);
23928        } else {
23929            move = null;
23930        }
23931
23932        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23933
23934        final Message msg = mHandler.obtainMessage(INIT_COPY);
23935        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23936        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23937                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23938                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23939                PackageManager.INSTALL_REASON_UNKNOWN);
23940        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23941        msg.obj = params;
23942
23943        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23944                System.identityHashCode(msg.obj));
23945        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23946                System.identityHashCode(msg.obj));
23947
23948        mHandler.sendMessage(msg);
23949    }
23950
23951    @Override
23952    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23953        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23954
23955        final int realMoveId = mNextMoveId.getAndIncrement();
23956        final Bundle extras = new Bundle();
23957        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23958        mMoveCallbacks.notifyCreated(realMoveId, extras);
23959
23960        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23961            @Override
23962            public void onCreated(int moveId, Bundle extras) {
23963                // Ignored
23964            }
23965
23966            @Override
23967            public void onStatusChanged(int moveId, int status, long estMillis) {
23968                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23969            }
23970        };
23971
23972        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23973        storage.setPrimaryStorageUuid(volumeUuid, callback);
23974        return realMoveId;
23975    }
23976
23977    @Override
23978    public int getMoveStatus(int moveId) {
23979        mContext.enforceCallingOrSelfPermission(
23980                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23981        return mMoveCallbacks.mLastStatus.get(moveId);
23982    }
23983
23984    @Override
23985    public void registerMoveCallback(IPackageMoveObserver callback) {
23986        mContext.enforceCallingOrSelfPermission(
23987                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23988        mMoveCallbacks.register(callback);
23989    }
23990
23991    @Override
23992    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23993        mContext.enforceCallingOrSelfPermission(
23994                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23995        mMoveCallbacks.unregister(callback);
23996    }
23997
23998    @Override
23999    public boolean setInstallLocation(int loc) {
24000        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24001                null);
24002        if (getInstallLocation() == loc) {
24003            return true;
24004        }
24005        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24006                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24007            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24008                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24009            return true;
24010        }
24011        return false;
24012   }
24013
24014    @Override
24015    public int getInstallLocation() {
24016        // allow instant app access
24017        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24018                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24019                PackageHelper.APP_INSTALL_AUTO);
24020    }
24021
24022    /** Called by UserManagerService */
24023    void cleanUpUser(UserManagerService userManager, int userHandle) {
24024        synchronized (mPackages) {
24025            mDirtyUsers.remove(userHandle);
24026            mUserNeedsBadging.delete(userHandle);
24027            mSettings.removeUserLPw(userHandle);
24028            mPendingBroadcasts.remove(userHandle);
24029            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24030            removeUnusedPackagesLPw(userManager, userHandle);
24031        }
24032    }
24033
24034    /**
24035     * We're removing userHandle and would like to remove any downloaded packages
24036     * that are no longer in use by any other user.
24037     * @param userHandle the user being removed
24038     */
24039    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24040        final boolean DEBUG_CLEAN_APKS = false;
24041        int [] users = userManager.getUserIds();
24042        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24043        while (psit.hasNext()) {
24044            PackageSetting ps = psit.next();
24045            if (ps.pkg == null) {
24046                continue;
24047            }
24048            final String packageName = ps.pkg.packageName;
24049            // Skip over if system app
24050            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24051                continue;
24052            }
24053            if (DEBUG_CLEAN_APKS) {
24054                Slog.i(TAG, "Checking package " + packageName);
24055            }
24056            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24057            if (keep) {
24058                if (DEBUG_CLEAN_APKS) {
24059                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24060                }
24061            } else {
24062                for (int i = 0; i < users.length; i++) {
24063                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24064                        keep = true;
24065                        if (DEBUG_CLEAN_APKS) {
24066                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24067                                    + users[i]);
24068                        }
24069                        break;
24070                    }
24071                }
24072            }
24073            if (!keep) {
24074                if (DEBUG_CLEAN_APKS) {
24075                    Slog.i(TAG, "  Removing package " + packageName);
24076                }
24077                mHandler.post(new Runnable() {
24078                    public void run() {
24079                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24080                                userHandle, 0);
24081                    } //end run
24082                });
24083            }
24084        }
24085    }
24086
24087    /** Called by UserManagerService */
24088    void createNewUser(int userId, String[] disallowedPackages) {
24089        synchronized (mInstallLock) {
24090            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24091        }
24092        synchronized (mPackages) {
24093            scheduleWritePackageRestrictionsLocked(userId);
24094            scheduleWritePackageListLocked(userId);
24095            applyFactoryDefaultBrowserLPw(userId);
24096            primeDomainVerificationsLPw(userId);
24097        }
24098    }
24099
24100    void onNewUserCreated(final int userId) {
24101        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24102        // If permission review for legacy apps is required, we represent
24103        // dagerous permissions for such apps as always granted runtime
24104        // permissions to keep per user flag state whether review is needed.
24105        // Hence, if a new user is added we have to propagate dangerous
24106        // permission grants for these legacy apps.
24107        if (mPermissionReviewRequired) {
24108            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24109                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24110        }
24111    }
24112
24113    @Override
24114    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24115        mContext.enforceCallingOrSelfPermission(
24116                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24117                "Only package verification agents can read the verifier device identity");
24118
24119        synchronized (mPackages) {
24120            return mSettings.getVerifierDeviceIdentityLPw();
24121        }
24122    }
24123
24124    @Override
24125    public void setPermissionEnforced(String permission, boolean enforced) {
24126        // TODO: Now that we no longer change GID for storage, this should to away.
24127        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24128                "setPermissionEnforced");
24129        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24130            synchronized (mPackages) {
24131                if (mSettings.mReadExternalStorageEnforced == null
24132                        || mSettings.mReadExternalStorageEnforced != enforced) {
24133                    mSettings.mReadExternalStorageEnforced = enforced;
24134                    mSettings.writeLPr();
24135                }
24136            }
24137            // kill any non-foreground processes so we restart them and
24138            // grant/revoke the GID.
24139            final IActivityManager am = ActivityManager.getService();
24140            if (am != null) {
24141                final long token = Binder.clearCallingIdentity();
24142                try {
24143                    am.killProcessesBelowForeground("setPermissionEnforcement");
24144                } catch (RemoteException e) {
24145                } finally {
24146                    Binder.restoreCallingIdentity(token);
24147                }
24148            }
24149        } else {
24150            throw new IllegalArgumentException("No selective enforcement for " + permission);
24151        }
24152    }
24153
24154    @Override
24155    @Deprecated
24156    public boolean isPermissionEnforced(String permission) {
24157        // allow instant applications
24158        return true;
24159    }
24160
24161    @Override
24162    public boolean isStorageLow() {
24163        // allow instant applications
24164        final long token = Binder.clearCallingIdentity();
24165        try {
24166            final DeviceStorageMonitorInternal
24167                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24168            if (dsm != null) {
24169                return dsm.isMemoryLow();
24170            } else {
24171                return false;
24172            }
24173        } finally {
24174            Binder.restoreCallingIdentity(token);
24175        }
24176    }
24177
24178    @Override
24179    public IPackageInstaller getPackageInstaller() {
24180        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24181            return null;
24182        }
24183        return mInstallerService;
24184    }
24185
24186    private boolean userNeedsBadging(int userId) {
24187        int index = mUserNeedsBadging.indexOfKey(userId);
24188        if (index < 0) {
24189            final UserInfo userInfo;
24190            final long token = Binder.clearCallingIdentity();
24191            try {
24192                userInfo = sUserManager.getUserInfo(userId);
24193            } finally {
24194                Binder.restoreCallingIdentity(token);
24195            }
24196            final boolean b;
24197            if (userInfo != null && userInfo.isManagedProfile()) {
24198                b = true;
24199            } else {
24200                b = false;
24201            }
24202            mUserNeedsBadging.put(userId, b);
24203            return b;
24204        }
24205        return mUserNeedsBadging.valueAt(index);
24206    }
24207
24208    @Override
24209    public KeySet getKeySetByAlias(String packageName, String alias) {
24210        if (packageName == null || alias == null) {
24211            return null;
24212        }
24213        synchronized(mPackages) {
24214            final PackageParser.Package pkg = mPackages.get(packageName);
24215            if (pkg == null) {
24216                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24217                throw new IllegalArgumentException("Unknown package: " + packageName);
24218            }
24219            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24220            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24221                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24222                throw new IllegalArgumentException("Unknown package: " + packageName);
24223            }
24224            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24225            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24226        }
24227    }
24228
24229    @Override
24230    public KeySet getSigningKeySet(String packageName) {
24231        if (packageName == null) {
24232            return null;
24233        }
24234        synchronized(mPackages) {
24235            final int callingUid = Binder.getCallingUid();
24236            final int callingUserId = UserHandle.getUserId(callingUid);
24237            final PackageParser.Package pkg = mPackages.get(packageName);
24238            if (pkg == null) {
24239                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24240                throw new IllegalArgumentException("Unknown package: " + packageName);
24241            }
24242            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24243            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24244                // filter and pretend the package doesn't exist
24245                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24246                        + ", uid:" + callingUid);
24247                throw new IllegalArgumentException("Unknown package: " + packageName);
24248            }
24249            if (pkg.applicationInfo.uid != callingUid
24250                    && Process.SYSTEM_UID != callingUid) {
24251                throw new SecurityException("May not access signing KeySet of other apps.");
24252            }
24253            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24254            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24255        }
24256    }
24257
24258    @Override
24259    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24260        final int callingUid = Binder.getCallingUid();
24261        if (getInstantAppPackageName(callingUid) != null) {
24262            return false;
24263        }
24264        if (packageName == null || ks == null) {
24265            return false;
24266        }
24267        synchronized(mPackages) {
24268            final PackageParser.Package pkg = mPackages.get(packageName);
24269            if (pkg == null
24270                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24271                            UserHandle.getUserId(callingUid))) {
24272                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24273                throw new IllegalArgumentException("Unknown package: " + packageName);
24274            }
24275            IBinder ksh = ks.getToken();
24276            if (ksh instanceof KeySetHandle) {
24277                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24278                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24279            }
24280            return false;
24281        }
24282    }
24283
24284    @Override
24285    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24286        final int callingUid = Binder.getCallingUid();
24287        if (getInstantAppPackageName(callingUid) != null) {
24288            return false;
24289        }
24290        if (packageName == null || ks == null) {
24291            return false;
24292        }
24293        synchronized(mPackages) {
24294            final PackageParser.Package pkg = mPackages.get(packageName);
24295            if (pkg == null
24296                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24297                            UserHandle.getUserId(callingUid))) {
24298                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24299                throw new IllegalArgumentException("Unknown package: " + packageName);
24300            }
24301            IBinder ksh = ks.getToken();
24302            if (ksh instanceof KeySetHandle) {
24303                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24304                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24305            }
24306            return false;
24307        }
24308    }
24309
24310    private void deletePackageIfUnusedLPr(final String packageName) {
24311        PackageSetting ps = mSettings.mPackages.get(packageName);
24312        if (ps == null) {
24313            return;
24314        }
24315        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24316            // TODO Implement atomic delete if package is unused
24317            // It is currently possible that the package will be deleted even if it is installed
24318            // after this method returns.
24319            mHandler.post(new Runnable() {
24320                public void run() {
24321                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24322                            0, PackageManager.DELETE_ALL_USERS);
24323                }
24324            });
24325        }
24326    }
24327
24328    /**
24329     * Check and throw if the given before/after packages would be considered a
24330     * downgrade.
24331     */
24332    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24333            throws PackageManagerException {
24334        if (after.versionCode < before.mVersionCode) {
24335            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24336                    "Update version code " + after.versionCode + " is older than current "
24337                    + before.mVersionCode);
24338        } else if (after.versionCode == before.mVersionCode) {
24339            if (after.baseRevisionCode < before.baseRevisionCode) {
24340                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24341                        "Update base revision code " + after.baseRevisionCode
24342                        + " is older than current " + before.baseRevisionCode);
24343            }
24344
24345            if (!ArrayUtils.isEmpty(after.splitNames)) {
24346                for (int i = 0; i < after.splitNames.length; i++) {
24347                    final String splitName = after.splitNames[i];
24348                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24349                    if (j != -1) {
24350                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24351                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24352                                    "Update split " + splitName + " revision code "
24353                                    + after.splitRevisionCodes[i] + " is older than current "
24354                                    + before.splitRevisionCodes[j]);
24355                        }
24356                    }
24357                }
24358            }
24359        }
24360    }
24361
24362    private static class MoveCallbacks extends Handler {
24363        private static final int MSG_CREATED = 1;
24364        private static final int MSG_STATUS_CHANGED = 2;
24365
24366        private final RemoteCallbackList<IPackageMoveObserver>
24367                mCallbacks = new RemoteCallbackList<>();
24368
24369        private final SparseIntArray mLastStatus = new SparseIntArray();
24370
24371        public MoveCallbacks(Looper looper) {
24372            super(looper);
24373        }
24374
24375        public void register(IPackageMoveObserver callback) {
24376            mCallbacks.register(callback);
24377        }
24378
24379        public void unregister(IPackageMoveObserver callback) {
24380            mCallbacks.unregister(callback);
24381        }
24382
24383        @Override
24384        public void handleMessage(Message msg) {
24385            final SomeArgs args = (SomeArgs) msg.obj;
24386            final int n = mCallbacks.beginBroadcast();
24387            for (int i = 0; i < n; i++) {
24388                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24389                try {
24390                    invokeCallback(callback, msg.what, args);
24391                } catch (RemoteException ignored) {
24392                }
24393            }
24394            mCallbacks.finishBroadcast();
24395            args.recycle();
24396        }
24397
24398        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24399                throws RemoteException {
24400            switch (what) {
24401                case MSG_CREATED: {
24402                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24403                    break;
24404                }
24405                case MSG_STATUS_CHANGED: {
24406                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24407                    break;
24408                }
24409            }
24410        }
24411
24412        private void notifyCreated(int moveId, Bundle extras) {
24413            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24414
24415            final SomeArgs args = SomeArgs.obtain();
24416            args.argi1 = moveId;
24417            args.arg2 = extras;
24418            obtainMessage(MSG_CREATED, args).sendToTarget();
24419        }
24420
24421        private void notifyStatusChanged(int moveId, int status) {
24422            notifyStatusChanged(moveId, status, -1);
24423        }
24424
24425        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24426            Slog.v(TAG, "Move " + moveId + " status " + status);
24427
24428            final SomeArgs args = SomeArgs.obtain();
24429            args.argi1 = moveId;
24430            args.argi2 = status;
24431            args.arg3 = estMillis;
24432            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24433
24434            synchronized (mLastStatus) {
24435                mLastStatus.put(moveId, status);
24436            }
24437        }
24438    }
24439
24440    private final static class OnPermissionChangeListeners extends Handler {
24441        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24442
24443        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24444                new RemoteCallbackList<>();
24445
24446        public OnPermissionChangeListeners(Looper looper) {
24447            super(looper);
24448        }
24449
24450        @Override
24451        public void handleMessage(Message msg) {
24452            switch (msg.what) {
24453                case MSG_ON_PERMISSIONS_CHANGED: {
24454                    final int uid = msg.arg1;
24455                    handleOnPermissionsChanged(uid);
24456                } break;
24457            }
24458        }
24459
24460        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24461            mPermissionListeners.register(listener);
24462
24463        }
24464
24465        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24466            mPermissionListeners.unregister(listener);
24467        }
24468
24469        public void onPermissionsChanged(int uid) {
24470            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24471                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24472            }
24473        }
24474
24475        private void handleOnPermissionsChanged(int uid) {
24476            final int count = mPermissionListeners.beginBroadcast();
24477            try {
24478                for (int i = 0; i < count; i++) {
24479                    IOnPermissionsChangeListener callback = mPermissionListeners
24480                            .getBroadcastItem(i);
24481                    try {
24482                        callback.onPermissionsChanged(uid);
24483                    } catch (RemoteException e) {
24484                        Log.e(TAG, "Permission listener is dead", e);
24485                    }
24486                }
24487            } finally {
24488                mPermissionListeners.finishBroadcast();
24489            }
24490        }
24491    }
24492
24493    private class PackageManagerInternalImpl extends PackageManagerInternal {
24494        @Override
24495        public void setLocationPackagesProvider(PackagesProvider provider) {
24496            synchronized (mPackages) {
24497                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24498            }
24499        }
24500
24501        @Override
24502        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24503            synchronized (mPackages) {
24504                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24505            }
24506        }
24507
24508        @Override
24509        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24510            synchronized (mPackages) {
24511                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24512            }
24513        }
24514
24515        @Override
24516        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24517            synchronized (mPackages) {
24518                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24519            }
24520        }
24521
24522        @Override
24523        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24524            synchronized (mPackages) {
24525                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24526            }
24527        }
24528
24529        @Override
24530        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24531            synchronized (mPackages) {
24532                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24533            }
24534        }
24535
24536        @Override
24537        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24538            synchronized (mPackages) {
24539                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24540                        packageName, userId);
24541            }
24542        }
24543
24544        @Override
24545        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24546            synchronized (mPackages) {
24547                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24548                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24549                        packageName, userId);
24550            }
24551        }
24552
24553        @Override
24554        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24555            synchronized (mPackages) {
24556                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24557                        packageName, userId);
24558            }
24559        }
24560
24561        @Override
24562        public void setKeepUninstalledPackages(final List<String> packageList) {
24563            Preconditions.checkNotNull(packageList);
24564            List<String> removedFromList = null;
24565            synchronized (mPackages) {
24566                if (mKeepUninstalledPackages != null) {
24567                    final int packagesCount = mKeepUninstalledPackages.size();
24568                    for (int i = 0; i < packagesCount; i++) {
24569                        String oldPackage = mKeepUninstalledPackages.get(i);
24570                        if (packageList != null && packageList.contains(oldPackage)) {
24571                            continue;
24572                        }
24573                        if (removedFromList == null) {
24574                            removedFromList = new ArrayList<>();
24575                        }
24576                        removedFromList.add(oldPackage);
24577                    }
24578                }
24579                mKeepUninstalledPackages = new ArrayList<>(packageList);
24580                if (removedFromList != null) {
24581                    final int removedCount = removedFromList.size();
24582                    for (int i = 0; i < removedCount; i++) {
24583                        deletePackageIfUnusedLPr(removedFromList.get(i));
24584                    }
24585                }
24586            }
24587        }
24588
24589        @Override
24590        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24591            synchronized (mPackages) {
24592                // If we do not support permission review, done.
24593                if (!mPermissionReviewRequired) {
24594                    return false;
24595                }
24596
24597                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24598                if (packageSetting == null) {
24599                    return false;
24600                }
24601
24602                // Permission review applies only to apps not supporting the new permission model.
24603                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24604                    return false;
24605                }
24606
24607                // Legacy apps have the permission and get user consent on launch.
24608                PermissionsState permissionsState = packageSetting.getPermissionsState();
24609                return permissionsState.isPermissionReviewRequired(userId);
24610            }
24611        }
24612
24613        @Override
24614        public PackageInfo getPackageInfo(
24615                String packageName, int flags, int filterCallingUid, int userId) {
24616            return PackageManagerService.this
24617                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24618                            flags, filterCallingUid, userId);
24619        }
24620
24621        @Override
24622        public ApplicationInfo getApplicationInfo(
24623                String packageName, int flags, int filterCallingUid, int userId) {
24624            return PackageManagerService.this
24625                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24626        }
24627
24628        @Override
24629        public ActivityInfo getActivityInfo(
24630                ComponentName component, int flags, int filterCallingUid, int userId) {
24631            return PackageManagerService.this
24632                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24633        }
24634
24635        @Override
24636        public List<ResolveInfo> queryIntentActivities(
24637                Intent intent, int flags, int filterCallingUid, int userId) {
24638            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24639            return PackageManagerService.this
24640                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24641                            userId, false /*resolveForStart*/);
24642        }
24643
24644        @Override
24645        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24646                int userId) {
24647            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24648        }
24649
24650        @Override
24651        public void setDeviceAndProfileOwnerPackages(
24652                int deviceOwnerUserId, String deviceOwnerPackage,
24653                SparseArray<String> profileOwnerPackages) {
24654            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24655                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24656        }
24657
24658        @Override
24659        public boolean isPackageDataProtected(int userId, String packageName) {
24660            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24661        }
24662
24663        @Override
24664        public boolean isPackageEphemeral(int userId, String packageName) {
24665            synchronized (mPackages) {
24666                final PackageSetting ps = mSettings.mPackages.get(packageName);
24667                return ps != null ? ps.getInstantApp(userId) : false;
24668            }
24669        }
24670
24671        @Override
24672        public boolean wasPackageEverLaunched(String packageName, int userId) {
24673            synchronized (mPackages) {
24674                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24675            }
24676        }
24677
24678        @Override
24679        public void grantRuntimePermission(String packageName, String name, int userId,
24680                boolean overridePolicy) {
24681            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24682                    overridePolicy);
24683        }
24684
24685        @Override
24686        public void revokeRuntimePermission(String packageName, String name, int userId,
24687                boolean overridePolicy) {
24688            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24689                    overridePolicy);
24690        }
24691
24692        @Override
24693        public String getNameForUid(int uid) {
24694            return PackageManagerService.this.getNameForUid(uid);
24695        }
24696
24697        @Override
24698        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24699                Intent origIntent, String resolvedType, String callingPackage,
24700                Bundle verificationBundle, int userId) {
24701            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24702                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24703                    userId);
24704        }
24705
24706        @Override
24707        public void grantEphemeralAccess(int userId, Intent intent,
24708                int targetAppId, int ephemeralAppId) {
24709            synchronized (mPackages) {
24710                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24711                        targetAppId, ephemeralAppId);
24712            }
24713        }
24714
24715        @Override
24716        public boolean isInstantAppInstallerComponent(ComponentName component) {
24717            synchronized (mPackages) {
24718                return mInstantAppInstallerActivity != null
24719                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24720            }
24721        }
24722
24723        @Override
24724        public void pruneInstantApps() {
24725            mInstantAppRegistry.pruneInstantApps();
24726        }
24727
24728        @Override
24729        public String getSetupWizardPackageName() {
24730            return mSetupWizardPackage;
24731        }
24732
24733        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24734            if (policy != null) {
24735                mExternalSourcesPolicy = policy;
24736            }
24737        }
24738
24739        @Override
24740        public boolean isPackagePersistent(String packageName) {
24741            synchronized (mPackages) {
24742                PackageParser.Package pkg = mPackages.get(packageName);
24743                return pkg != null
24744                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24745                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24746                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24747                        : false;
24748            }
24749        }
24750
24751        @Override
24752        public List<PackageInfo> getOverlayPackages(int userId) {
24753            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24754            synchronized (mPackages) {
24755                for (PackageParser.Package p : mPackages.values()) {
24756                    if (p.mOverlayTarget != null) {
24757                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24758                        if (pkg != null) {
24759                            overlayPackages.add(pkg);
24760                        }
24761                    }
24762                }
24763            }
24764            return overlayPackages;
24765        }
24766
24767        @Override
24768        public List<String> getTargetPackageNames(int userId) {
24769            List<String> targetPackages = new ArrayList<>();
24770            synchronized (mPackages) {
24771                for (PackageParser.Package p : mPackages.values()) {
24772                    if (p.mOverlayTarget == null) {
24773                        targetPackages.add(p.packageName);
24774                    }
24775                }
24776            }
24777            return targetPackages;
24778        }
24779
24780        @Override
24781        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24782                @Nullable List<String> overlayPackageNames) {
24783            synchronized (mPackages) {
24784                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24785                    Slog.e(TAG, "failed to find package " + targetPackageName);
24786                    return false;
24787                }
24788                ArrayList<String> overlayPaths = null;
24789                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24790                    final int N = overlayPackageNames.size();
24791                    overlayPaths = new ArrayList<>(N);
24792                    for (int i = 0; i < N; i++) {
24793                        final String packageName = overlayPackageNames.get(i);
24794                        final PackageParser.Package pkg = mPackages.get(packageName);
24795                        if (pkg == null) {
24796                            Slog.e(TAG, "failed to find package " + packageName);
24797                            return false;
24798                        }
24799                        overlayPaths.add(pkg.baseCodePath);
24800                    }
24801                }
24802
24803                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24804                ps.setOverlayPaths(overlayPaths, userId);
24805                return true;
24806            }
24807        }
24808
24809        @Override
24810        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24811                int flags, int userId) {
24812            return resolveIntentInternal(
24813                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24814        }
24815
24816        @Override
24817        public ResolveInfo resolveService(Intent intent, String resolvedType,
24818                int flags, int userId, int callingUid) {
24819            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24820        }
24821
24822        @Override
24823        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24824            synchronized (mPackages) {
24825                mIsolatedOwners.put(isolatedUid, ownerUid);
24826            }
24827        }
24828
24829        @Override
24830        public void removeIsolatedUid(int isolatedUid) {
24831            synchronized (mPackages) {
24832                mIsolatedOwners.delete(isolatedUid);
24833            }
24834        }
24835
24836        @Override
24837        public int getUidTargetSdkVersion(int uid) {
24838            synchronized (mPackages) {
24839                return getUidTargetSdkVersionLockedLPr(uid);
24840            }
24841        }
24842
24843        @Override
24844        public boolean canAccessInstantApps(int callingUid, int userId) {
24845            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24846        }
24847    }
24848
24849    @Override
24850    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24851        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24852        synchronized (mPackages) {
24853            final long identity = Binder.clearCallingIdentity();
24854            try {
24855                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24856                        packageNames, userId);
24857            } finally {
24858                Binder.restoreCallingIdentity(identity);
24859            }
24860        }
24861    }
24862
24863    @Override
24864    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24865        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24866        synchronized (mPackages) {
24867            final long identity = Binder.clearCallingIdentity();
24868            try {
24869                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24870                        packageNames, userId);
24871            } finally {
24872                Binder.restoreCallingIdentity(identity);
24873            }
24874        }
24875    }
24876
24877    private static void enforceSystemOrPhoneCaller(String tag) {
24878        int callingUid = Binder.getCallingUid();
24879        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24880            throw new SecurityException(
24881                    "Cannot call " + tag + " from UID " + callingUid);
24882        }
24883    }
24884
24885    boolean isHistoricalPackageUsageAvailable() {
24886        return mPackageUsage.isHistoricalPackageUsageAvailable();
24887    }
24888
24889    /**
24890     * Return a <b>copy</b> of the collection of packages known to the package manager.
24891     * @return A copy of the values of mPackages.
24892     */
24893    Collection<PackageParser.Package> getPackages() {
24894        synchronized (mPackages) {
24895            return new ArrayList<>(mPackages.values());
24896        }
24897    }
24898
24899    /**
24900     * Logs process start information (including base APK hash) to the security log.
24901     * @hide
24902     */
24903    @Override
24904    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24905            String apkFile, int pid) {
24906        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24907            return;
24908        }
24909        if (!SecurityLog.isLoggingEnabled()) {
24910            return;
24911        }
24912        Bundle data = new Bundle();
24913        data.putLong("startTimestamp", System.currentTimeMillis());
24914        data.putString("processName", processName);
24915        data.putInt("uid", uid);
24916        data.putString("seinfo", seinfo);
24917        data.putString("apkFile", apkFile);
24918        data.putInt("pid", pid);
24919        Message msg = mProcessLoggingHandler.obtainMessage(
24920                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24921        msg.setData(data);
24922        mProcessLoggingHandler.sendMessage(msg);
24923    }
24924
24925    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24926        return mCompilerStats.getPackageStats(pkgName);
24927    }
24928
24929    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24930        return getOrCreateCompilerPackageStats(pkg.packageName);
24931    }
24932
24933    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24934        return mCompilerStats.getOrCreatePackageStats(pkgName);
24935    }
24936
24937    public void deleteCompilerPackageStats(String pkgName) {
24938        mCompilerStats.deletePackageStats(pkgName);
24939    }
24940
24941    @Override
24942    public int getInstallReason(String packageName, int userId) {
24943        final int callingUid = Binder.getCallingUid();
24944        enforceCrossUserPermission(callingUid, userId,
24945                true /* requireFullPermission */, false /* checkShell */,
24946                "get install reason");
24947        synchronized (mPackages) {
24948            final PackageSetting ps = mSettings.mPackages.get(packageName);
24949            if (filterAppAccessLPr(ps, callingUid, userId)) {
24950                return PackageManager.INSTALL_REASON_UNKNOWN;
24951            }
24952            if (ps != null) {
24953                return ps.getInstallReason(userId);
24954            }
24955        }
24956        return PackageManager.INSTALL_REASON_UNKNOWN;
24957    }
24958
24959    @Override
24960    public boolean canRequestPackageInstalls(String packageName, int userId) {
24961        return canRequestPackageInstallsInternal(packageName, 0, userId,
24962                true /* throwIfPermNotDeclared*/);
24963    }
24964
24965    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24966            boolean throwIfPermNotDeclared) {
24967        int callingUid = Binder.getCallingUid();
24968        int uid = getPackageUid(packageName, 0, userId);
24969        if (callingUid != uid && callingUid != Process.ROOT_UID
24970                && callingUid != Process.SYSTEM_UID) {
24971            throw new SecurityException(
24972                    "Caller uid " + callingUid + " does not own package " + packageName);
24973        }
24974        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24975        if (info == null) {
24976            return false;
24977        }
24978        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24979            return false;
24980        }
24981        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24982        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24983        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24984            if (throwIfPermNotDeclared) {
24985                throw new SecurityException("Need to declare " + appOpPermission
24986                        + " to call this api");
24987            } else {
24988                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24989                return false;
24990            }
24991        }
24992        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24993            return false;
24994        }
24995        if (mExternalSourcesPolicy != null) {
24996            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24997            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24998                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24999            }
25000        }
25001        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25002    }
25003
25004    @Override
25005    public ComponentName getInstantAppResolverSettingsComponent() {
25006        return mInstantAppResolverSettingsComponent;
25007    }
25008
25009    @Override
25010    public ComponentName getInstantAppInstallerComponent() {
25011        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25012            return null;
25013        }
25014        return mInstantAppInstallerActivity == null
25015                ? null : mInstantAppInstallerActivity.getComponentName();
25016    }
25017
25018    @Override
25019    public String getInstantAppAndroidId(String packageName, int userId) {
25020        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25021                "getInstantAppAndroidId");
25022        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25023                true /* requireFullPermission */, false /* checkShell */,
25024                "getInstantAppAndroidId");
25025        // Make sure the target is an Instant App.
25026        if (!isInstantApp(packageName, userId)) {
25027            return null;
25028        }
25029        synchronized (mPackages) {
25030            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25031        }
25032    }
25033
25034    boolean canHaveOatDir(String packageName) {
25035        synchronized (mPackages) {
25036            PackageParser.Package p = mPackages.get(packageName);
25037            if (p == null) {
25038                return false;
25039            }
25040            return p.canHaveOatDir();
25041        }
25042    }
25043
25044    private String getOatDir(PackageParser.Package pkg) {
25045        if (!pkg.canHaveOatDir()) {
25046            return null;
25047        }
25048        File codePath = new File(pkg.codePath);
25049        if (codePath.isDirectory()) {
25050            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25051        }
25052        return null;
25053    }
25054
25055    void deleteOatArtifactsOfPackage(String packageName) {
25056        final String[] instructionSets;
25057        final List<String> codePaths;
25058        final String oatDir;
25059        final PackageParser.Package pkg;
25060        synchronized (mPackages) {
25061            pkg = mPackages.get(packageName);
25062        }
25063        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25064        codePaths = pkg.getAllCodePaths();
25065        oatDir = getOatDir(pkg);
25066
25067        for (String codePath : codePaths) {
25068            for (String isa : instructionSets) {
25069                try {
25070                    mInstaller.deleteOdex(codePath, isa, oatDir);
25071                } catch (InstallerException e) {
25072                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25073                }
25074            }
25075        }
25076    }
25077
25078    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25079        Set<String> unusedPackages = new HashSet<>();
25080        long currentTimeInMillis = System.currentTimeMillis();
25081        synchronized (mPackages) {
25082            for (PackageParser.Package pkg : mPackages.values()) {
25083                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25084                if (ps == null) {
25085                    continue;
25086                }
25087                PackageDexUsage.PackageUseInfo packageUseInfo =
25088                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25089                if (PackageManagerServiceUtils
25090                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25091                                downgradeTimeThresholdMillis, packageUseInfo,
25092                                pkg.getLatestPackageUseTimeInMills(),
25093                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25094                    unusedPackages.add(pkg.packageName);
25095                }
25096            }
25097        }
25098        return unusedPackages;
25099    }
25100}
25101
25102interface PackageSender {
25103    void sendPackageBroadcast(final String action, final String pkg,
25104        final Bundle extras, final int flags, final String targetPkg,
25105        final IIntentReceiver finishedReceiver, final int[] userIds);
25106    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
25107        int appId, int... userIds);
25108}
25109