PackageManagerService.java revision 14062f2382388a3a15802bf8b8b24d1f41d548c6
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.IOnPermissionsChangeListener;
136import android.content.pm.IPackageDataObserver;
137import android.content.pm.IPackageDeleteObserver;
138import android.content.pm.IPackageDeleteObserver2;
139import android.content.pm.IPackageInstallObserver2;
140import android.content.pm.IPackageInstaller;
141import android.content.pm.IPackageManager;
142import android.content.pm.IPackageMoveObserver;
143import android.content.pm.IPackageStatsObserver;
144import android.content.pm.InstantAppInfo;
145import android.content.pm.InstantAppRequest;
146import android.content.pm.InstantAppResolveInfo;
147import android.content.pm.InstrumentationInfo;
148import android.content.pm.IntentFilterVerificationInfo;
149import android.content.pm.KeySet;
150import android.content.pm.PackageCleanItem;
151import android.content.pm.PackageInfo;
152import android.content.pm.PackageInfoLite;
153import android.content.pm.PackageInstaller;
154import android.content.pm.PackageManager;
155import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
156import android.content.pm.PackageManagerInternal;
157import android.content.pm.PackageParser;
158import android.content.pm.PackageParser.ActivityIntentInfo;
159import android.content.pm.PackageParser.PackageLite;
160import android.content.pm.PackageParser.PackageParserException;
161import android.content.pm.PackageStats;
162import android.content.pm.PackageUserState;
163import android.content.pm.ParceledListSlice;
164import android.content.pm.PermissionGroupInfo;
165import android.content.pm.PermissionInfo;
166import android.content.pm.ProviderInfo;
167import android.content.pm.ResolveInfo;
168import android.content.pm.ServiceInfo;
169import android.content.pm.SharedLibraryInfo;
170import android.content.pm.Signature;
171import android.content.pm.UserInfo;
172import android.content.pm.VerifierDeviceIdentity;
173import android.content.pm.VerifierInfo;
174import android.content.pm.VersionedPackage;
175import android.content.res.Resources;
176import android.database.ContentObserver;
177import android.graphics.Bitmap;
178import android.hardware.display.DisplayManager;
179import android.net.Uri;
180import android.os.Binder;
181import android.os.Build;
182import android.os.Bundle;
183import android.os.Debug;
184import android.os.Environment;
185import android.os.Environment.UserEnvironment;
186import android.os.FileUtils;
187import android.os.Handler;
188import android.os.IBinder;
189import android.os.Looper;
190import android.os.Message;
191import android.os.Parcel;
192import android.os.ParcelFileDescriptor;
193import android.os.PatternMatcher;
194import android.os.Process;
195import android.os.RemoteCallbackList;
196import android.os.RemoteException;
197import android.os.ResultReceiver;
198import android.os.SELinux;
199import android.os.ServiceManager;
200import android.os.ShellCallback;
201import android.os.SystemClock;
202import android.os.SystemProperties;
203import android.os.Trace;
204import android.os.UserHandle;
205import android.os.UserManager;
206import android.os.UserManagerInternal;
207import android.os.storage.IStorageManager;
208import android.os.storage.StorageEventListener;
209import android.os.storage.StorageManager;
210import android.os.storage.StorageManagerInternal;
211import android.os.storage.VolumeInfo;
212import android.os.storage.VolumeRecord;
213import android.provider.Settings.Global;
214import android.provider.Settings.Secure;
215import android.security.KeyStore;
216import android.security.SystemKeyStore;
217import android.service.pm.PackageServiceDumpProto;
218import android.system.ErrnoException;
219import android.system.Os;
220import android.text.TextUtils;
221import android.text.format.DateUtils;
222import android.util.ArrayMap;
223import android.util.ArraySet;
224import android.util.Base64;
225import android.util.BootTimingsTraceLog;
226import android.util.DisplayMetrics;
227import android.util.EventLog;
228import android.util.ExceptionUtils;
229import android.util.Log;
230import android.util.LogPrinter;
231import android.util.MathUtils;
232import android.util.PackageUtils;
233import android.util.Pair;
234import android.util.PrintStreamPrinter;
235import android.util.Slog;
236import android.util.SparseArray;
237import android.util.SparseBooleanArray;
238import android.util.SparseIntArray;
239import android.util.Xml;
240import android.util.jar.StrictJarFile;
241import android.util.proto.ProtoOutputStream;
242import android.view.Display;
243
244import com.android.internal.R;
245import com.android.internal.annotations.GuardedBy;
246import com.android.internal.app.IMediaContainerService;
247import com.android.internal.app.ResolverActivity;
248import com.android.internal.content.NativeLibraryHelper;
249import com.android.internal.content.PackageHelper;
250import com.android.internal.logging.MetricsLogger;
251import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
252import com.android.internal.os.IParcelFileDescriptorFactory;
253import com.android.internal.os.RoSystemProperties;
254import com.android.internal.os.SomeArgs;
255import com.android.internal.os.Zygote;
256import com.android.internal.telephony.CarrierAppUtils;
257import com.android.internal.util.ArrayUtils;
258import com.android.internal.util.ConcurrentUtils;
259import com.android.internal.util.DumpUtils;
260import com.android.internal.util.FastPrintWriter;
261import com.android.internal.util.FastXmlSerializer;
262import com.android.internal.util.IndentingPrintWriter;
263import com.android.internal.util.Preconditions;
264import com.android.internal.util.XmlUtils;
265import com.android.server.AttributeCache;
266import com.android.server.DeviceIdleController;
267import com.android.server.EventLogTags;
268import com.android.server.FgThread;
269import com.android.server.IntentResolver;
270import com.android.server.LocalServices;
271import com.android.server.LockGuard;
272import com.android.server.ServiceThread;
273import com.android.server.SystemConfig;
274import com.android.server.SystemServerInitThreadPool;
275import com.android.server.Watchdog;
276import com.android.server.net.NetworkPolicyManagerInternal;
277import com.android.server.pm.Installer.InstallerException;
278import com.android.server.pm.PermissionsState.PermissionState;
279import com.android.server.pm.Settings.DatabaseVersion;
280import com.android.server.pm.Settings.VersionInfo;
281import com.android.server.pm.dex.DexManager;
282import com.android.server.storage.DeviceStorageMonitorInternal;
283
284import dalvik.system.CloseGuard;
285import dalvik.system.DexFile;
286import dalvik.system.VMRuntime;
287
288import libcore.io.IoUtils;
289import libcore.util.EmptyArray;
290
291import org.xmlpull.v1.XmlPullParser;
292import org.xmlpull.v1.XmlPullParserException;
293import org.xmlpull.v1.XmlSerializer;
294
295import java.io.BufferedOutputStream;
296import java.io.BufferedReader;
297import java.io.ByteArrayInputStream;
298import java.io.ByteArrayOutputStream;
299import java.io.File;
300import java.io.FileDescriptor;
301import java.io.FileInputStream;
302import java.io.FileOutputStream;
303import java.io.FileReader;
304import java.io.FilenameFilter;
305import java.io.IOException;
306import java.io.PrintWriter;
307import java.lang.annotation.Retention;
308import java.lang.annotation.RetentionPolicy;
309import java.nio.charset.StandardCharsets;
310import java.security.DigestInputStream;
311import java.security.MessageDigest;
312import java.security.NoSuchAlgorithmException;
313import java.security.PublicKey;
314import java.security.SecureRandom;
315import java.security.cert.Certificate;
316import java.security.cert.CertificateEncodingException;
317import java.security.cert.CertificateException;
318import java.text.SimpleDateFormat;
319import java.util.ArrayList;
320import java.util.Arrays;
321import java.util.Collection;
322import java.util.Collections;
323import java.util.Comparator;
324import java.util.Date;
325import java.util.HashMap;
326import java.util.HashSet;
327import java.util.Iterator;
328import java.util.LinkedHashSet;
329import java.util.List;
330import java.util.Map;
331import java.util.Objects;
332import java.util.Set;
333import java.util.concurrent.CountDownLatch;
334import java.util.concurrent.Future;
335import java.util.concurrent.TimeUnit;
336import java.util.concurrent.atomic.AtomicBoolean;
337import java.util.concurrent.atomic.AtomicInteger;
338
339/**
340 * Keep track of all those APKs everywhere.
341 * <p>
342 * Internally there are two important locks:
343 * <ul>
344 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
345 * and other related state. It is a fine-grained lock that should only be held
346 * momentarily, as it's one of the most contended locks in the system.
347 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
348 * operations typically involve heavy lifting of application data on disk. Since
349 * {@code installd} is single-threaded, and it's operations can often be slow,
350 * this lock should never be acquired while already holding {@link #mPackages}.
351 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
352 * holding {@link #mInstallLock}.
353 * </ul>
354 * Many internal methods rely on the caller to hold the appropriate locks, and
355 * this contract is expressed through method name suffixes:
356 * <ul>
357 * <li>fooLI(): the caller must hold {@link #mInstallLock}
358 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
359 * being modified must be frozen
360 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
361 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
362 * </ul>
363 * <p>
364 * Because this class is very central to the platform's security; please run all
365 * CTS and unit tests whenever making modifications:
366 *
367 * <pre>
368 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
369 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
370 * </pre>
371 */
372public class PackageManagerService extends IPackageManager.Stub
373        implements PackageSender {
374    static final String TAG = "PackageManager";
375    static final boolean DEBUG_SETTINGS = false;
376    static final boolean DEBUG_PREFERRED = false;
377    static final boolean DEBUG_UPGRADE = false;
378    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
379    private static final boolean DEBUG_BACKUP = false;
380    private static final boolean DEBUG_INSTALL = false;
381    private static final boolean DEBUG_REMOVE = false;
382    private static final boolean DEBUG_BROADCASTS = false;
383    private static final boolean DEBUG_SHOW_INFO = false;
384    private static final boolean DEBUG_PACKAGE_INFO = false;
385    private static final boolean DEBUG_INTENT_MATCHING = false;
386    private static final boolean DEBUG_PACKAGE_SCANNING = false;
387    private static final boolean DEBUG_VERIFY = false;
388    private static final boolean DEBUG_FILTERS = false;
389    private static final boolean DEBUG_PERMISSIONS = false;
390    private static final boolean DEBUG_SHARED_LIBRARIES = false;
391
392    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
393    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
394    // user, but by default initialize to this.
395    public static final boolean DEBUG_DEXOPT = false;
396
397    private static final boolean DEBUG_ABI_SELECTION = false;
398    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
399    private static final boolean DEBUG_TRIAGED_MISSING = false;
400    private static final boolean DEBUG_APP_DATA = false;
401
402    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
403    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
404
405    private static final boolean HIDE_EPHEMERAL_APIS = false;
406
407    private static final boolean ENABLE_FREE_CACHE_V2 =
408            SystemProperties.getBoolean("fw.free_cache_v2", true);
409
410    private static final int RADIO_UID = Process.PHONE_UID;
411    private static final int LOG_UID = Process.LOG_UID;
412    private static final int NFC_UID = Process.NFC_UID;
413    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
414    private static final int SHELL_UID = Process.SHELL_UID;
415
416    // Cap the size of permission trees that 3rd party apps can define
417    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
418
419    // Suffix used during package installation when copying/moving
420    // package apks to install directory.
421    private static final String INSTALL_PACKAGE_SUFFIX = "-";
422
423    static final int SCAN_NO_DEX = 1<<1;
424    static final int SCAN_FORCE_DEX = 1<<2;
425    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
426    static final int SCAN_NEW_INSTALL = 1<<4;
427    static final int SCAN_UPDATE_TIME = 1<<5;
428    static final int SCAN_BOOTING = 1<<6;
429    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
430    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
431    static final int SCAN_REPLACING = 1<<9;
432    static final int SCAN_REQUIRE_KNOWN = 1<<10;
433    static final int SCAN_MOVE = 1<<11;
434    static final int SCAN_INITIAL = 1<<12;
435    static final int SCAN_CHECK_ONLY = 1<<13;
436    static final int SCAN_DONT_KILL_APP = 1<<14;
437    static final int SCAN_IGNORE_FROZEN = 1<<15;
438    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
439    static final int SCAN_AS_INSTANT_APP = 1<<17;
440    static final int SCAN_AS_FULL_APP = 1<<18;
441    /** Should not be with the scan flags */
442    static final int FLAGS_REMOVE_CHATTY = 1<<31;
443
444    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
445
446    private static final int[] EMPTY_INT_ARRAY = new int[0];
447
448    private static final int TYPE_UNKNOWN = 0;
449    private static final int TYPE_ACTIVITY = 1;
450    private static final int TYPE_RECEIVER = 2;
451    private static final int TYPE_SERVICE = 3;
452    private static final int TYPE_PROVIDER = 4;
453    @IntDef(prefix = { "TYPE_" }, value = {
454            TYPE_UNKNOWN,
455            TYPE_ACTIVITY,
456            TYPE_RECEIVER,
457            TYPE_SERVICE,
458            TYPE_PROVIDER,
459    })
460    @Retention(RetentionPolicy.SOURCE)
461    public @interface ComponentType {}
462
463    /**
464     * Timeout (in milliseconds) after which the watchdog should declare that
465     * our handler thread is wedged.  The usual default for such things is one
466     * minute but we sometimes do very lengthy I/O operations on this thread,
467     * such as installing multi-gigabyte applications, so ours needs to be longer.
468     */
469    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
470
471    /**
472     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
473     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
474     * settings entry if available, otherwise we use the hardcoded default.  If it's been
475     * more than this long since the last fstrim, we force one during the boot sequence.
476     *
477     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
478     * one gets run at the next available charging+idle time.  This final mandatory
479     * no-fstrim check kicks in only of the other scheduling criteria is never met.
480     */
481    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
482
483    /**
484     * Whether verification is enabled by default.
485     */
486    private static final boolean DEFAULT_VERIFY_ENABLE = true;
487
488    /**
489     * The default maximum time to wait for the verification agent to return in
490     * milliseconds.
491     */
492    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
493
494    /**
495     * The default response for package verification timeout.
496     *
497     * This can be either PackageManager.VERIFICATION_ALLOW or
498     * PackageManager.VERIFICATION_REJECT.
499     */
500    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
501
502    static final String PLATFORM_PACKAGE_NAME = "android";
503
504    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
505
506    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
507            DEFAULT_CONTAINER_PACKAGE,
508            "com.android.defcontainer.DefaultContainerService");
509
510    private static final String KILL_APP_REASON_GIDS_CHANGED =
511            "permission grant or revoke changed gids";
512
513    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
514            "permissions revoked";
515
516    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
517
518    private static final String PACKAGE_SCHEME = "package";
519
520    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
521
522    /** Permission grant: not grant the permission. */
523    private static final int GRANT_DENIED = 1;
524
525    /** Permission grant: grant the permission as an install permission. */
526    private static final int GRANT_INSTALL = 2;
527
528    /** Permission grant: grant the permission as a runtime one. */
529    private static final int GRANT_RUNTIME = 3;
530
531    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
532    private static final int GRANT_UPGRADE = 4;
533
534    /** Canonical intent used to identify what counts as a "web browser" app */
535    private static final Intent sBrowserIntent;
536    static {
537        sBrowserIntent = new Intent();
538        sBrowserIntent.setAction(Intent.ACTION_VIEW);
539        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
540        sBrowserIntent.setData(Uri.parse("http:"));
541    }
542
543    /**
544     * The set of all protected actions [i.e. those actions for which a high priority
545     * intent filter is disallowed].
546     */
547    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
548    static {
549        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
550        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
551        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
552        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
553    }
554
555    // Compilation reasons.
556    public static final int REASON_FIRST_BOOT = 0;
557    public static final int REASON_BOOT = 1;
558    public static final int REASON_INSTALL = 2;
559    public static final int REASON_BACKGROUND_DEXOPT = 3;
560    public static final int REASON_AB_OTA = 4;
561
562    public static final int REASON_LAST = REASON_AB_OTA;
563
564    /** All dangerous permission names in the same order as the events in MetricsEvent */
565    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
566            Manifest.permission.READ_CALENDAR,
567            Manifest.permission.WRITE_CALENDAR,
568            Manifest.permission.CAMERA,
569            Manifest.permission.READ_CONTACTS,
570            Manifest.permission.WRITE_CONTACTS,
571            Manifest.permission.GET_ACCOUNTS,
572            Manifest.permission.ACCESS_FINE_LOCATION,
573            Manifest.permission.ACCESS_COARSE_LOCATION,
574            Manifest.permission.RECORD_AUDIO,
575            Manifest.permission.READ_PHONE_STATE,
576            Manifest.permission.CALL_PHONE,
577            Manifest.permission.READ_CALL_LOG,
578            Manifest.permission.WRITE_CALL_LOG,
579            Manifest.permission.ADD_VOICEMAIL,
580            Manifest.permission.USE_SIP,
581            Manifest.permission.PROCESS_OUTGOING_CALLS,
582            Manifest.permission.READ_CELL_BROADCASTS,
583            Manifest.permission.BODY_SENSORS,
584            Manifest.permission.SEND_SMS,
585            Manifest.permission.RECEIVE_SMS,
586            Manifest.permission.READ_SMS,
587            Manifest.permission.RECEIVE_WAP_PUSH,
588            Manifest.permission.RECEIVE_MMS,
589            Manifest.permission.READ_EXTERNAL_STORAGE,
590            Manifest.permission.WRITE_EXTERNAL_STORAGE,
591            Manifest.permission.READ_PHONE_NUMBERS,
592            Manifest.permission.ANSWER_PHONE_CALLS);
593
594
595    /**
596     * Version number for the package parser cache. Increment this whenever the format or
597     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
598     */
599    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
600
601    /**
602     * Whether the package parser cache is enabled.
603     */
604    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
605
606    final ServiceThread mHandlerThread;
607
608    final PackageHandler mHandler;
609
610    private final ProcessLoggingHandler mProcessLoggingHandler;
611
612    /**
613     * Messages for {@link #mHandler} that need to wait for system ready before
614     * being dispatched.
615     */
616    private ArrayList<Message> mPostSystemReadyMessages;
617
618    final int mSdkVersion = Build.VERSION.SDK_INT;
619
620    final Context mContext;
621    final boolean mFactoryTest;
622    final boolean mOnlyCore;
623    final DisplayMetrics mMetrics;
624    final int mDefParseFlags;
625    final String[] mSeparateProcesses;
626    final boolean mIsUpgrade;
627    final boolean mIsPreNUpgrade;
628    final boolean mIsPreNMR1Upgrade;
629
630    // Have we told the Activity Manager to whitelist the default container service by uid yet?
631    @GuardedBy("mPackages")
632    boolean mDefaultContainerWhitelisted = false;
633
634    @GuardedBy("mPackages")
635    private boolean mDexOptDialogShown;
636
637    /** The location for ASEC container files on internal storage. */
638    final String mAsecInternalPath;
639
640    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
641    // LOCK HELD.  Can be called with mInstallLock held.
642    @GuardedBy("mInstallLock")
643    final Installer mInstaller;
644
645    /** Directory where installed third-party apps stored */
646    final File mAppInstallDir;
647
648    /**
649     * Directory to which applications installed internally have their
650     * 32 bit native libraries copied.
651     */
652    private File mAppLib32InstallDir;
653
654    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
655    // apps.
656    final File mDrmAppPrivateInstallDir;
657
658    // ----------------------------------------------------------------
659
660    // Lock for state used when installing and doing other long running
661    // operations.  Methods that must be called with this lock held have
662    // the suffix "LI".
663    final Object mInstallLock = new Object();
664
665    // ----------------------------------------------------------------
666
667    // Keys are String (package name), values are Package.  This also serves
668    // as the lock for the global state.  Methods that must be called with
669    // this lock held have the prefix "LP".
670    @GuardedBy("mPackages")
671    final ArrayMap<String, PackageParser.Package> mPackages =
672            new ArrayMap<String, PackageParser.Package>();
673
674    final ArrayMap<String, Set<String>> mKnownCodebase =
675            new ArrayMap<String, Set<String>>();
676
677    // Keys are isolated uids and values are the uid of the application
678    // that created the isolated proccess.
679    @GuardedBy("mPackages")
680    final SparseIntArray mIsolatedOwners = new SparseIntArray();
681
682    /**
683     * Tracks new system packages [received in an OTA] that we expect to
684     * find updated user-installed versions. Keys are package name, values
685     * are package location.
686     */
687    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
688    /**
689     * Tracks high priority intent filters for protected actions. During boot, certain
690     * filter actions are protected and should never be allowed to have a high priority
691     * intent filter for them. However, there is one, and only one exception -- the
692     * setup wizard. It must be able to define a high priority intent filter for these
693     * actions to ensure there are no escapes from the wizard. We need to delay processing
694     * of these during boot as we need to look at all of the system packages in order
695     * to know which component is the setup wizard.
696     */
697    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
698    /**
699     * Whether or not processing protected filters should be deferred.
700     */
701    private boolean mDeferProtectedFilters = true;
702
703    /**
704     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
705     */
706    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
707    /**
708     * Whether or not system app permissions should be promoted from install to runtime.
709     */
710    boolean mPromoteSystemApps;
711
712    @GuardedBy("mPackages")
713    final Settings mSettings;
714
715    /**
716     * Set of package names that are currently "frozen", which means active
717     * surgery is being done on the code/data for that package. The platform
718     * will refuse to launch frozen packages to avoid race conditions.
719     *
720     * @see PackageFreezer
721     */
722    @GuardedBy("mPackages")
723    final ArraySet<String> mFrozenPackages = new ArraySet<>();
724
725    final ProtectedPackages mProtectedPackages;
726
727    boolean mFirstBoot;
728
729    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
730
731    // System configuration read by SystemConfig.
732    final int[] mGlobalGids;
733    final SparseArray<ArraySet<String>> mSystemPermissions;
734    @GuardedBy("mAvailableFeatures")
735    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
736
737    // If mac_permissions.xml was found for seinfo labeling.
738    boolean mFoundPolicyFile;
739
740    private final InstantAppRegistry mInstantAppRegistry;
741
742    @GuardedBy("mPackages")
743    int mChangedPackagesSequenceNumber;
744    /**
745     * List of changed [installed, removed or updated] packages.
746     * mapping from user id -> sequence number -> package name
747     */
748    @GuardedBy("mPackages")
749    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
750    /**
751     * The sequence number of the last change to a package.
752     * mapping from user id -> package name -> sequence number
753     */
754    @GuardedBy("mPackages")
755    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
756
757    class PackageParserCallback implements PackageParser.Callback {
758        @Override public final boolean hasFeature(String feature) {
759            return PackageManagerService.this.hasSystemFeature(feature, 0);
760        }
761
762        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
763                Collection<PackageParser.Package> allPackages, String targetPackageName) {
764            List<PackageParser.Package> overlayPackages = null;
765            for (PackageParser.Package p : allPackages) {
766                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
767                    if (overlayPackages == null) {
768                        overlayPackages = new ArrayList<PackageParser.Package>();
769                    }
770                    overlayPackages.add(p);
771                }
772            }
773            if (overlayPackages != null) {
774                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
775                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
776                        return p1.mOverlayPriority - p2.mOverlayPriority;
777                    }
778                };
779                Collections.sort(overlayPackages, cmp);
780            }
781            return overlayPackages;
782        }
783
784        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
785                String targetPackageName, String targetPath) {
786            if ("android".equals(targetPackageName)) {
787                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
788                // native AssetManager.
789                return null;
790            }
791            List<PackageParser.Package> overlayPackages =
792                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
793            if (overlayPackages == null || overlayPackages.isEmpty()) {
794                return null;
795            }
796            List<String> overlayPathList = null;
797            for (PackageParser.Package overlayPackage : overlayPackages) {
798                if (targetPath == null) {
799                    if (overlayPathList == null) {
800                        overlayPathList = new ArrayList<String>();
801                    }
802                    overlayPathList.add(overlayPackage.baseCodePath);
803                    continue;
804                }
805
806                try {
807                    // Creates idmaps for system to parse correctly the Android manifest of the
808                    // target package.
809                    //
810                    // OverlayManagerService will update each of them with a correct gid from its
811                    // target package app id.
812                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
813                            UserHandle.getSharedAppGid(
814                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
815                    if (overlayPathList == null) {
816                        overlayPathList = new ArrayList<String>();
817                    }
818                    overlayPathList.add(overlayPackage.baseCodePath);
819                } catch (InstallerException e) {
820                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
821                            overlayPackage.baseCodePath);
822                }
823            }
824            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
825        }
826
827        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
828            synchronized (mPackages) {
829                return getStaticOverlayPathsLocked(
830                        mPackages.values(), targetPackageName, targetPath);
831            }
832        }
833
834        @Override public final String[] getOverlayApks(String targetPackageName) {
835            return getStaticOverlayPaths(targetPackageName, null);
836        }
837
838        @Override public final String[] getOverlayPaths(String targetPackageName,
839                String targetPath) {
840            return getStaticOverlayPaths(targetPackageName, targetPath);
841        }
842    };
843
844    class ParallelPackageParserCallback extends PackageParserCallback {
845        List<PackageParser.Package> mOverlayPackages = null;
846
847        void findStaticOverlayPackages() {
848            synchronized (mPackages) {
849                for (PackageParser.Package p : mPackages.values()) {
850                    if (p.mIsStaticOverlay) {
851                        if (mOverlayPackages == null) {
852                            mOverlayPackages = new ArrayList<PackageParser.Package>();
853                        }
854                        mOverlayPackages.add(p);
855                    }
856                }
857            }
858        }
859
860        @Override
861        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
862            // We can trust mOverlayPackages without holding mPackages because package uninstall
863            // can't happen while running parallel parsing.
864            // Moreover holding mPackages on each parsing thread causes dead-lock.
865            return mOverlayPackages == null ? null :
866                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
867        }
868    }
869
870    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
871    final ParallelPackageParserCallback mParallelPackageParserCallback =
872            new ParallelPackageParserCallback();
873
874    public static final class SharedLibraryEntry {
875        public final @Nullable String path;
876        public final @Nullable String apk;
877        public final @NonNull SharedLibraryInfo info;
878
879        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
880                String declaringPackageName, int declaringPackageVersionCode) {
881            path = _path;
882            apk = _apk;
883            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
884                    declaringPackageName, declaringPackageVersionCode), null);
885        }
886    }
887
888    // Currently known shared libraries.
889    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
890    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
891            new ArrayMap<>();
892
893    // All available activities, for your resolving pleasure.
894    final ActivityIntentResolver mActivities =
895            new ActivityIntentResolver();
896
897    // All available receivers, for your resolving pleasure.
898    final ActivityIntentResolver mReceivers =
899            new ActivityIntentResolver();
900
901    // All available services, for your resolving pleasure.
902    final ServiceIntentResolver mServices = new ServiceIntentResolver();
903
904    // All available providers, for your resolving pleasure.
905    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
906
907    // Mapping from provider base names (first directory in content URI codePath)
908    // to the provider information.
909    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
910            new ArrayMap<String, PackageParser.Provider>();
911
912    // Mapping from instrumentation class names to info about them.
913    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
914            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
915
916    // Mapping from permission names to info about them.
917    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
918            new ArrayMap<String, PackageParser.PermissionGroup>();
919
920    // Packages whose data we have transfered into another package, thus
921    // should no longer exist.
922    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
923
924    // Broadcast actions that are only available to the system.
925    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
926
927    /** List of packages waiting for verification. */
928    final SparseArray<PackageVerificationState> mPendingVerification
929            = new SparseArray<PackageVerificationState>();
930
931    /** Set of packages associated with each app op permission. */
932    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
933
934    final PackageInstallerService mInstallerService;
935
936    private final PackageDexOptimizer mPackageDexOptimizer;
937    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
938    // is used by other apps).
939    private final DexManager mDexManager;
940
941    private AtomicInteger mNextMoveId = new AtomicInteger();
942    private final MoveCallbacks mMoveCallbacks;
943
944    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
945
946    // Cache of users who need badging.
947    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
948
949    /** Token for keys in mPendingVerification. */
950    private int mPendingVerificationToken = 0;
951
952    volatile boolean mSystemReady;
953    volatile boolean mSafeMode;
954    volatile boolean mHasSystemUidErrors;
955    private volatile boolean mEphemeralAppsDisabled;
956
957    ApplicationInfo mAndroidApplication;
958    final ActivityInfo mResolveActivity = new ActivityInfo();
959    final ResolveInfo mResolveInfo = new ResolveInfo();
960    ComponentName mResolveComponentName;
961    PackageParser.Package mPlatformPackage;
962    ComponentName mCustomResolverComponentName;
963
964    boolean mResolverReplaced = false;
965
966    private final @Nullable ComponentName mIntentFilterVerifierComponent;
967    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
968
969    private int mIntentFilterVerificationToken = 0;
970
971    /** The service connection to the ephemeral resolver */
972    final EphemeralResolverConnection mInstantAppResolverConnection;
973    /** Component used to show resolver settings for Instant Apps */
974    final ComponentName mInstantAppResolverSettingsComponent;
975
976    /** Activity used to install instant applications */
977    ActivityInfo mInstantAppInstallerActivity;
978    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
979
980    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
981            = new SparseArray<IntentFilterVerificationState>();
982
983    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
984
985    // List of packages names to keep cached, even if they are uninstalled for all users
986    private List<String> mKeepUninstalledPackages;
987
988    private UserManagerInternal mUserManagerInternal;
989
990    private DeviceIdleController.LocalService mDeviceIdleController;
991
992    private File mCacheDir;
993
994    private ArraySet<String> mPrivappPermissionsViolations;
995
996    private Future<?> mPrepareAppDataFuture;
997
998    private static class IFVerificationParams {
999        PackageParser.Package pkg;
1000        boolean replacing;
1001        int userId;
1002        int verifierUid;
1003
1004        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1005                int _userId, int _verifierUid) {
1006            pkg = _pkg;
1007            replacing = _replacing;
1008            userId = _userId;
1009            replacing = _replacing;
1010            verifierUid = _verifierUid;
1011        }
1012    }
1013
1014    private interface IntentFilterVerifier<T extends IntentFilter> {
1015        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1016                                               T filter, String packageName);
1017        void startVerifications(int userId);
1018        void receiveVerificationResponse(int verificationId);
1019    }
1020
1021    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1022        private Context mContext;
1023        private ComponentName mIntentFilterVerifierComponent;
1024        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1025
1026        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1027            mContext = context;
1028            mIntentFilterVerifierComponent = verifierComponent;
1029        }
1030
1031        private String getDefaultScheme() {
1032            return IntentFilter.SCHEME_HTTPS;
1033        }
1034
1035        @Override
1036        public void startVerifications(int userId) {
1037            // Launch verifications requests
1038            int count = mCurrentIntentFilterVerifications.size();
1039            for (int n=0; n<count; n++) {
1040                int verificationId = mCurrentIntentFilterVerifications.get(n);
1041                final IntentFilterVerificationState ivs =
1042                        mIntentFilterVerificationStates.get(verificationId);
1043
1044                String packageName = ivs.getPackageName();
1045
1046                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1047                final int filterCount = filters.size();
1048                ArraySet<String> domainsSet = new ArraySet<>();
1049                for (int m=0; m<filterCount; m++) {
1050                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1051                    domainsSet.addAll(filter.getHostsList());
1052                }
1053                synchronized (mPackages) {
1054                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1055                            packageName, domainsSet) != null) {
1056                        scheduleWriteSettingsLocked();
1057                    }
1058                }
1059                sendVerificationRequest(userId, verificationId, ivs);
1060            }
1061            mCurrentIntentFilterVerifications.clear();
1062        }
1063
1064        private void sendVerificationRequest(int userId, int verificationId,
1065                IntentFilterVerificationState ivs) {
1066
1067            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1068            verificationIntent.putExtra(
1069                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1070                    verificationId);
1071            verificationIntent.putExtra(
1072                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1073                    getDefaultScheme());
1074            verificationIntent.putExtra(
1075                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1076                    ivs.getHostsString());
1077            verificationIntent.putExtra(
1078                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1079                    ivs.getPackageName());
1080            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1081            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1082
1083            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1084            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1085                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1086                    userId, false, "intent filter verifier");
1087
1088            UserHandle user = new UserHandle(userId);
1089            mContext.sendBroadcastAsUser(verificationIntent, user);
1090            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1091                    "Sending IntentFilter verification broadcast");
1092        }
1093
1094        public void receiveVerificationResponse(int verificationId) {
1095            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1096
1097            final boolean verified = ivs.isVerified();
1098
1099            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1100            final int count = filters.size();
1101            if (DEBUG_DOMAIN_VERIFICATION) {
1102                Slog.i(TAG, "Received verification response " + verificationId
1103                        + " for " + count + " filters, verified=" + verified);
1104            }
1105            for (int n=0; n<count; n++) {
1106                PackageParser.ActivityIntentInfo filter = filters.get(n);
1107                filter.setVerified(verified);
1108
1109                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1110                        + " verified with result:" + verified + " and hosts:"
1111                        + ivs.getHostsString());
1112            }
1113
1114            mIntentFilterVerificationStates.remove(verificationId);
1115
1116            final String packageName = ivs.getPackageName();
1117            IntentFilterVerificationInfo ivi = null;
1118
1119            synchronized (mPackages) {
1120                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1121            }
1122            if (ivi == null) {
1123                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1124                        + verificationId + " packageName:" + packageName);
1125                return;
1126            }
1127            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1128                    "Updating IntentFilterVerificationInfo for package " + packageName
1129                            +" verificationId:" + verificationId);
1130
1131            synchronized (mPackages) {
1132                if (verified) {
1133                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1134                } else {
1135                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1136                }
1137                scheduleWriteSettingsLocked();
1138
1139                final int userId = ivs.getUserId();
1140                if (userId != UserHandle.USER_ALL) {
1141                    final int userStatus =
1142                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1143
1144                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1145                    boolean needUpdate = false;
1146
1147                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1148                    // already been set by the User thru the Disambiguation dialog
1149                    switch (userStatus) {
1150                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1151                            if (verified) {
1152                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1153                            } else {
1154                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1155                            }
1156                            needUpdate = true;
1157                            break;
1158
1159                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1160                            if (verified) {
1161                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1162                                needUpdate = true;
1163                            }
1164                            break;
1165
1166                        default:
1167                            // Nothing to do
1168                    }
1169
1170                    if (needUpdate) {
1171                        mSettings.updateIntentFilterVerificationStatusLPw(
1172                                packageName, updatedStatus, userId);
1173                        scheduleWritePackageRestrictionsLocked(userId);
1174                    }
1175                }
1176            }
1177        }
1178
1179        @Override
1180        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1181                    ActivityIntentInfo filter, String packageName) {
1182            if (!hasValidDomains(filter)) {
1183                return false;
1184            }
1185            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1186            if (ivs == null) {
1187                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1188                        packageName);
1189            }
1190            if (DEBUG_DOMAIN_VERIFICATION) {
1191                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1192            }
1193            ivs.addFilter(filter);
1194            return true;
1195        }
1196
1197        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1198                int userId, int verificationId, String packageName) {
1199            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1200                    verifierUid, userId, packageName);
1201            ivs.setPendingState();
1202            synchronized (mPackages) {
1203                mIntentFilterVerificationStates.append(verificationId, ivs);
1204                mCurrentIntentFilterVerifications.add(verificationId);
1205            }
1206            return ivs;
1207        }
1208    }
1209
1210    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1211        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1212                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1213                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1214    }
1215
1216    // Set of pending broadcasts for aggregating enable/disable of components.
1217    static class PendingPackageBroadcasts {
1218        // for each user id, a map of <package name -> components within that package>
1219        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1220
1221        public PendingPackageBroadcasts() {
1222            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1223        }
1224
1225        public ArrayList<String> get(int userId, String packageName) {
1226            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1227            return packages.get(packageName);
1228        }
1229
1230        public void put(int userId, String packageName, ArrayList<String> components) {
1231            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1232            packages.put(packageName, components);
1233        }
1234
1235        public void remove(int userId, String packageName) {
1236            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1237            if (packages != null) {
1238                packages.remove(packageName);
1239            }
1240        }
1241
1242        public void remove(int userId) {
1243            mUidMap.remove(userId);
1244        }
1245
1246        public int userIdCount() {
1247            return mUidMap.size();
1248        }
1249
1250        public int userIdAt(int n) {
1251            return mUidMap.keyAt(n);
1252        }
1253
1254        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1255            return mUidMap.get(userId);
1256        }
1257
1258        public int size() {
1259            // total number of pending broadcast entries across all userIds
1260            int num = 0;
1261            for (int i = 0; i< mUidMap.size(); i++) {
1262                num += mUidMap.valueAt(i).size();
1263            }
1264            return num;
1265        }
1266
1267        public void clear() {
1268            mUidMap.clear();
1269        }
1270
1271        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1272            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1273            if (map == null) {
1274                map = new ArrayMap<String, ArrayList<String>>();
1275                mUidMap.put(userId, map);
1276            }
1277            return map;
1278        }
1279    }
1280    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1281
1282    // Service Connection to remote media container service to copy
1283    // package uri's from external media onto secure containers
1284    // or internal storage.
1285    private IMediaContainerService mContainerService = null;
1286
1287    static final int SEND_PENDING_BROADCAST = 1;
1288    static final int MCS_BOUND = 3;
1289    static final int END_COPY = 4;
1290    static final int INIT_COPY = 5;
1291    static final int MCS_UNBIND = 6;
1292    static final int START_CLEANING_PACKAGE = 7;
1293    static final int FIND_INSTALL_LOC = 8;
1294    static final int POST_INSTALL = 9;
1295    static final int MCS_RECONNECT = 10;
1296    static final int MCS_GIVE_UP = 11;
1297    static final int UPDATED_MEDIA_STATUS = 12;
1298    static final int WRITE_SETTINGS = 13;
1299    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1300    static final int PACKAGE_VERIFIED = 15;
1301    static final int CHECK_PENDING_VERIFICATION = 16;
1302    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1303    static final int INTENT_FILTER_VERIFIED = 18;
1304    static final int WRITE_PACKAGE_LIST = 19;
1305    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1306
1307    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1308
1309    // Delay time in millisecs
1310    static final int BROADCAST_DELAY = 10 * 1000;
1311
1312    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1313            2 * 60 * 60 * 1000L; /* two hours */
1314
1315    static UserManagerService sUserManager;
1316
1317    // Stores a list of users whose package restrictions file needs to be updated
1318    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1319
1320    final private DefaultContainerConnection mDefContainerConn =
1321            new DefaultContainerConnection();
1322    class DefaultContainerConnection implements ServiceConnection {
1323        public void onServiceConnected(ComponentName name, IBinder service) {
1324            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1325            final IMediaContainerService imcs = IMediaContainerService.Stub
1326                    .asInterface(Binder.allowBlocking(service));
1327            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1328        }
1329
1330        public void onServiceDisconnected(ComponentName name) {
1331            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1332        }
1333    }
1334
1335    // Recordkeeping of restore-after-install operations that are currently in flight
1336    // between the Package Manager and the Backup Manager
1337    static class PostInstallData {
1338        public InstallArgs args;
1339        public PackageInstalledInfo res;
1340
1341        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1342            args = _a;
1343            res = _r;
1344        }
1345    }
1346
1347    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1348    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1349
1350    // XML tags for backup/restore of various bits of state
1351    private static final String TAG_PREFERRED_BACKUP = "pa";
1352    private static final String TAG_DEFAULT_APPS = "da";
1353    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1354
1355    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1356    private static final String TAG_ALL_GRANTS = "rt-grants";
1357    private static final String TAG_GRANT = "grant";
1358    private static final String ATTR_PACKAGE_NAME = "pkg";
1359
1360    private static final String TAG_PERMISSION = "perm";
1361    private static final String ATTR_PERMISSION_NAME = "name";
1362    private static final String ATTR_IS_GRANTED = "g";
1363    private static final String ATTR_USER_SET = "set";
1364    private static final String ATTR_USER_FIXED = "fixed";
1365    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1366
1367    // System/policy permission grants are not backed up
1368    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1369            FLAG_PERMISSION_POLICY_FIXED
1370            | FLAG_PERMISSION_SYSTEM_FIXED
1371            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1372
1373    // And we back up these user-adjusted states
1374    private static final int USER_RUNTIME_GRANT_MASK =
1375            FLAG_PERMISSION_USER_SET
1376            | FLAG_PERMISSION_USER_FIXED
1377            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1378
1379    final @Nullable String mRequiredVerifierPackage;
1380    final @NonNull String mRequiredInstallerPackage;
1381    final @NonNull String mRequiredUninstallerPackage;
1382    final @Nullable String mSetupWizardPackage;
1383    final @Nullable String mStorageManagerPackage;
1384    final @NonNull String mServicesSystemSharedLibraryPackageName;
1385    final @NonNull String mSharedSystemSharedLibraryPackageName;
1386
1387    final boolean mPermissionReviewRequired;
1388
1389    private final PackageUsage mPackageUsage = new PackageUsage();
1390    private final CompilerStats mCompilerStats = new CompilerStats();
1391
1392    class PackageHandler extends Handler {
1393        private boolean mBound = false;
1394        final ArrayList<HandlerParams> mPendingInstalls =
1395            new ArrayList<HandlerParams>();
1396
1397        private boolean connectToService() {
1398            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1399                    " DefaultContainerService");
1400            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1401            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1402            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1403                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1404                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1405                mBound = true;
1406                return true;
1407            }
1408            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1409            return false;
1410        }
1411
1412        private void disconnectService() {
1413            mContainerService = null;
1414            mBound = false;
1415            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1416            mContext.unbindService(mDefContainerConn);
1417            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1418        }
1419
1420        PackageHandler(Looper looper) {
1421            super(looper);
1422        }
1423
1424        public void handleMessage(Message msg) {
1425            try {
1426                doHandleMessage(msg);
1427            } finally {
1428                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1429            }
1430        }
1431
1432        void doHandleMessage(Message msg) {
1433            switch (msg.what) {
1434                case INIT_COPY: {
1435                    HandlerParams params = (HandlerParams) msg.obj;
1436                    int idx = mPendingInstalls.size();
1437                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1438                    // If a bind was already initiated we dont really
1439                    // need to do anything. The pending install
1440                    // will be processed later on.
1441                    if (!mBound) {
1442                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1443                                System.identityHashCode(mHandler));
1444                        // If this is the only one pending we might
1445                        // have to bind to the service again.
1446                        if (!connectToService()) {
1447                            Slog.e(TAG, "Failed to bind to media container service");
1448                            params.serviceError();
1449                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1450                                    System.identityHashCode(mHandler));
1451                            if (params.traceMethod != null) {
1452                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1453                                        params.traceCookie);
1454                            }
1455                            return;
1456                        } else {
1457                            // Once we bind to the service, the first
1458                            // pending request will be processed.
1459                            mPendingInstalls.add(idx, params);
1460                        }
1461                    } else {
1462                        mPendingInstalls.add(idx, params);
1463                        // Already bound to the service. Just make
1464                        // sure we trigger off processing the first request.
1465                        if (idx == 0) {
1466                            mHandler.sendEmptyMessage(MCS_BOUND);
1467                        }
1468                    }
1469                    break;
1470                }
1471                case MCS_BOUND: {
1472                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1473                    if (msg.obj != null) {
1474                        mContainerService = (IMediaContainerService) msg.obj;
1475                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1476                                System.identityHashCode(mHandler));
1477                    }
1478                    if (mContainerService == null) {
1479                        if (!mBound) {
1480                            // Something seriously wrong since we are not bound and we are not
1481                            // waiting for connection. Bail out.
1482                            Slog.e(TAG, "Cannot bind to media container service");
1483                            for (HandlerParams params : mPendingInstalls) {
1484                                // Indicate service bind error
1485                                params.serviceError();
1486                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1487                                        System.identityHashCode(params));
1488                                if (params.traceMethod != null) {
1489                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1490                                            params.traceMethod, params.traceCookie);
1491                                }
1492                                return;
1493                            }
1494                            mPendingInstalls.clear();
1495                        } else {
1496                            Slog.w(TAG, "Waiting to connect to media container service");
1497                        }
1498                    } else if (mPendingInstalls.size() > 0) {
1499                        HandlerParams params = mPendingInstalls.get(0);
1500                        if (params != null) {
1501                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1502                                    System.identityHashCode(params));
1503                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1504                            if (params.startCopy()) {
1505                                // We are done...  look for more work or to
1506                                // go idle.
1507                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1508                                        "Checking for more work or unbind...");
1509                                // Delete pending install
1510                                if (mPendingInstalls.size() > 0) {
1511                                    mPendingInstalls.remove(0);
1512                                }
1513                                if (mPendingInstalls.size() == 0) {
1514                                    if (mBound) {
1515                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1516                                                "Posting delayed MCS_UNBIND");
1517                                        removeMessages(MCS_UNBIND);
1518                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1519                                        // Unbind after a little delay, to avoid
1520                                        // continual thrashing.
1521                                        sendMessageDelayed(ubmsg, 10000);
1522                                    }
1523                                } else {
1524                                    // There are more pending requests in queue.
1525                                    // Just post MCS_BOUND message to trigger processing
1526                                    // of next pending install.
1527                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1528                                            "Posting MCS_BOUND for next work");
1529                                    mHandler.sendEmptyMessage(MCS_BOUND);
1530                                }
1531                            }
1532                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1533                        }
1534                    } else {
1535                        // Should never happen ideally.
1536                        Slog.w(TAG, "Empty queue");
1537                    }
1538                    break;
1539                }
1540                case MCS_RECONNECT: {
1541                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1542                    if (mPendingInstalls.size() > 0) {
1543                        if (mBound) {
1544                            disconnectService();
1545                        }
1546                        if (!connectToService()) {
1547                            Slog.e(TAG, "Failed to bind to media container service");
1548                            for (HandlerParams params : mPendingInstalls) {
1549                                // Indicate service bind error
1550                                params.serviceError();
1551                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1552                                        System.identityHashCode(params));
1553                            }
1554                            mPendingInstalls.clear();
1555                        }
1556                    }
1557                    break;
1558                }
1559                case MCS_UNBIND: {
1560                    // If there is no actual work left, then time to unbind.
1561                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1562
1563                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1564                        if (mBound) {
1565                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1566
1567                            disconnectService();
1568                        }
1569                    } else if (mPendingInstalls.size() > 0) {
1570                        // There are more pending requests in queue.
1571                        // Just post MCS_BOUND message to trigger processing
1572                        // of next pending install.
1573                        mHandler.sendEmptyMessage(MCS_BOUND);
1574                    }
1575
1576                    break;
1577                }
1578                case MCS_GIVE_UP: {
1579                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1580                    HandlerParams params = mPendingInstalls.remove(0);
1581                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1582                            System.identityHashCode(params));
1583                    break;
1584                }
1585                case SEND_PENDING_BROADCAST: {
1586                    String packages[];
1587                    ArrayList<String> components[];
1588                    int size = 0;
1589                    int uids[];
1590                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1591                    synchronized (mPackages) {
1592                        if (mPendingBroadcasts == null) {
1593                            return;
1594                        }
1595                        size = mPendingBroadcasts.size();
1596                        if (size <= 0) {
1597                            // Nothing to be done. Just return
1598                            return;
1599                        }
1600                        packages = new String[size];
1601                        components = new ArrayList[size];
1602                        uids = new int[size];
1603                        int i = 0;  // filling out the above arrays
1604
1605                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1606                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1607                            Iterator<Map.Entry<String, ArrayList<String>>> it
1608                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1609                                            .entrySet().iterator();
1610                            while (it.hasNext() && i < size) {
1611                                Map.Entry<String, ArrayList<String>> ent = it.next();
1612                                packages[i] = ent.getKey();
1613                                components[i] = ent.getValue();
1614                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1615                                uids[i] = (ps != null)
1616                                        ? UserHandle.getUid(packageUserId, ps.appId)
1617                                        : -1;
1618                                i++;
1619                            }
1620                        }
1621                        size = i;
1622                        mPendingBroadcasts.clear();
1623                    }
1624                    // Send broadcasts
1625                    for (int i = 0; i < size; i++) {
1626                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1627                    }
1628                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1629                    break;
1630                }
1631                case START_CLEANING_PACKAGE: {
1632                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1633                    final String packageName = (String)msg.obj;
1634                    final int userId = msg.arg1;
1635                    final boolean andCode = msg.arg2 != 0;
1636                    synchronized (mPackages) {
1637                        if (userId == UserHandle.USER_ALL) {
1638                            int[] users = sUserManager.getUserIds();
1639                            for (int user : users) {
1640                                mSettings.addPackageToCleanLPw(
1641                                        new PackageCleanItem(user, packageName, andCode));
1642                            }
1643                        } else {
1644                            mSettings.addPackageToCleanLPw(
1645                                    new PackageCleanItem(userId, packageName, andCode));
1646                        }
1647                    }
1648                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1649                    startCleaningPackages();
1650                } break;
1651                case POST_INSTALL: {
1652                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1653
1654                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1655                    final boolean didRestore = (msg.arg2 != 0);
1656                    mRunningInstalls.delete(msg.arg1);
1657
1658                    if (data != null) {
1659                        InstallArgs args = data.args;
1660                        PackageInstalledInfo parentRes = data.res;
1661
1662                        final boolean grantPermissions = (args.installFlags
1663                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1664                        final boolean killApp = (args.installFlags
1665                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1666                        final String[] grantedPermissions = args.installGrantPermissions;
1667
1668                        // Handle the parent package
1669                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1670                                grantedPermissions, didRestore, args.installerPackageName,
1671                                args.observer);
1672
1673                        // Handle the child packages
1674                        final int childCount = (parentRes.addedChildPackages != null)
1675                                ? parentRes.addedChildPackages.size() : 0;
1676                        for (int i = 0; i < childCount; i++) {
1677                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1678                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1679                                    grantedPermissions, false, args.installerPackageName,
1680                                    args.observer);
1681                        }
1682
1683                        // Log tracing if needed
1684                        if (args.traceMethod != null) {
1685                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1686                                    args.traceCookie);
1687                        }
1688                    } else {
1689                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1690                    }
1691
1692                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1693                } break;
1694                case UPDATED_MEDIA_STATUS: {
1695                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1696                    boolean reportStatus = msg.arg1 == 1;
1697                    boolean doGc = msg.arg2 == 1;
1698                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1699                    if (doGc) {
1700                        // Force a gc to clear up stale containers.
1701                        Runtime.getRuntime().gc();
1702                    }
1703                    if (msg.obj != null) {
1704                        @SuppressWarnings("unchecked")
1705                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1706                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1707                        // Unload containers
1708                        unloadAllContainers(args);
1709                    }
1710                    if (reportStatus) {
1711                        try {
1712                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1713                                    "Invoking StorageManagerService call back");
1714                            PackageHelper.getStorageManager().finishMediaUpdate();
1715                        } catch (RemoteException e) {
1716                            Log.e(TAG, "StorageManagerService not running?");
1717                        }
1718                    }
1719                } break;
1720                case WRITE_SETTINGS: {
1721                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1722                    synchronized (mPackages) {
1723                        removeMessages(WRITE_SETTINGS);
1724                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1725                        mSettings.writeLPr();
1726                        mDirtyUsers.clear();
1727                    }
1728                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1729                } break;
1730                case WRITE_PACKAGE_RESTRICTIONS: {
1731                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1732                    synchronized (mPackages) {
1733                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1734                        for (int userId : mDirtyUsers) {
1735                            mSettings.writePackageRestrictionsLPr(userId);
1736                        }
1737                        mDirtyUsers.clear();
1738                    }
1739                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1740                } break;
1741                case WRITE_PACKAGE_LIST: {
1742                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1743                    synchronized (mPackages) {
1744                        removeMessages(WRITE_PACKAGE_LIST);
1745                        mSettings.writePackageListLPr(msg.arg1);
1746                    }
1747                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1748                } break;
1749                case CHECK_PENDING_VERIFICATION: {
1750                    final int verificationId = msg.arg1;
1751                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1752
1753                    if ((state != null) && !state.timeoutExtended()) {
1754                        final InstallArgs args = state.getInstallArgs();
1755                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1756
1757                        Slog.i(TAG, "Verification timed out for " + originUri);
1758                        mPendingVerification.remove(verificationId);
1759
1760                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1761
1762                        final UserHandle user = args.getUser();
1763                        if (getDefaultVerificationResponse(user)
1764                                == PackageManager.VERIFICATION_ALLOW) {
1765                            Slog.i(TAG, "Continuing with installation of " + originUri);
1766                            state.setVerifierResponse(Binder.getCallingUid(),
1767                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1768                            broadcastPackageVerified(verificationId, originUri,
1769                                    PackageManager.VERIFICATION_ALLOW, user);
1770                            try {
1771                                ret = args.copyApk(mContainerService, true);
1772                            } catch (RemoteException e) {
1773                                Slog.e(TAG, "Could not contact the ContainerService");
1774                            }
1775                        } else {
1776                            broadcastPackageVerified(verificationId, originUri,
1777                                    PackageManager.VERIFICATION_REJECT, user);
1778                        }
1779
1780                        Trace.asyncTraceEnd(
1781                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1782
1783                        processPendingInstall(args, ret);
1784                        mHandler.sendEmptyMessage(MCS_UNBIND);
1785                    }
1786                    break;
1787                }
1788                case PACKAGE_VERIFIED: {
1789                    final int verificationId = msg.arg1;
1790
1791                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1792                    if (state == null) {
1793                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1794                        break;
1795                    }
1796
1797                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1798
1799                    state.setVerifierResponse(response.callerUid, response.code);
1800
1801                    if (state.isVerificationComplete()) {
1802                        mPendingVerification.remove(verificationId);
1803
1804                        final InstallArgs args = state.getInstallArgs();
1805                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1806
1807                        int ret;
1808                        if (state.isInstallAllowed()) {
1809                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1810                            broadcastPackageVerified(verificationId, originUri,
1811                                    response.code, state.getInstallArgs().getUser());
1812                            try {
1813                                ret = args.copyApk(mContainerService, true);
1814                            } catch (RemoteException e) {
1815                                Slog.e(TAG, "Could not contact the ContainerService");
1816                            }
1817                        } else {
1818                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1819                        }
1820
1821                        Trace.asyncTraceEnd(
1822                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1823
1824                        processPendingInstall(args, ret);
1825                        mHandler.sendEmptyMessage(MCS_UNBIND);
1826                    }
1827
1828                    break;
1829                }
1830                case START_INTENT_FILTER_VERIFICATIONS: {
1831                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1832                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1833                            params.replacing, params.pkg);
1834                    break;
1835                }
1836                case INTENT_FILTER_VERIFIED: {
1837                    final int verificationId = msg.arg1;
1838
1839                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1840                            verificationId);
1841                    if (state == null) {
1842                        Slog.w(TAG, "Invalid IntentFilter verification token "
1843                                + verificationId + " received");
1844                        break;
1845                    }
1846
1847                    final int userId = state.getUserId();
1848
1849                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1850                            "Processing IntentFilter verification with token:"
1851                            + verificationId + " and userId:" + userId);
1852
1853                    final IntentFilterVerificationResponse response =
1854                            (IntentFilterVerificationResponse) msg.obj;
1855
1856                    state.setVerifierResponse(response.callerUid, response.code);
1857
1858                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1859                            "IntentFilter verification with token:" + verificationId
1860                            + " and userId:" + userId
1861                            + " is settings verifier response with response code:"
1862                            + response.code);
1863
1864                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1865                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1866                                + response.getFailedDomainsString());
1867                    }
1868
1869                    if (state.isVerificationComplete()) {
1870                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1871                    } else {
1872                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1873                                "IntentFilter verification with token:" + verificationId
1874                                + " was not said to be complete");
1875                    }
1876
1877                    break;
1878                }
1879                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1880                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1881                            mInstantAppResolverConnection,
1882                            (InstantAppRequest) msg.obj,
1883                            mInstantAppInstallerActivity,
1884                            mHandler);
1885                }
1886            }
1887        }
1888    }
1889
1890    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1891            boolean killApp, String[] grantedPermissions,
1892            boolean launchedForRestore, String installerPackage,
1893            IPackageInstallObserver2 installObserver) {
1894        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1895            // Send the removed broadcasts
1896            if (res.removedInfo != null) {
1897                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1898            }
1899
1900            // Now that we successfully installed the package, grant runtime
1901            // permissions if requested before broadcasting the install. Also
1902            // for legacy apps in permission review mode we clear the permission
1903            // review flag which is used to emulate runtime permissions for
1904            // legacy apps.
1905            if (grantPermissions) {
1906                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1907            }
1908
1909            final boolean update = res.removedInfo != null
1910                    && res.removedInfo.removedPackage != null;
1911            final String origInstallerPackageName = res.removedInfo != null
1912                    ? res.removedInfo.installerPackageName : null;
1913
1914            // If this is the first time we have child packages for a disabled privileged
1915            // app that had no children, we grant requested runtime permissions to the new
1916            // children if the parent on the system image had them already granted.
1917            if (res.pkg.parentPackage != null) {
1918                synchronized (mPackages) {
1919                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1920                }
1921            }
1922
1923            synchronized (mPackages) {
1924                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1925            }
1926
1927            final String packageName = res.pkg.applicationInfo.packageName;
1928
1929            // Determine the set of users who are adding this package for
1930            // the first time vs. those who are seeing an update.
1931            int[] firstUsers = EMPTY_INT_ARRAY;
1932            int[] updateUsers = EMPTY_INT_ARRAY;
1933            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1934            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1935            for (int newUser : res.newUsers) {
1936                if (ps.getInstantApp(newUser)) {
1937                    continue;
1938                }
1939                if (allNewUsers) {
1940                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1941                    continue;
1942                }
1943                boolean isNew = true;
1944                for (int origUser : res.origUsers) {
1945                    if (origUser == newUser) {
1946                        isNew = false;
1947                        break;
1948                    }
1949                }
1950                if (isNew) {
1951                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1952                } else {
1953                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1954                }
1955            }
1956
1957            // Send installed broadcasts if the package is not a static shared lib.
1958            if (res.pkg.staticSharedLibName == null) {
1959                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1960
1961                // Send added for users that see the package for the first time
1962                // sendPackageAddedForNewUsers also deals with system apps
1963                int appId = UserHandle.getAppId(res.uid);
1964                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1965                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1966
1967                // Send added for users that don't see the package for the first time
1968                Bundle extras = new Bundle(1);
1969                extras.putInt(Intent.EXTRA_UID, res.uid);
1970                if (update) {
1971                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1972                }
1973                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1974                        extras, 0 /*flags*/,
1975                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1976                if (origInstallerPackageName != null) {
1977                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1978                            extras, 0 /*flags*/,
1979                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1980                }
1981
1982                // Send replaced for users that don't see the package for the first time
1983                if (update) {
1984                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1985                            packageName, extras, 0 /*flags*/,
1986                            null /*targetPackage*/, null /*finishedReceiver*/,
1987                            updateUsers);
1988                    if (origInstallerPackageName != null) {
1989                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1990                                extras, 0 /*flags*/,
1991                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1992                    }
1993                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1994                            null /*package*/, null /*extras*/, 0 /*flags*/,
1995                            packageName /*targetPackage*/,
1996                            null /*finishedReceiver*/, updateUsers);
1997                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1998                    // First-install and we did a restore, so we're responsible for the
1999                    // first-launch broadcast.
2000                    if (DEBUG_BACKUP) {
2001                        Slog.i(TAG, "Post-restore of " + packageName
2002                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2003                    }
2004                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2005                }
2006
2007                // Send broadcast package appeared if forward locked/external for all users
2008                // treat asec-hosted packages like removable media on upgrade
2009                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2010                    if (DEBUG_INSTALL) {
2011                        Slog.i(TAG, "upgrading pkg " + res.pkg
2012                                + " is ASEC-hosted -> AVAILABLE");
2013                    }
2014                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2015                    ArrayList<String> pkgList = new ArrayList<>(1);
2016                    pkgList.add(packageName);
2017                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2018                }
2019            }
2020
2021            // Work that needs to happen on first install within each user
2022            if (firstUsers != null && firstUsers.length > 0) {
2023                synchronized (mPackages) {
2024                    for (int userId : firstUsers) {
2025                        // If this app is a browser and it's newly-installed for some
2026                        // users, clear any default-browser state in those users. The
2027                        // app's nature doesn't depend on the user, so we can just check
2028                        // its browser nature in any user and generalize.
2029                        if (packageIsBrowser(packageName, userId)) {
2030                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2031                        }
2032
2033                        // We may also need to apply pending (restored) runtime
2034                        // permission grants within these users.
2035                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2036                    }
2037                }
2038            }
2039
2040            // Log current value of "unknown sources" setting
2041            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2042                    getUnknownSourcesSettings());
2043
2044            // Remove the replaced package's older resources safely now
2045            // We delete after a gc for applications  on sdcard.
2046            if (res.removedInfo != null && res.removedInfo.args != null) {
2047                Runtime.getRuntime().gc();
2048                synchronized (mInstallLock) {
2049                    res.removedInfo.args.doPostDeleteLI(true);
2050                }
2051            } else {
2052                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2053                // and not block here.
2054                VMRuntime.getRuntime().requestConcurrentGC();
2055            }
2056
2057            // Notify DexManager that the package was installed for new users.
2058            // The updated users should already be indexed and the package code paths
2059            // should not change.
2060            // Don't notify the manager for ephemeral apps as they are not expected to
2061            // survive long enough to benefit of background optimizations.
2062            for (int userId : firstUsers) {
2063                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2064                // There's a race currently where some install events may interleave with an uninstall.
2065                // This can lead to package info being null (b/36642664).
2066                if (info != null) {
2067                    mDexManager.notifyPackageInstalled(info, userId);
2068                }
2069            }
2070        }
2071
2072        // If someone is watching installs - notify them
2073        if (installObserver != null) {
2074            try {
2075                Bundle extras = extrasForInstallResult(res);
2076                installObserver.onPackageInstalled(res.name, res.returnCode,
2077                        res.returnMsg, extras);
2078            } catch (RemoteException e) {
2079                Slog.i(TAG, "Observer no longer exists.");
2080            }
2081        }
2082    }
2083
2084    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2085            PackageParser.Package pkg) {
2086        if (pkg.parentPackage == null) {
2087            return;
2088        }
2089        if (pkg.requestedPermissions == null) {
2090            return;
2091        }
2092        final PackageSetting disabledSysParentPs = mSettings
2093                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2094        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2095                || !disabledSysParentPs.isPrivileged()
2096                || (disabledSysParentPs.childPackageNames != null
2097                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2098            return;
2099        }
2100        final int[] allUserIds = sUserManager.getUserIds();
2101        final int permCount = pkg.requestedPermissions.size();
2102        for (int i = 0; i < permCount; i++) {
2103            String permission = pkg.requestedPermissions.get(i);
2104            BasePermission bp = mSettings.mPermissions.get(permission);
2105            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2106                continue;
2107            }
2108            for (int userId : allUserIds) {
2109                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2110                        permission, userId)) {
2111                    grantRuntimePermission(pkg.packageName, permission, userId);
2112                }
2113            }
2114        }
2115    }
2116
2117    private StorageEventListener mStorageListener = new StorageEventListener() {
2118        @Override
2119        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2120            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2121                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2122                    final String volumeUuid = vol.getFsUuid();
2123
2124                    // Clean up any users or apps that were removed or recreated
2125                    // while this volume was missing
2126                    sUserManager.reconcileUsers(volumeUuid);
2127                    reconcileApps(volumeUuid);
2128
2129                    // Clean up any install sessions that expired or were
2130                    // cancelled while this volume was missing
2131                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2132
2133                    loadPrivatePackages(vol);
2134
2135                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2136                    unloadPrivatePackages(vol);
2137                }
2138            }
2139
2140            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2141                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2142                    updateExternalMediaStatus(true, false);
2143                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2144                    updateExternalMediaStatus(false, false);
2145                }
2146            }
2147        }
2148
2149        @Override
2150        public void onVolumeForgotten(String fsUuid) {
2151            if (TextUtils.isEmpty(fsUuid)) {
2152                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2153                return;
2154            }
2155
2156            // Remove any apps installed on the forgotten volume
2157            synchronized (mPackages) {
2158                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2159                for (PackageSetting ps : packages) {
2160                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2161                    deletePackageVersioned(new VersionedPackage(ps.name,
2162                            PackageManager.VERSION_CODE_HIGHEST),
2163                            new LegacyPackageDeleteObserver(null).getBinder(),
2164                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2165                    // Try very hard to release any references to this package
2166                    // so we don't risk the system server being killed due to
2167                    // open FDs
2168                    AttributeCache.instance().removePackage(ps.name);
2169                }
2170
2171                mSettings.onVolumeForgotten(fsUuid);
2172                mSettings.writeLPr();
2173            }
2174        }
2175    };
2176
2177    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2178            String[] grantedPermissions) {
2179        for (int userId : userIds) {
2180            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2181        }
2182    }
2183
2184    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2185            String[] grantedPermissions) {
2186        PackageSetting ps = (PackageSetting) pkg.mExtras;
2187        if (ps == null) {
2188            return;
2189        }
2190
2191        PermissionsState permissionsState = ps.getPermissionsState();
2192
2193        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2194                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2195
2196        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2197                >= Build.VERSION_CODES.M;
2198
2199        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2200
2201        for (String permission : pkg.requestedPermissions) {
2202            final BasePermission bp;
2203            synchronized (mPackages) {
2204                bp = mSettings.mPermissions.get(permission);
2205            }
2206            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2207                    && (!instantApp || bp.isInstant())
2208                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2209                    && (grantedPermissions == null
2210                           || ArrayUtils.contains(grantedPermissions, permission))) {
2211                final int flags = permissionsState.getPermissionFlags(permission, userId);
2212                if (supportsRuntimePermissions) {
2213                    // Installer cannot change immutable permissions.
2214                    if ((flags & immutableFlags) == 0) {
2215                        grantRuntimePermission(pkg.packageName, permission, userId);
2216                    }
2217                } else if (mPermissionReviewRequired) {
2218                    // In permission review mode we clear the review flag when we
2219                    // are asked to install the app with all permissions granted.
2220                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2221                        updatePermissionFlags(permission, pkg.packageName,
2222                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2223                    }
2224                }
2225            }
2226        }
2227    }
2228
2229    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2230        Bundle extras = null;
2231        switch (res.returnCode) {
2232            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2233                extras = new Bundle();
2234                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2235                        res.origPermission);
2236                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2237                        res.origPackage);
2238                break;
2239            }
2240            case PackageManager.INSTALL_SUCCEEDED: {
2241                extras = new Bundle();
2242                extras.putBoolean(Intent.EXTRA_REPLACING,
2243                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2244                break;
2245            }
2246        }
2247        return extras;
2248    }
2249
2250    void scheduleWriteSettingsLocked() {
2251        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2252            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2253        }
2254    }
2255
2256    void scheduleWritePackageListLocked(int userId) {
2257        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2258            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2259            msg.arg1 = userId;
2260            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2261        }
2262    }
2263
2264    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2265        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2266        scheduleWritePackageRestrictionsLocked(userId);
2267    }
2268
2269    void scheduleWritePackageRestrictionsLocked(int userId) {
2270        final int[] userIds = (userId == UserHandle.USER_ALL)
2271                ? sUserManager.getUserIds() : new int[]{userId};
2272        for (int nextUserId : userIds) {
2273            if (!sUserManager.exists(nextUserId)) return;
2274            mDirtyUsers.add(nextUserId);
2275            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2276                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2277            }
2278        }
2279    }
2280
2281    public static PackageManagerService main(Context context, Installer installer,
2282            boolean factoryTest, boolean onlyCore) {
2283        // Self-check for initial settings.
2284        PackageManagerServiceCompilerMapping.checkProperties();
2285
2286        PackageManagerService m = new PackageManagerService(context, installer,
2287                factoryTest, onlyCore);
2288        m.enableSystemUserPackages();
2289        ServiceManager.addService("package", m);
2290        return m;
2291    }
2292
2293    private void enableSystemUserPackages() {
2294        if (!UserManager.isSplitSystemUser()) {
2295            return;
2296        }
2297        // For system user, enable apps based on the following conditions:
2298        // - app is whitelisted or belong to one of these groups:
2299        //   -- system app which has no launcher icons
2300        //   -- system app which has INTERACT_ACROSS_USERS permission
2301        //   -- system IME app
2302        // - app is not in the blacklist
2303        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2304        Set<String> enableApps = new ArraySet<>();
2305        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2306                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2307                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2308        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2309        enableApps.addAll(wlApps);
2310        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2311                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2312        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2313        enableApps.removeAll(blApps);
2314        Log.i(TAG, "Applications installed for system user: " + enableApps);
2315        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2316                UserHandle.SYSTEM);
2317        final int allAppsSize = allAps.size();
2318        synchronized (mPackages) {
2319            for (int i = 0; i < allAppsSize; i++) {
2320                String pName = allAps.get(i);
2321                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2322                // Should not happen, but we shouldn't be failing if it does
2323                if (pkgSetting == null) {
2324                    continue;
2325                }
2326                boolean install = enableApps.contains(pName);
2327                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2328                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2329                            + " for system user");
2330                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2331                }
2332            }
2333            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2334        }
2335    }
2336
2337    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2338        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2339                Context.DISPLAY_SERVICE);
2340        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2341    }
2342
2343    /**
2344     * Requests that files preopted on a secondary system partition be copied to the data partition
2345     * if possible.  Note that the actual copying of the files is accomplished by init for security
2346     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2347     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2348     */
2349    private static void requestCopyPreoptedFiles() {
2350        final int WAIT_TIME_MS = 100;
2351        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2352        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2353            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2354            // We will wait for up to 100 seconds.
2355            final long timeStart = SystemClock.uptimeMillis();
2356            final long timeEnd = timeStart + 100 * 1000;
2357            long timeNow = timeStart;
2358            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2359                try {
2360                    Thread.sleep(WAIT_TIME_MS);
2361                } catch (InterruptedException e) {
2362                    // Do nothing
2363                }
2364                timeNow = SystemClock.uptimeMillis();
2365                if (timeNow > timeEnd) {
2366                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2367                    Slog.wtf(TAG, "cppreopt did not finish!");
2368                    break;
2369                }
2370            }
2371
2372            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2373        }
2374    }
2375
2376    public PackageManagerService(Context context, Installer installer,
2377            boolean factoryTest, boolean onlyCore) {
2378        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2379        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2380        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2381                SystemClock.uptimeMillis());
2382
2383        if (mSdkVersion <= 0) {
2384            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2385        }
2386
2387        mContext = context;
2388
2389        mPermissionReviewRequired = context.getResources().getBoolean(
2390                R.bool.config_permissionReviewRequired);
2391
2392        mFactoryTest = factoryTest;
2393        mOnlyCore = onlyCore;
2394        mMetrics = new DisplayMetrics();
2395        mSettings = new Settings(mPackages);
2396        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2397                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2398        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2399                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2400        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2401                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2402        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2407                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2408
2409        String separateProcesses = SystemProperties.get("debug.separate_processes");
2410        if (separateProcesses != null && separateProcesses.length() > 0) {
2411            if ("*".equals(separateProcesses)) {
2412                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2413                mSeparateProcesses = null;
2414                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2415            } else {
2416                mDefParseFlags = 0;
2417                mSeparateProcesses = separateProcesses.split(",");
2418                Slog.w(TAG, "Running with debug.separate_processes: "
2419                        + separateProcesses);
2420            }
2421        } else {
2422            mDefParseFlags = 0;
2423            mSeparateProcesses = null;
2424        }
2425
2426        mInstaller = installer;
2427        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2428                "*dexopt*");
2429        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2430        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2431
2432        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2433                FgThread.get().getLooper());
2434
2435        getDefaultDisplayMetrics(context, mMetrics);
2436
2437        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2438        SystemConfig systemConfig = SystemConfig.getInstance();
2439        mGlobalGids = systemConfig.getGlobalGids();
2440        mSystemPermissions = systemConfig.getSystemPermissions();
2441        mAvailableFeatures = systemConfig.getAvailableFeatures();
2442        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2443
2444        mProtectedPackages = new ProtectedPackages(mContext);
2445
2446        synchronized (mInstallLock) {
2447        // writer
2448        synchronized (mPackages) {
2449            mHandlerThread = new ServiceThread(TAG,
2450                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2451            mHandlerThread.start();
2452            mHandler = new PackageHandler(mHandlerThread.getLooper());
2453            mProcessLoggingHandler = new ProcessLoggingHandler();
2454            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2455
2456            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2457            mInstantAppRegistry = new InstantAppRegistry(this);
2458
2459            File dataDir = Environment.getDataDirectory();
2460            mAppInstallDir = new File(dataDir, "app");
2461            mAppLib32InstallDir = new File(dataDir, "app-lib");
2462            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2463            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2464            sUserManager = new UserManagerService(context, this,
2465                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2466
2467            // Propagate permission configuration in to package manager.
2468            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2469                    = systemConfig.getPermissions();
2470            for (int i=0; i<permConfig.size(); i++) {
2471                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2472                BasePermission bp = mSettings.mPermissions.get(perm.name);
2473                if (bp == null) {
2474                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2475                    mSettings.mPermissions.put(perm.name, bp);
2476                }
2477                if (perm.gids != null) {
2478                    bp.setGids(perm.gids, perm.perUser);
2479                }
2480            }
2481
2482            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2483            final int builtInLibCount = libConfig.size();
2484            for (int i = 0; i < builtInLibCount; i++) {
2485                String name = libConfig.keyAt(i);
2486                String path = libConfig.valueAt(i);
2487                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2488                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2489            }
2490
2491            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2492
2493            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2494            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2495            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2496
2497            // Clean up orphaned packages for which the code path doesn't exist
2498            // and they are an update to a system app - caused by bug/32321269
2499            final int packageSettingCount = mSettings.mPackages.size();
2500            for (int i = packageSettingCount - 1; i >= 0; i--) {
2501                PackageSetting ps = mSettings.mPackages.valueAt(i);
2502                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2503                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2504                    mSettings.mPackages.removeAt(i);
2505                    mSettings.enableSystemPackageLPw(ps.name);
2506                }
2507            }
2508
2509            if (mFirstBoot) {
2510                requestCopyPreoptedFiles();
2511            }
2512
2513            String customResolverActivity = Resources.getSystem().getString(
2514                    R.string.config_customResolverActivity);
2515            if (TextUtils.isEmpty(customResolverActivity)) {
2516                customResolverActivity = null;
2517            } else {
2518                mCustomResolverComponentName = ComponentName.unflattenFromString(
2519                        customResolverActivity);
2520            }
2521
2522            long startTime = SystemClock.uptimeMillis();
2523
2524            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2525                    startTime);
2526
2527            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2528            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2529
2530            if (bootClassPath == null) {
2531                Slog.w(TAG, "No BOOTCLASSPATH found!");
2532            }
2533
2534            if (systemServerClassPath == null) {
2535                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2536            }
2537
2538            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2539
2540            final VersionInfo ver = mSettings.getInternalVersion();
2541            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2542            if (mIsUpgrade) {
2543                logCriticalInfo(Log.INFO,
2544                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2545            }
2546
2547            // when upgrading from pre-M, promote system app permissions from install to runtime
2548            mPromoteSystemApps =
2549                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2550
2551            // When upgrading from pre-N, we need to handle package extraction like first boot,
2552            // as there is no profiling data available.
2553            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2554
2555            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2556
2557            // save off the names of pre-existing system packages prior to scanning; we don't
2558            // want to automatically grant runtime permissions for new system apps
2559            if (mPromoteSystemApps) {
2560                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2561                while (pkgSettingIter.hasNext()) {
2562                    PackageSetting ps = pkgSettingIter.next();
2563                    if (isSystemApp(ps)) {
2564                        mExistingSystemPackages.add(ps.name);
2565                    }
2566                }
2567            }
2568
2569            mCacheDir = preparePackageParserCache(mIsUpgrade);
2570
2571            // Set flag to monitor and not change apk file paths when
2572            // scanning install directories.
2573            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2574
2575            if (mIsUpgrade || mFirstBoot) {
2576                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2577            }
2578
2579            // Collect vendor overlay packages. (Do this before scanning any apps.)
2580            // For security and version matching reason, only consider
2581            // overlay packages if they reside in the right directory.
2582            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2583                    | PackageParser.PARSE_IS_SYSTEM
2584                    | PackageParser.PARSE_IS_SYSTEM_DIR
2585                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2586
2587            mParallelPackageParserCallback.findStaticOverlayPackages();
2588
2589            // Find base frameworks (resource packages without code).
2590            scanDirTracedLI(frameworkDir, mDefParseFlags
2591                    | PackageParser.PARSE_IS_SYSTEM
2592                    | PackageParser.PARSE_IS_SYSTEM_DIR
2593                    | PackageParser.PARSE_IS_PRIVILEGED,
2594                    scanFlags | SCAN_NO_DEX, 0);
2595
2596            // Collected privileged system packages.
2597            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2598            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2599                    | PackageParser.PARSE_IS_SYSTEM
2600                    | PackageParser.PARSE_IS_SYSTEM_DIR
2601                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2602
2603            // Collect ordinary system packages.
2604            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2605            scanDirTracedLI(systemAppDir, mDefParseFlags
2606                    | PackageParser.PARSE_IS_SYSTEM
2607                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2608
2609            // Collect all vendor packages.
2610            File vendorAppDir = new File("/vendor/app");
2611            try {
2612                vendorAppDir = vendorAppDir.getCanonicalFile();
2613            } catch (IOException e) {
2614                // failed to look up canonical path, continue with original one
2615            }
2616            scanDirTracedLI(vendorAppDir, mDefParseFlags
2617                    | PackageParser.PARSE_IS_SYSTEM
2618                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2619
2620            // Collect all OEM packages.
2621            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2622            scanDirTracedLI(oemAppDir, mDefParseFlags
2623                    | PackageParser.PARSE_IS_SYSTEM
2624                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2625
2626            // Prune any system packages that no longer exist.
2627            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2628            if (!mOnlyCore) {
2629                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2630                while (psit.hasNext()) {
2631                    PackageSetting ps = psit.next();
2632
2633                    /*
2634                     * If this is not a system app, it can't be a
2635                     * disable system app.
2636                     */
2637                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2638                        continue;
2639                    }
2640
2641                    /*
2642                     * If the package is scanned, it's not erased.
2643                     */
2644                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2645                    if (scannedPkg != null) {
2646                        /*
2647                         * If the system app is both scanned and in the
2648                         * disabled packages list, then it must have been
2649                         * added via OTA. Remove it from the currently
2650                         * scanned package so the previously user-installed
2651                         * application can be scanned.
2652                         */
2653                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2654                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2655                                    + ps.name + "; removing system app.  Last known codePath="
2656                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2657                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2658                                    + scannedPkg.mVersionCode);
2659                            removePackageLI(scannedPkg, true);
2660                            mExpectingBetter.put(ps.name, ps.codePath);
2661                        }
2662
2663                        continue;
2664                    }
2665
2666                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2667                        psit.remove();
2668                        logCriticalInfo(Log.WARN, "System package " + ps.name
2669                                + " no longer exists; it's data will be wiped");
2670                        // Actual deletion of code and data will be handled by later
2671                        // reconciliation step
2672                    } else {
2673                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2674                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2675                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2676                        }
2677                    }
2678                }
2679            }
2680
2681            //look for any incomplete package installations
2682            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2683            for (int i = 0; i < deletePkgsList.size(); i++) {
2684                // Actual deletion of code and data will be handled by later
2685                // reconciliation step
2686                final String packageName = deletePkgsList.get(i).name;
2687                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2688                synchronized (mPackages) {
2689                    mSettings.removePackageLPw(packageName);
2690                }
2691            }
2692
2693            //delete tmp files
2694            deleteTempPackageFiles();
2695
2696            // Remove any shared userIDs that have no associated packages
2697            mSettings.pruneSharedUsersLPw();
2698
2699            if (!mOnlyCore) {
2700                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2701                        SystemClock.uptimeMillis());
2702                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2703
2704                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2705                        | PackageParser.PARSE_FORWARD_LOCK,
2706                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2707
2708                /**
2709                 * Remove disable package settings for any updated system
2710                 * apps that were removed via an OTA. If they're not a
2711                 * previously-updated app, remove them completely.
2712                 * Otherwise, just revoke their system-level permissions.
2713                 */
2714                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2715                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2716                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2717
2718                    String msg;
2719                    if (deletedPkg == null) {
2720                        msg = "Updated system package " + deletedAppName
2721                                + " no longer exists; it's data will be wiped";
2722                        // Actual deletion of code and data will be handled by later
2723                        // reconciliation step
2724                    } else {
2725                        msg = "Updated system app + " + deletedAppName
2726                                + " no longer present; removing system privileges for "
2727                                + deletedAppName;
2728
2729                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2730
2731                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2732                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2733                    }
2734                    logCriticalInfo(Log.WARN, msg);
2735                }
2736
2737                /**
2738                 * Make sure all system apps that we expected to appear on
2739                 * the userdata partition actually showed up. If they never
2740                 * appeared, crawl back and revive the system version.
2741                 */
2742                for (int i = 0; i < mExpectingBetter.size(); i++) {
2743                    final String packageName = mExpectingBetter.keyAt(i);
2744                    if (!mPackages.containsKey(packageName)) {
2745                        final File scanFile = mExpectingBetter.valueAt(i);
2746
2747                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2748                                + " but never showed up; reverting to system");
2749
2750                        int reparseFlags = mDefParseFlags;
2751                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2752                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2753                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2754                                    | PackageParser.PARSE_IS_PRIVILEGED;
2755                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2756                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2757                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2758                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2759                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2760                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2761                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2762                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2763                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2764                        } else {
2765                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2766                            continue;
2767                        }
2768
2769                        mSettings.enableSystemPackageLPw(packageName);
2770
2771                        try {
2772                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2773                        } catch (PackageManagerException e) {
2774                            Slog.e(TAG, "Failed to parse original system package: "
2775                                    + e.getMessage());
2776                        }
2777                    }
2778                }
2779            }
2780            mExpectingBetter.clear();
2781
2782            // Resolve the storage manager.
2783            mStorageManagerPackage = getStorageManagerPackageName();
2784
2785            // Resolve protected action filters. Only the setup wizard is allowed to
2786            // have a high priority filter for these actions.
2787            mSetupWizardPackage = getSetupWizardPackageName();
2788            if (mProtectedFilters.size() > 0) {
2789                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2790                    Slog.i(TAG, "No setup wizard;"
2791                        + " All protected intents capped to priority 0");
2792                }
2793                for (ActivityIntentInfo filter : mProtectedFilters) {
2794                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2795                        if (DEBUG_FILTERS) {
2796                            Slog.i(TAG, "Found setup wizard;"
2797                                + " allow priority " + filter.getPriority() + ";"
2798                                + " package: " + filter.activity.info.packageName
2799                                + " activity: " + filter.activity.className
2800                                + " priority: " + filter.getPriority());
2801                        }
2802                        // skip setup wizard; allow it to keep the high priority filter
2803                        continue;
2804                    }
2805                    if (DEBUG_FILTERS) {
2806                        Slog.i(TAG, "Protected action; cap priority to 0;"
2807                                + " package: " + filter.activity.info.packageName
2808                                + " activity: " + filter.activity.className
2809                                + " origPrio: " + filter.getPriority());
2810                    }
2811                    filter.setPriority(0);
2812                }
2813            }
2814            mDeferProtectedFilters = false;
2815            mProtectedFilters.clear();
2816
2817            // Now that we know all of the shared libraries, update all clients to have
2818            // the correct library paths.
2819            updateAllSharedLibrariesLPw(null);
2820
2821            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2822                // NOTE: We ignore potential failures here during a system scan (like
2823                // the rest of the commands above) because there's precious little we
2824                // can do about it. A settings error is reported, though.
2825                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2826            }
2827
2828            // Now that we know all the packages we are keeping,
2829            // read and update their last usage times.
2830            mPackageUsage.read(mPackages);
2831            mCompilerStats.read();
2832
2833            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2834                    SystemClock.uptimeMillis());
2835            Slog.i(TAG, "Time to scan packages: "
2836                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2837                    + " seconds");
2838
2839            // If the platform SDK has changed since the last time we booted,
2840            // we need to re-grant app permission to catch any new ones that
2841            // appear.  This is really a hack, and means that apps can in some
2842            // cases get permissions that the user didn't initially explicitly
2843            // allow...  it would be nice to have some better way to handle
2844            // this situation.
2845            int updateFlags = UPDATE_PERMISSIONS_ALL;
2846            if (ver.sdkVersion != mSdkVersion) {
2847                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2848                        + mSdkVersion + "; regranting permissions for internal storage");
2849                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2850            }
2851            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2852            ver.sdkVersion = mSdkVersion;
2853
2854            // If this is the first boot or an update from pre-M, and it is a normal
2855            // boot, then we need to initialize the default preferred apps across
2856            // all defined users.
2857            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2858                for (UserInfo user : sUserManager.getUsers(true)) {
2859                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2860                    applyFactoryDefaultBrowserLPw(user.id);
2861                    primeDomainVerificationsLPw(user.id);
2862                }
2863            }
2864
2865            // Prepare storage for system user really early during boot,
2866            // since core system apps like SettingsProvider and SystemUI
2867            // can't wait for user to start
2868            final int storageFlags;
2869            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2870                storageFlags = StorageManager.FLAG_STORAGE_DE;
2871            } else {
2872                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2873            }
2874            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2875                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2876                    true /* onlyCoreApps */);
2877            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2878                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2879                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2880                traceLog.traceBegin("AppDataFixup");
2881                try {
2882                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2883                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2884                } catch (InstallerException e) {
2885                    Slog.w(TAG, "Trouble fixing GIDs", e);
2886                }
2887                traceLog.traceEnd();
2888
2889                traceLog.traceBegin("AppDataPrepare");
2890                if (deferPackages == null || deferPackages.isEmpty()) {
2891                    return;
2892                }
2893                int count = 0;
2894                for (String pkgName : deferPackages) {
2895                    PackageParser.Package pkg = null;
2896                    synchronized (mPackages) {
2897                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2898                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2899                            pkg = ps.pkg;
2900                        }
2901                    }
2902                    if (pkg != null) {
2903                        synchronized (mInstallLock) {
2904                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2905                                    true /* maybeMigrateAppData */);
2906                        }
2907                        count++;
2908                    }
2909                }
2910                traceLog.traceEnd();
2911                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2912            }, "prepareAppData");
2913
2914            // If this is first boot after an OTA, and a normal boot, then
2915            // we need to clear code cache directories.
2916            // Note that we do *not* clear the application profiles. These remain valid
2917            // across OTAs and are used to drive profile verification (post OTA) and
2918            // profile compilation (without waiting to collect a fresh set of profiles).
2919            if (mIsUpgrade && !onlyCore) {
2920                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2921                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2922                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2923                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2924                        // No apps are running this early, so no need to freeze
2925                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2926                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2927                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2928                    }
2929                }
2930                ver.fingerprint = Build.FINGERPRINT;
2931            }
2932
2933            checkDefaultBrowser();
2934
2935            // clear only after permissions and other defaults have been updated
2936            mExistingSystemPackages.clear();
2937            mPromoteSystemApps = false;
2938
2939            // All the changes are done during package scanning.
2940            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2941
2942            // can downgrade to reader
2943            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2944            mSettings.writeLPr();
2945            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2946            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2947                    SystemClock.uptimeMillis());
2948
2949            if (!mOnlyCore) {
2950                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2951                mRequiredInstallerPackage = getRequiredInstallerLPr();
2952                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2953                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2954                if (mIntentFilterVerifierComponent != null) {
2955                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2956                            mIntentFilterVerifierComponent);
2957                } else {
2958                    mIntentFilterVerifier = null;
2959                }
2960                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2961                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2962                        SharedLibraryInfo.VERSION_UNDEFINED);
2963                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2964                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2965                        SharedLibraryInfo.VERSION_UNDEFINED);
2966            } else {
2967                mRequiredVerifierPackage = null;
2968                mRequiredInstallerPackage = null;
2969                mRequiredUninstallerPackage = null;
2970                mIntentFilterVerifierComponent = null;
2971                mIntentFilterVerifier = null;
2972                mServicesSystemSharedLibraryPackageName = null;
2973                mSharedSystemSharedLibraryPackageName = null;
2974            }
2975
2976            mInstallerService = new PackageInstallerService(context, this);
2977            final Pair<ComponentName, String> instantAppResolverComponent =
2978                    getInstantAppResolverLPr();
2979            if (instantAppResolverComponent != null) {
2980                if (DEBUG_EPHEMERAL) {
2981                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2982                }
2983                mInstantAppResolverConnection = new EphemeralResolverConnection(
2984                        mContext, instantAppResolverComponent.first,
2985                        instantAppResolverComponent.second);
2986                mInstantAppResolverSettingsComponent =
2987                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2988            } else {
2989                mInstantAppResolverConnection = null;
2990                mInstantAppResolverSettingsComponent = null;
2991            }
2992            updateInstantAppInstallerLocked(null);
2993
2994            // Read and update the usage of dex files.
2995            // Do this at the end of PM init so that all the packages have their
2996            // data directory reconciled.
2997            // At this point we know the code paths of the packages, so we can validate
2998            // the disk file and build the internal cache.
2999            // The usage file is expected to be small so loading and verifying it
3000            // should take a fairly small time compare to the other activities (e.g. package
3001            // scanning).
3002            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3003            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3004            for (int userId : currentUserIds) {
3005                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3006            }
3007            mDexManager.load(userPackages);
3008        } // synchronized (mPackages)
3009        } // synchronized (mInstallLock)
3010
3011        // Now after opening every single application zip, make sure they
3012        // are all flushed.  Not really needed, but keeps things nice and
3013        // tidy.
3014        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3015        Runtime.getRuntime().gc();
3016        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3017
3018        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3019        FallbackCategoryProvider.loadFallbacks();
3020        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3021
3022        // The initial scanning above does many calls into installd while
3023        // holding the mPackages lock, but we're mostly interested in yelling
3024        // once we have a booted system.
3025        mInstaller.setWarnIfHeld(mPackages);
3026
3027        // Expose private service for system components to use.
3028        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3029        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3030    }
3031
3032    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3033        // we're only interested in updating the installer appliction when 1) it's not
3034        // already set or 2) the modified package is the installer
3035        if (mInstantAppInstallerActivity != null
3036                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3037                        .equals(modifiedPackage)) {
3038            return;
3039        }
3040        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3041    }
3042
3043    private static File preparePackageParserCache(boolean isUpgrade) {
3044        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3045            return null;
3046        }
3047
3048        // Disable package parsing on eng builds to allow for faster incremental development.
3049        if ("eng".equals(Build.TYPE)) {
3050            return null;
3051        }
3052
3053        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3054            Slog.i(TAG, "Disabling package parser cache due to system property.");
3055            return null;
3056        }
3057
3058        // The base directory for the package parser cache lives under /data/system/.
3059        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3060                "package_cache");
3061        if (cacheBaseDir == null) {
3062            return null;
3063        }
3064
3065        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3066        // This also serves to "GC" unused entries when the package cache version changes (which
3067        // can only happen during upgrades).
3068        if (isUpgrade) {
3069            FileUtils.deleteContents(cacheBaseDir);
3070        }
3071
3072
3073        // Return the versioned package cache directory. This is something like
3074        // "/data/system/package_cache/1"
3075        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3076
3077        // The following is a workaround to aid development on non-numbered userdebug
3078        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3079        // the system partition is newer.
3080        //
3081        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3082        // that starts with "eng." to signify that this is an engineering build and not
3083        // destined for release.
3084        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3085            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3086
3087            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3088            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3089            // in general and should not be used for production changes. In this specific case,
3090            // we know that they will work.
3091            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3092            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3093                FileUtils.deleteContents(cacheBaseDir);
3094                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3095            }
3096        }
3097
3098        return cacheDir;
3099    }
3100
3101    @Override
3102    public boolean isFirstBoot() {
3103        // allow instant applications
3104        return mFirstBoot;
3105    }
3106
3107    @Override
3108    public boolean isOnlyCoreApps() {
3109        // allow instant applications
3110        return mOnlyCore;
3111    }
3112
3113    @Override
3114    public boolean isUpgrade() {
3115        // allow instant applications
3116        return mIsUpgrade;
3117    }
3118
3119    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3120        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3121
3122        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3123                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3124                UserHandle.USER_SYSTEM);
3125        if (matches.size() == 1) {
3126            return matches.get(0).getComponentInfo().packageName;
3127        } else if (matches.size() == 0) {
3128            Log.e(TAG, "There should probably be a verifier, but, none were found");
3129            return null;
3130        }
3131        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3132    }
3133
3134    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3135        synchronized (mPackages) {
3136            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3137            if (libraryEntry == null) {
3138                throw new IllegalStateException("Missing required shared library:" + name);
3139            }
3140            return libraryEntry.apk;
3141        }
3142    }
3143
3144    private @NonNull String getRequiredInstallerLPr() {
3145        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3146        intent.addCategory(Intent.CATEGORY_DEFAULT);
3147        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3148
3149        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3150                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3151                UserHandle.USER_SYSTEM);
3152        if (matches.size() == 1) {
3153            ResolveInfo resolveInfo = matches.get(0);
3154            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3155                throw new RuntimeException("The installer must be a privileged app");
3156            }
3157            return matches.get(0).getComponentInfo().packageName;
3158        } else {
3159            throw new RuntimeException("There must be exactly one installer; found " + matches);
3160        }
3161    }
3162
3163    private @NonNull String getRequiredUninstallerLPr() {
3164        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3165        intent.addCategory(Intent.CATEGORY_DEFAULT);
3166        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3167
3168        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3169                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3170                UserHandle.USER_SYSTEM);
3171        if (resolveInfo == null ||
3172                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3173            throw new RuntimeException("There must be exactly one uninstaller; found "
3174                    + resolveInfo);
3175        }
3176        return resolveInfo.getComponentInfo().packageName;
3177    }
3178
3179    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3180        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3181
3182        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3183                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3184                UserHandle.USER_SYSTEM);
3185        ResolveInfo best = null;
3186        final int N = matches.size();
3187        for (int i = 0; i < N; i++) {
3188            final ResolveInfo cur = matches.get(i);
3189            final String packageName = cur.getComponentInfo().packageName;
3190            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3191                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3192                continue;
3193            }
3194
3195            if (best == null || cur.priority > best.priority) {
3196                best = cur;
3197            }
3198        }
3199
3200        if (best != null) {
3201            return best.getComponentInfo().getComponentName();
3202        }
3203        Slog.w(TAG, "Intent filter verifier not found");
3204        return null;
3205    }
3206
3207    @Override
3208    public @Nullable ComponentName getInstantAppResolverComponent() {
3209        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3210            return null;
3211        }
3212        synchronized (mPackages) {
3213            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3214            if (instantAppResolver == null) {
3215                return null;
3216            }
3217            return instantAppResolver.first;
3218        }
3219    }
3220
3221    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3222        final String[] packageArray =
3223                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3224        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3225            if (DEBUG_EPHEMERAL) {
3226                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3227            }
3228            return null;
3229        }
3230
3231        final int callingUid = Binder.getCallingUid();
3232        final int resolveFlags =
3233                MATCH_DIRECT_BOOT_AWARE
3234                | MATCH_DIRECT_BOOT_UNAWARE
3235                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3236        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3237        final Intent resolverIntent = new Intent(actionName);
3238        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3239                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3240        // temporarily look for the old action
3241        if (resolvers.size() == 0) {
3242            if (DEBUG_EPHEMERAL) {
3243                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3244            }
3245            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3246            resolverIntent.setAction(actionName);
3247            resolvers = queryIntentServicesInternal(resolverIntent, null,
3248                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3249        }
3250        final int N = resolvers.size();
3251        if (N == 0) {
3252            if (DEBUG_EPHEMERAL) {
3253                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3254            }
3255            return null;
3256        }
3257
3258        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3259        for (int i = 0; i < N; i++) {
3260            final ResolveInfo info = resolvers.get(i);
3261
3262            if (info.serviceInfo == null) {
3263                continue;
3264            }
3265
3266            final String packageName = info.serviceInfo.packageName;
3267            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3268                if (DEBUG_EPHEMERAL) {
3269                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3270                            + " pkg: " + packageName + ", info:" + info);
3271                }
3272                continue;
3273            }
3274
3275            if (DEBUG_EPHEMERAL) {
3276                Slog.v(TAG, "Ephemeral resolver found;"
3277                        + " pkg: " + packageName + ", info:" + info);
3278            }
3279            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3280        }
3281        if (DEBUG_EPHEMERAL) {
3282            Slog.v(TAG, "Ephemeral resolver NOT found");
3283        }
3284        return null;
3285    }
3286
3287    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3288        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3289        intent.addCategory(Intent.CATEGORY_DEFAULT);
3290        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3291
3292        final int resolveFlags =
3293                MATCH_DIRECT_BOOT_AWARE
3294                | MATCH_DIRECT_BOOT_UNAWARE
3295                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3296        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3297                resolveFlags, UserHandle.USER_SYSTEM);
3298        // temporarily look for the old action
3299        if (matches.isEmpty()) {
3300            if (DEBUG_EPHEMERAL) {
3301                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3302            }
3303            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3304            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3305                    resolveFlags, UserHandle.USER_SYSTEM);
3306        }
3307        Iterator<ResolveInfo> iter = matches.iterator();
3308        while (iter.hasNext()) {
3309            final ResolveInfo rInfo = iter.next();
3310            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3311            if (ps != null) {
3312                final PermissionsState permissionsState = ps.getPermissionsState();
3313                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3314                    continue;
3315                }
3316            }
3317            iter.remove();
3318        }
3319        if (matches.size() == 0) {
3320            return null;
3321        } else if (matches.size() == 1) {
3322            return (ActivityInfo) matches.get(0).getComponentInfo();
3323        } else {
3324            throw new RuntimeException(
3325                    "There must be at most one ephemeral installer; found " + matches);
3326        }
3327    }
3328
3329    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3330            @NonNull ComponentName resolver) {
3331        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3332                .addCategory(Intent.CATEGORY_DEFAULT)
3333                .setPackage(resolver.getPackageName());
3334        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3335        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3336                UserHandle.USER_SYSTEM);
3337        // temporarily look for the old action
3338        if (matches.isEmpty()) {
3339            if (DEBUG_EPHEMERAL) {
3340                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3341            }
3342            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3343            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3344                    UserHandle.USER_SYSTEM);
3345        }
3346        if (matches.isEmpty()) {
3347            return null;
3348        }
3349        return matches.get(0).getComponentInfo().getComponentName();
3350    }
3351
3352    private void primeDomainVerificationsLPw(int userId) {
3353        if (DEBUG_DOMAIN_VERIFICATION) {
3354            Slog.d(TAG, "Priming domain verifications in user " + userId);
3355        }
3356
3357        SystemConfig systemConfig = SystemConfig.getInstance();
3358        ArraySet<String> packages = systemConfig.getLinkedApps();
3359
3360        for (String packageName : packages) {
3361            PackageParser.Package pkg = mPackages.get(packageName);
3362            if (pkg != null) {
3363                if (!pkg.isSystemApp()) {
3364                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3365                    continue;
3366                }
3367
3368                ArraySet<String> domains = null;
3369                for (PackageParser.Activity a : pkg.activities) {
3370                    for (ActivityIntentInfo filter : a.intents) {
3371                        if (hasValidDomains(filter)) {
3372                            if (domains == null) {
3373                                domains = new ArraySet<String>();
3374                            }
3375                            domains.addAll(filter.getHostsList());
3376                        }
3377                    }
3378                }
3379
3380                if (domains != null && domains.size() > 0) {
3381                    if (DEBUG_DOMAIN_VERIFICATION) {
3382                        Slog.v(TAG, "      + " + packageName);
3383                    }
3384                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3385                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3386                    // and then 'always' in the per-user state actually used for intent resolution.
3387                    final IntentFilterVerificationInfo ivi;
3388                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3389                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3390                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3391                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3392                } else {
3393                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3394                            + "' does not handle web links");
3395                }
3396            } else {
3397                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3398            }
3399        }
3400
3401        scheduleWritePackageRestrictionsLocked(userId);
3402        scheduleWriteSettingsLocked();
3403    }
3404
3405    private void applyFactoryDefaultBrowserLPw(int userId) {
3406        // The default browser app's package name is stored in a string resource,
3407        // with a product-specific overlay used for vendor customization.
3408        String browserPkg = mContext.getResources().getString(
3409                com.android.internal.R.string.default_browser);
3410        if (!TextUtils.isEmpty(browserPkg)) {
3411            // non-empty string => required to be a known package
3412            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3413            if (ps == null) {
3414                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3415                browserPkg = null;
3416            } else {
3417                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3418            }
3419        }
3420
3421        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3422        // default.  If there's more than one, just leave everything alone.
3423        if (browserPkg == null) {
3424            calculateDefaultBrowserLPw(userId);
3425        }
3426    }
3427
3428    private void calculateDefaultBrowserLPw(int userId) {
3429        List<String> allBrowsers = resolveAllBrowserApps(userId);
3430        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3431        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3432    }
3433
3434    private List<String> resolveAllBrowserApps(int userId) {
3435        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3436        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3437                PackageManager.MATCH_ALL, userId);
3438
3439        final int count = list.size();
3440        List<String> result = new ArrayList<String>(count);
3441        for (int i=0; i<count; i++) {
3442            ResolveInfo info = list.get(i);
3443            if (info.activityInfo == null
3444                    || !info.handleAllWebDataURI
3445                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3446                    || result.contains(info.activityInfo.packageName)) {
3447                continue;
3448            }
3449            result.add(info.activityInfo.packageName);
3450        }
3451
3452        return result;
3453    }
3454
3455    private boolean packageIsBrowser(String packageName, int userId) {
3456        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3457                PackageManager.MATCH_ALL, userId);
3458        final int N = list.size();
3459        for (int i = 0; i < N; i++) {
3460            ResolveInfo info = list.get(i);
3461            if (packageName.equals(info.activityInfo.packageName)) {
3462                return true;
3463            }
3464        }
3465        return false;
3466    }
3467
3468    private void checkDefaultBrowser() {
3469        final int myUserId = UserHandle.myUserId();
3470        final String packageName = getDefaultBrowserPackageName(myUserId);
3471        if (packageName != null) {
3472            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3473            if (info == null) {
3474                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3475                synchronized (mPackages) {
3476                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3477                }
3478            }
3479        }
3480    }
3481
3482    @Override
3483    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3484            throws RemoteException {
3485        try {
3486            return super.onTransact(code, data, reply, flags);
3487        } catch (RuntimeException e) {
3488            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3489                Slog.wtf(TAG, "Package Manager Crash", e);
3490            }
3491            throw e;
3492        }
3493    }
3494
3495    static int[] appendInts(int[] cur, int[] add) {
3496        if (add == null) return cur;
3497        if (cur == null) return add;
3498        final int N = add.length;
3499        for (int i=0; i<N; i++) {
3500            cur = appendInt(cur, add[i]);
3501        }
3502        return cur;
3503    }
3504
3505    /**
3506     * Returns whether or not a full application can see an instant application.
3507     * <p>
3508     * Currently, there are three cases in which this can occur:
3509     * <ol>
3510     * <li>The calling application is a "special" process. The special
3511     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3512     *     and {@code 0}</li>
3513     * <li>The calling application has the permission
3514     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3515     * <li>The calling application is the default launcher on the
3516     *     system partition.</li>
3517     * </ol>
3518     */
3519    private boolean canViewInstantApps(int callingUid, int userId) {
3520        if (callingUid == Process.SYSTEM_UID
3521                || callingUid == Process.SHELL_UID
3522                || callingUid == Process.ROOT_UID) {
3523            return true;
3524        }
3525        if (mContext.checkCallingOrSelfPermission(
3526                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3527            return true;
3528        }
3529        if (mContext.checkCallingOrSelfPermission(
3530                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3531            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3532            if (homeComponent != null
3533                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3534                return true;
3535            }
3536        }
3537        return false;
3538    }
3539
3540    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3541        if (!sUserManager.exists(userId)) return null;
3542        if (ps == null) {
3543            return null;
3544        }
3545        PackageParser.Package p = ps.pkg;
3546        if (p == null) {
3547            return null;
3548        }
3549        final int callingUid = Binder.getCallingUid();
3550        // Filter out ephemeral app metadata:
3551        //   * The system/shell/root can see metadata for any app
3552        //   * An installed app can see metadata for 1) other installed apps
3553        //     and 2) ephemeral apps that have explicitly interacted with it
3554        //   * Ephemeral apps can only see their own data and exposed installed apps
3555        //   * Holding a signature permission allows seeing instant apps
3556        if (filterAppAccessLPr(ps, callingUid, userId)) {
3557            return null;
3558        }
3559
3560        final PermissionsState permissionsState = ps.getPermissionsState();
3561
3562        // Compute GIDs only if requested
3563        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3564                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3565        // Compute granted permissions only if package has requested permissions
3566        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3567                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3568        final PackageUserState state = ps.readUserState(userId);
3569
3570        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3571                && ps.isSystem()) {
3572            flags |= MATCH_ANY_USER;
3573        }
3574
3575        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3576                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3577
3578        if (packageInfo == null) {
3579            return null;
3580        }
3581
3582        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3583                resolveExternalPackageNameLPr(p);
3584
3585        return packageInfo;
3586    }
3587
3588    @Override
3589    public void checkPackageStartable(String packageName, int userId) {
3590        final int callingUid = Binder.getCallingUid();
3591        if (getInstantAppPackageName(callingUid) != null) {
3592            throw new SecurityException("Instant applications don't have access to this method");
3593        }
3594        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3595        synchronized (mPackages) {
3596            final PackageSetting ps = mSettings.mPackages.get(packageName);
3597            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3598                throw new SecurityException("Package " + packageName + " was not found!");
3599            }
3600
3601            if (!ps.getInstalled(userId)) {
3602                throw new SecurityException(
3603                        "Package " + packageName + " was not installed for user " + userId + "!");
3604            }
3605
3606            if (mSafeMode && !ps.isSystem()) {
3607                throw new SecurityException("Package " + packageName + " not a system app!");
3608            }
3609
3610            if (mFrozenPackages.contains(packageName)) {
3611                throw new SecurityException("Package " + packageName + " is currently frozen!");
3612            }
3613
3614            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3615                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3616                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3617            }
3618        }
3619    }
3620
3621    @Override
3622    public boolean isPackageAvailable(String packageName, int userId) {
3623        if (!sUserManager.exists(userId)) return false;
3624        final int callingUid = Binder.getCallingUid();
3625        enforceCrossUserPermission(callingUid, userId,
3626                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3627        synchronized (mPackages) {
3628            PackageParser.Package p = mPackages.get(packageName);
3629            if (p != null) {
3630                final PackageSetting ps = (PackageSetting) p.mExtras;
3631                if (filterAppAccessLPr(ps, callingUid, userId)) {
3632                    return false;
3633                }
3634                if (ps != null) {
3635                    final PackageUserState state = ps.readUserState(userId);
3636                    if (state != null) {
3637                        return PackageParser.isAvailable(state);
3638                    }
3639                }
3640            }
3641        }
3642        return false;
3643    }
3644
3645    @Override
3646    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3647        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3648                flags, Binder.getCallingUid(), userId);
3649    }
3650
3651    @Override
3652    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3653            int flags, int userId) {
3654        return getPackageInfoInternal(versionedPackage.getPackageName(),
3655                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3656    }
3657
3658    /**
3659     * Important: The provided filterCallingUid is used exclusively to filter out packages
3660     * that can be seen based on user state. It's typically the original caller uid prior
3661     * to clearing. Because it can only be provided by trusted code, it's value can be
3662     * trusted and will be used as-is; unlike userId which will be validated by this method.
3663     */
3664    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3665            int flags, int filterCallingUid, int userId) {
3666        if (!sUserManager.exists(userId)) return null;
3667        flags = updateFlagsForPackage(flags, userId, packageName);
3668        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3669                false /* requireFullPermission */, false /* checkShell */, "get package info");
3670
3671        // reader
3672        synchronized (mPackages) {
3673            // Normalize package name to handle renamed packages and static libs
3674            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3675
3676            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3677            if (matchFactoryOnly) {
3678                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3679                if (ps != null) {
3680                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3681                        return null;
3682                    }
3683                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3684                        return null;
3685                    }
3686                    return generatePackageInfo(ps, flags, userId);
3687                }
3688            }
3689
3690            PackageParser.Package p = mPackages.get(packageName);
3691            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3692                return null;
3693            }
3694            if (DEBUG_PACKAGE_INFO)
3695                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3696            if (p != null) {
3697                final PackageSetting ps = (PackageSetting) p.mExtras;
3698                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3699                    return null;
3700                }
3701                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3702                    return null;
3703                }
3704                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3705            }
3706            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3707                final PackageSetting ps = mSettings.mPackages.get(packageName);
3708                if (ps == null) return null;
3709                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3710                    return null;
3711                }
3712                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3713                    return null;
3714                }
3715                return generatePackageInfo(ps, flags, userId);
3716            }
3717        }
3718        return null;
3719    }
3720
3721    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3722        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3723            return true;
3724        }
3725        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3726            return true;
3727        }
3728        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3729            return true;
3730        }
3731        return false;
3732    }
3733
3734    private boolean isComponentVisibleToInstantApp(
3735            @Nullable ComponentName component, @ComponentType int type) {
3736        if (type == TYPE_ACTIVITY) {
3737            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3738            return activity != null
3739                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3740                    : false;
3741        } else if (type == TYPE_RECEIVER) {
3742            final PackageParser.Activity activity = mReceivers.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_SERVICE) {
3747            final PackageParser.Service service = mServices.mServices.get(component);
3748            return service != null
3749                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3750                    : false;
3751        } else if (type == TYPE_PROVIDER) {
3752            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3753            return provider != null
3754                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3755                    : false;
3756        } else if (type == TYPE_UNKNOWN) {
3757            return isComponentVisibleToInstantApp(component);
3758        }
3759        return false;
3760    }
3761
3762    /**
3763     * Returns whether or not access to the application should be filtered.
3764     * <p>
3765     * Access may be limited based upon whether the calling or target applications
3766     * are instant applications.
3767     *
3768     * @see #canAccessInstantApps(int)
3769     */
3770    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3771            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3772        // if we're in an isolated process, get the real calling UID
3773        if (Process.isIsolated(callingUid)) {
3774            callingUid = mIsolatedOwners.get(callingUid);
3775        }
3776        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3777        final boolean callerIsInstantApp = instantAppPkgName != null;
3778        if (ps == null) {
3779            if (callerIsInstantApp) {
3780                // pretend the application exists, but, needs to be filtered
3781                return true;
3782            }
3783            return false;
3784        }
3785        // if the target and caller are the same application, don't filter
3786        if (isCallerSameApp(ps.name, callingUid)) {
3787            return false;
3788        }
3789        if (callerIsInstantApp) {
3790            // request for a specific component; if it hasn't been explicitly exposed, filter
3791            if (component != null) {
3792                return !isComponentVisibleToInstantApp(component, componentType);
3793            }
3794            // request for application; if no components have been explicitly exposed, filter
3795            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3796        }
3797        if (ps.getInstantApp(userId)) {
3798            // caller can see all components of all instant applications, don't filter
3799            if (canViewInstantApps(callingUid, userId)) {
3800                return false;
3801            }
3802            // request for a specific instant application component, filter
3803            if (component != null) {
3804                return true;
3805            }
3806            // request for an instant application; if the caller hasn't been granted access, filter
3807            return !mInstantAppRegistry.isInstantAccessGranted(
3808                    userId, UserHandle.getAppId(callingUid), ps.appId);
3809        }
3810        return false;
3811    }
3812
3813    /**
3814     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3815     */
3816    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3817        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3818    }
3819
3820    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3821            int flags) {
3822        // Callers can access only the libs they depend on, otherwise they need to explicitly
3823        // ask for the shared libraries given the caller is allowed to access all static libs.
3824        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3825            // System/shell/root get to see all static libs
3826            final int appId = UserHandle.getAppId(uid);
3827            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3828                    || appId == Process.ROOT_UID) {
3829                return false;
3830            }
3831        }
3832
3833        // No package means no static lib as it is always on internal storage
3834        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3835            return false;
3836        }
3837
3838        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3839                ps.pkg.staticSharedLibVersion);
3840        if (libEntry == null) {
3841            return false;
3842        }
3843
3844        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3845        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3846        if (uidPackageNames == null) {
3847            return true;
3848        }
3849
3850        for (String uidPackageName : uidPackageNames) {
3851            if (ps.name.equals(uidPackageName)) {
3852                return false;
3853            }
3854            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3855            if (uidPs != null) {
3856                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3857                        libEntry.info.getName());
3858                if (index < 0) {
3859                    continue;
3860                }
3861                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3862                    return false;
3863                }
3864            }
3865        }
3866        return true;
3867    }
3868
3869    @Override
3870    public String[] currentToCanonicalPackageNames(String[] names) {
3871        final int callingUid = Binder.getCallingUid();
3872        if (getInstantAppPackageName(callingUid) != null) {
3873            return names;
3874        }
3875        final String[] out = new String[names.length];
3876        // reader
3877        synchronized (mPackages) {
3878            final int callingUserId = UserHandle.getUserId(callingUid);
3879            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3880            for (int i=names.length-1; i>=0; i--) {
3881                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3882                boolean translateName = false;
3883                if (ps != null && ps.realName != null) {
3884                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3885                    translateName = !targetIsInstantApp
3886                            || canViewInstantApps
3887                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3888                                    UserHandle.getAppId(callingUid), ps.appId);
3889                }
3890                out[i] = translateName ? ps.realName : names[i];
3891            }
3892        }
3893        return out;
3894    }
3895
3896    @Override
3897    public String[] canonicalToCurrentPackageNames(String[] names) {
3898        final int callingUid = Binder.getCallingUid();
3899        if (getInstantAppPackageName(callingUid) != null) {
3900            return names;
3901        }
3902        final String[] out = new String[names.length];
3903        // reader
3904        synchronized (mPackages) {
3905            final int callingUserId = UserHandle.getUserId(callingUid);
3906            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3907            for (int i=names.length-1; i>=0; i--) {
3908                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3909                boolean translateName = false;
3910                if (cur != null) {
3911                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3912                    final boolean targetIsInstantApp =
3913                            ps != null && ps.getInstantApp(callingUserId);
3914                    translateName = !targetIsInstantApp
3915                            || canViewInstantApps
3916                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3917                                    UserHandle.getAppId(callingUid), ps.appId);
3918                }
3919                out[i] = translateName ? cur : names[i];
3920            }
3921        }
3922        return out;
3923    }
3924
3925    @Override
3926    public int getPackageUid(String packageName, int flags, int userId) {
3927        if (!sUserManager.exists(userId)) return -1;
3928        final int callingUid = Binder.getCallingUid();
3929        flags = updateFlagsForPackage(flags, userId, packageName);
3930        enforceCrossUserPermission(callingUid, userId,
3931                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3932
3933        // reader
3934        synchronized (mPackages) {
3935            final PackageParser.Package p = mPackages.get(packageName);
3936            if (p != null && p.isMatch(flags)) {
3937                PackageSetting ps = (PackageSetting) p.mExtras;
3938                if (filterAppAccessLPr(ps, callingUid, userId)) {
3939                    return -1;
3940                }
3941                return UserHandle.getUid(userId, p.applicationInfo.uid);
3942            }
3943            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3944                final PackageSetting ps = mSettings.mPackages.get(packageName);
3945                if (ps != null && ps.isMatch(flags)
3946                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3947                    return UserHandle.getUid(userId, ps.appId);
3948                }
3949            }
3950        }
3951
3952        return -1;
3953    }
3954
3955    @Override
3956    public int[] getPackageGids(String packageName, int flags, int userId) {
3957        if (!sUserManager.exists(userId)) return null;
3958        final int callingUid = Binder.getCallingUid();
3959        flags = updateFlagsForPackage(flags, userId, packageName);
3960        enforceCrossUserPermission(callingUid, userId,
3961                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3962
3963        // reader
3964        synchronized (mPackages) {
3965            final PackageParser.Package p = mPackages.get(packageName);
3966            if (p != null && p.isMatch(flags)) {
3967                PackageSetting ps = (PackageSetting) p.mExtras;
3968                if (filterAppAccessLPr(ps, callingUid, userId)) {
3969                    return null;
3970                }
3971                // TODO: Shouldn't this be checking for package installed state for userId and
3972                // return null?
3973                return ps.getPermissionsState().computeGids(userId);
3974            }
3975            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3976                final PackageSetting ps = mSettings.mPackages.get(packageName);
3977                if (ps != null && ps.isMatch(flags)
3978                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3979                    return ps.getPermissionsState().computeGids(userId);
3980                }
3981            }
3982        }
3983
3984        return null;
3985    }
3986
3987    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3988        if (bp.perm != null) {
3989            return PackageParser.generatePermissionInfo(bp.perm, flags);
3990        }
3991        PermissionInfo pi = new PermissionInfo();
3992        pi.name = bp.name;
3993        pi.packageName = bp.sourcePackage;
3994        pi.nonLocalizedLabel = bp.name;
3995        pi.protectionLevel = bp.protectionLevel;
3996        return pi;
3997    }
3998
3999    @Override
4000    public PermissionInfo getPermissionInfo(String name, int flags) {
4001        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4002            return null;
4003        }
4004        // reader
4005        synchronized (mPackages) {
4006            final BasePermission p = mSettings.mPermissions.get(name);
4007            if (p != null) {
4008                return generatePermissionInfo(p, flags);
4009            }
4010            return null;
4011        }
4012    }
4013
4014    @Override
4015    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4016            int flags) {
4017        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4018            return null;
4019        }
4020        // reader
4021        synchronized (mPackages) {
4022            if (group != null && !mPermissionGroups.containsKey(group)) {
4023                // This is thrown as NameNotFoundException
4024                return null;
4025            }
4026
4027            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4028            for (BasePermission p : mSettings.mPermissions.values()) {
4029                if (group == null) {
4030                    if (p.perm == null || p.perm.info.group == null) {
4031                        out.add(generatePermissionInfo(p, flags));
4032                    }
4033                } else {
4034                    if (p.perm != null && group.equals(p.perm.info.group)) {
4035                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4036                    }
4037                }
4038            }
4039            return new ParceledListSlice<>(out);
4040        }
4041    }
4042
4043    @Override
4044    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4045        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4046            return null;
4047        }
4048        // reader
4049        synchronized (mPackages) {
4050            return PackageParser.generatePermissionGroupInfo(
4051                    mPermissionGroups.get(name), flags);
4052        }
4053    }
4054
4055    @Override
4056    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4057        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4058            return ParceledListSlice.emptyList();
4059        }
4060        // reader
4061        synchronized (mPackages) {
4062            final int N = mPermissionGroups.size();
4063            ArrayList<PermissionGroupInfo> out
4064                    = new ArrayList<PermissionGroupInfo>(N);
4065            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4066                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4067            }
4068            return new ParceledListSlice<>(out);
4069        }
4070    }
4071
4072    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4073            int filterCallingUid, int userId) {
4074        if (!sUserManager.exists(userId)) return null;
4075        PackageSetting ps = mSettings.mPackages.get(packageName);
4076        if (ps != null) {
4077            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4078                return null;
4079            }
4080            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4081                return null;
4082            }
4083            if (ps.pkg == null) {
4084                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4085                if (pInfo != null) {
4086                    return pInfo.applicationInfo;
4087                }
4088                return null;
4089            }
4090            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4091                    ps.readUserState(userId), userId);
4092            if (ai != null) {
4093                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4094            }
4095            return ai;
4096        }
4097        return null;
4098    }
4099
4100    @Override
4101    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4102        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4103    }
4104
4105    /**
4106     * Important: The provided filterCallingUid is used exclusively to filter out applications
4107     * that can be seen based on user state. It's typically the original caller uid prior
4108     * to clearing. Because it can only be provided by trusted code, it's value can be
4109     * trusted and will be used as-is; unlike userId which will be validated by this method.
4110     */
4111    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4112            int filterCallingUid, int userId) {
4113        if (!sUserManager.exists(userId)) return null;
4114        flags = updateFlagsForApplication(flags, userId, packageName);
4115        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4116                false /* requireFullPermission */, false /* checkShell */, "get application info");
4117
4118        // writer
4119        synchronized (mPackages) {
4120            // Normalize package name to handle renamed packages and static libs
4121            packageName = resolveInternalPackageNameLPr(packageName,
4122                    PackageManager.VERSION_CODE_HIGHEST);
4123
4124            PackageParser.Package p = mPackages.get(packageName);
4125            if (DEBUG_PACKAGE_INFO) Log.v(
4126                    TAG, "getApplicationInfo " + packageName
4127                    + ": " + p);
4128            if (p != null) {
4129                PackageSetting ps = mSettings.mPackages.get(packageName);
4130                if (ps == null) return null;
4131                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4132                    return null;
4133                }
4134                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4135                    return null;
4136                }
4137                // Note: isEnabledLP() does not apply here - always return info
4138                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4139                        p, flags, ps.readUserState(userId), userId);
4140                if (ai != null) {
4141                    ai.packageName = resolveExternalPackageNameLPr(p);
4142                }
4143                return ai;
4144            }
4145            if ("android".equals(packageName)||"system".equals(packageName)) {
4146                return mAndroidApplication;
4147            }
4148            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4149                // Already generates the external package name
4150                return generateApplicationInfoFromSettingsLPw(packageName,
4151                        flags, filterCallingUid, userId);
4152            }
4153        }
4154        return null;
4155    }
4156
4157    private String normalizePackageNameLPr(String packageName) {
4158        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4159        return normalizedPackageName != null ? normalizedPackageName : packageName;
4160    }
4161
4162    @Override
4163    public void deletePreloadsFileCache() {
4164        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4165            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4166        }
4167        File dir = Environment.getDataPreloadsFileCacheDirectory();
4168        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4169        FileUtils.deleteContents(dir);
4170    }
4171
4172    @Override
4173    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4174            final int storageFlags, final IPackageDataObserver observer) {
4175        mContext.enforceCallingOrSelfPermission(
4176                android.Manifest.permission.CLEAR_APP_CACHE, null);
4177        mHandler.post(() -> {
4178            boolean success = false;
4179            try {
4180                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4181                success = true;
4182            } catch (IOException e) {
4183                Slog.w(TAG, e);
4184            }
4185            if (observer != null) {
4186                try {
4187                    observer.onRemoveCompleted(null, success);
4188                } catch (RemoteException e) {
4189                    Slog.w(TAG, e);
4190                }
4191            }
4192        });
4193    }
4194
4195    @Override
4196    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4197            final int storageFlags, final IntentSender pi) {
4198        mContext.enforceCallingOrSelfPermission(
4199                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4200        mHandler.post(() -> {
4201            boolean success = false;
4202            try {
4203                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4204                success = true;
4205            } catch (IOException e) {
4206                Slog.w(TAG, e);
4207            }
4208            if (pi != null) {
4209                try {
4210                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4211                } catch (SendIntentException e) {
4212                    Slog.w(TAG, e);
4213                }
4214            }
4215        });
4216    }
4217
4218    /**
4219     * Blocking call to clear various types of cached data across the system
4220     * until the requested bytes are available.
4221     */
4222    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4223        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4224        final File file = storage.findPathForUuid(volumeUuid);
4225        if (file.getUsableSpace() >= bytes) return;
4226
4227        if (ENABLE_FREE_CACHE_V2) {
4228            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4229                    volumeUuid);
4230            final boolean aggressive = (storageFlags
4231                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4232            final boolean defyReserved = (storageFlags
4233                    & StorageManager.FLAG_ALLOCATE_DEFY_RESERVED) != 0;
4234            final long reservedBytes = (aggressive || defyReserved) ? 0
4235                    : storage.getStorageCacheBytes(file);
4236
4237            // 1. Pre-flight to determine if we have any chance to succeed
4238            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4239            if (internalVolume && (aggressive || SystemProperties
4240                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4241                deletePreloadsFileCache();
4242                if (file.getUsableSpace() >= bytes) return;
4243            }
4244
4245            // 3. Consider parsed APK data (aggressive only)
4246            if (internalVolume && aggressive) {
4247                FileUtils.deleteContents(mCacheDir);
4248                if (file.getUsableSpace() >= bytes) return;
4249            }
4250
4251            // 4. Consider cached app data (above quotas)
4252            try {
4253                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4254                        Installer.FLAG_FREE_CACHE_V2);
4255            } catch (InstallerException ignored) {
4256            }
4257            if (file.getUsableSpace() >= bytes) return;
4258
4259            // 5. Consider shared libraries with refcount=0 and age>min cache period
4260            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4261                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4262                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4263                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4264                return;
4265            }
4266
4267            // 6. Consider dexopt output (aggressive only)
4268            // TODO: Implement
4269
4270            // 7. Consider installed instant apps unused longer than min cache period
4271            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4272                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4273                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4274                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4275                return;
4276            }
4277
4278            // 8. Consider cached app data (below quotas)
4279            try {
4280                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4281                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4282            } catch (InstallerException ignored) {
4283            }
4284            if (file.getUsableSpace() >= bytes) return;
4285
4286            // 9. Consider DropBox entries
4287            // TODO: Implement
4288
4289            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4290            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4291                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4292                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4293                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4294                return;
4295            }
4296        } else {
4297            try {
4298                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4299            } catch (InstallerException ignored) {
4300            }
4301            if (file.getUsableSpace() >= bytes) return;
4302        }
4303
4304        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4305    }
4306
4307    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4308            throws IOException {
4309        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4310        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4311
4312        List<VersionedPackage> packagesToDelete = null;
4313        final long now = System.currentTimeMillis();
4314
4315        synchronized (mPackages) {
4316            final int[] allUsers = sUserManager.getUserIds();
4317            final int libCount = mSharedLibraries.size();
4318            for (int i = 0; i < libCount; i++) {
4319                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4320                if (versionedLib == null) {
4321                    continue;
4322                }
4323                final int versionCount = versionedLib.size();
4324                for (int j = 0; j < versionCount; j++) {
4325                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4326                    // Skip packages that are not static shared libs.
4327                    if (!libInfo.isStatic()) {
4328                        break;
4329                    }
4330                    // Important: We skip static shared libs used for some user since
4331                    // in such a case we need to keep the APK on the device. The check for
4332                    // a lib being used for any user is performed by the uninstall call.
4333                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4334                    // Resolve the package name - we use synthetic package names internally
4335                    final String internalPackageName = resolveInternalPackageNameLPr(
4336                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4337                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4338                    // Skip unused static shared libs cached less than the min period
4339                    // to prevent pruning a lib needed by a subsequently installed package.
4340                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4341                        continue;
4342                    }
4343                    if (packagesToDelete == null) {
4344                        packagesToDelete = new ArrayList<>();
4345                    }
4346                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4347                            declaringPackage.getVersionCode()));
4348                }
4349            }
4350        }
4351
4352        if (packagesToDelete != null) {
4353            final int packageCount = packagesToDelete.size();
4354            for (int i = 0; i < packageCount; i++) {
4355                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4356                // Delete the package synchronously (will fail of the lib used for any user).
4357                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4358                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4359                                == PackageManager.DELETE_SUCCEEDED) {
4360                    if (volume.getUsableSpace() >= neededSpace) {
4361                        return true;
4362                    }
4363                }
4364            }
4365        }
4366
4367        return false;
4368    }
4369
4370    /**
4371     * Update given flags based on encryption status of current user.
4372     */
4373    private int updateFlags(int flags, int userId) {
4374        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4375                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4376            // Caller expressed an explicit opinion about what encryption
4377            // aware/unaware components they want to see, so fall through and
4378            // give them what they want
4379        } else {
4380            // Caller expressed no opinion, so match based on user state
4381            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4382                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4383            } else {
4384                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4385            }
4386        }
4387        return flags;
4388    }
4389
4390    private UserManagerInternal getUserManagerInternal() {
4391        if (mUserManagerInternal == null) {
4392            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4393        }
4394        return mUserManagerInternal;
4395    }
4396
4397    private DeviceIdleController.LocalService getDeviceIdleController() {
4398        if (mDeviceIdleController == null) {
4399            mDeviceIdleController =
4400                    LocalServices.getService(DeviceIdleController.LocalService.class);
4401        }
4402        return mDeviceIdleController;
4403    }
4404
4405    /**
4406     * Update given flags when being used to request {@link PackageInfo}.
4407     */
4408    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4409        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4410        boolean triaged = true;
4411        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4412                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4413            // Caller is asking for component details, so they'd better be
4414            // asking for specific encryption matching behavior, or be triaged
4415            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4416                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4417                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4418                triaged = false;
4419            }
4420        }
4421        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4422                | PackageManager.MATCH_SYSTEM_ONLY
4423                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4424            triaged = false;
4425        }
4426        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4427            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4428                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4429                    + Debug.getCallers(5));
4430        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4431                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4432            // If the caller wants all packages and has a restricted profile associated with it,
4433            // then match all users. This is to make sure that launchers that need to access work
4434            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4435            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4436            flags |= PackageManager.MATCH_ANY_USER;
4437        }
4438        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4439            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4440                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4441        }
4442        return updateFlags(flags, userId);
4443    }
4444
4445    /**
4446     * Update given flags when being used to request {@link ApplicationInfo}.
4447     */
4448    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4449        return updateFlagsForPackage(flags, userId, cookie);
4450    }
4451
4452    /**
4453     * Update given flags when being used to request {@link ComponentInfo}.
4454     */
4455    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4456        if (cookie instanceof Intent) {
4457            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4458                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4459            }
4460        }
4461
4462        boolean triaged = true;
4463        // Caller is asking for component details, so they'd better be
4464        // asking for specific encryption matching behavior, or be triaged
4465        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4466                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4467                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4468            triaged = false;
4469        }
4470        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4471            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4472                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4473        }
4474
4475        return updateFlags(flags, userId);
4476    }
4477
4478    /**
4479     * Update given intent when being used to request {@link ResolveInfo}.
4480     */
4481    private Intent updateIntentForResolve(Intent intent) {
4482        if (intent.getSelector() != null) {
4483            intent = intent.getSelector();
4484        }
4485        if (DEBUG_PREFERRED) {
4486            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4487        }
4488        return intent;
4489    }
4490
4491    /**
4492     * Update given flags when being used to request {@link ResolveInfo}.
4493     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4494     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4495     * flag set. However, this flag is only honoured in three circumstances:
4496     * <ul>
4497     * <li>when called from a system process</li>
4498     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4499     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4500     * action and a {@code android.intent.category.BROWSABLE} category</li>
4501     * </ul>
4502     */
4503    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4504        return updateFlagsForResolve(flags, userId, intent, callingUid,
4505                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4506    }
4507    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4508            boolean wantInstantApps) {
4509        return updateFlagsForResolve(flags, userId, intent, callingUid,
4510                wantInstantApps, false /*onlyExposedExplicitly*/);
4511    }
4512    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4513            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4514        // Safe mode means we shouldn't match any third-party components
4515        if (mSafeMode) {
4516            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4517        }
4518        if (getInstantAppPackageName(callingUid) != null) {
4519            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4520            if (onlyExposedExplicitly) {
4521                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4522            }
4523            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4524            flags |= PackageManager.MATCH_INSTANT;
4525        } else {
4526            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4527            final boolean allowMatchInstant =
4528                    (wantInstantApps
4529                            && Intent.ACTION_VIEW.equals(intent.getAction())
4530                            && hasWebURI(intent))
4531                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4532            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4533                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4534            if (!allowMatchInstant) {
4535                flags &= ~PackageManager.MATCH_INSTANT;
4536            }
4537        }
4538        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4539    }
4540
4541    @Override
4542    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4543        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4544    }
4545
4546    /**
4547     * Important: The provided filterCallingUid is used exclusively to filter out activities
4548     * that can be seen based on user state. It's typically the original caller uid prior
4549     * to clearing. Because it can only be provided by trusted code, it's value can be
4550     * trusted and will be used as-is; unlike userId which will be validated by this method.
4551     */
4552    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4553            int filterCallingUid, int userId) {
4554        if (!sUserManager.exists(userId)) return null;
4555        flags = updateFlagsForComponent(flags, userId, component);
4556        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4557                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4558        synchronized (mPackages) {
4559            PackageParser.Activity a = mActivities.mActivities.get(component);
4560
4561            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4562            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4563                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4564                if (ps == null) return null;
4565                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4566                    return null;
4567                }
4568                return PackageParser.generateActivityInfo(
4569                        a, flags, ps.readUserState(userId), userId);
4570            }
4571            if (mResolveComponentName.equals(component)) {
4572                return PackageParser.generateActivityInfo(
4573                        mResolveActivity, flags, new PackageUserState(), userId);
4574            }
4575        }
4576        return null;
4577    }
4578
4579    @Override
4580    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4581            String resolvedType) {
4582        synchronized (mPackages) {
4583            if (component.equals(mResolveComponentName)) {
4584                // The resolver supports EVERYTHING!
4585                return true;
4586            }
4587            final int callingUid = Binder.getCallingUid();
4588            final int callingUserId = UserHandle.getUserId(callingUid);
4589            PackageParser.Activity a = mActivities.mActivities.get(component);
4590            if (a == null) {
4591                return false;
4592            }
4593            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4594            if (ps == null) {
4595                return false;
4596            }
4597            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4598                return false;
4599            }
4600            for (int i=0; i<a.intents.size(); i++) {
4601                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4602                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4603                    return true;
4604                }
4605            }
4606            return false;
4607        }
4608    }
4609
4610    @Override
4611    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4612        if (!sUserManager.exists(userId)) return null;
4613        final int callingUid = Binder.getCallingUid();
4614        flags = updateFlagsForComponent(flags, userId, component);
4615        enforceCrossUserPermission(callingUid, userId,
4616                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4617        synchronized (mPackages) {
4618            PackageParser.Activity a = mReceivers.mActivities.get(component);
4619            if (DEBUG_PACKAGE_INFO) Log.v(
4620                TAG, "getReceiverInfo " + component + ": " + a);
4621            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4622                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4623                if (ps == null) return null;
4624                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4625                    return null;
4626                }
4627                return PackageParser.generateActivityInfo(
4628                        a, flags, ps.readUserState(userId), userId);
4629            }
4630        }
4631        return null;
4632    }
4633
4634    @Override
4635    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4636            int flags, int userId) {
4637        if (!sUserManager.exists(userId)) return null;
4638        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4639        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4640            return null;
4641        }
4642
4643        flags = updateFlagsForPackage(flags, userId, null);
4644
4645        final boolean canSeeStaticLibraries =
4646                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4647                        == PERMISSION_GRANTED
4648                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4649                        == PERMISSION_GRANTED
4650                || canRequestPackageInstallsInternal(packageName,
4651                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4652                        false  /* throwIfPermNotDeclared*/)
4653                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4654                        == PERMISSION_GRANTED;
4655
4656        synchronized (mPackages) {
4657            List<SharedLibraryInfo> result = null;
4658
4659            final int libCount = mSharedLibraries.size();
4660            for (int i = 0; i < libCount; i++) {
4661                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4662                if (versionedLib == null) {
4663                    continue;
4664                }
4665
4666                final int versionCount = versionedLib.size();
4667                for (int j = 0; j < versionCount; j++) {
4668                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4669                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4670                        break;
4671                    }
4672                    final long identity = Binder.clearCallingIdentity();
4673                    try {
4674                        PackageInfo packageInfo = getPackageInfoVersioned(
4675                                libInfo.getDeclaringPackage(), flags
4676                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4677                        if (packageInfo == null) {
4678                            continue;
4679                        }
4680                    } finally {
4681                        Binder.restoreCallingIdentity(identity);
4682                    }
4683
4684                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4685                            libInfo.getVersion(), libInfo.getType(),
4686                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4687                            flags, userId));
4688
4689                    if (result == null) {
4690                        result = new ArrayList<>();
4691                    }
4692                    result.add(resLibInfo);
4693                }
4694            }
4695
4696            return result != null ? new ParceledListSlice<>(result) : null;
4697        }
4698    }
4699
4700    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4701            SharedLibraryInfo libInfo, int flags, int userId) {
4702        List<VersionedPackage> versionedPackages = null;
4703        final int packageCount = mSettings.mPackages.size();
4704        for (int i = 0; i < packageCount; i++) {
4705            PackageSetting ps = mSettings.mPackages.valueAt(i);
4706
4707            if (ps == null) {
4708                continue;
4709            }
4710
4711            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4712                continue;
4713            }
4714
4715            final String libName = libInfo.getName();
4716            if (libInfo.isStatic()) {
4717                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4718                if (libIdx < 0) {
4719                    continue;
4720                }
4721                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4722                    continue;
4723                }
4724                if (versionedPackages == null) {
4725                    versionedPackages = new ArrayList<>();
4726                }
4727                // If the dependent is a static shared lib, use the public package name
4728                String dependentPackageName = ps.name;
4729                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4730                    dependentPackageName = ps.pkg.manifestPackageName;
4731                }
4732                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4733            } else if (ps.pkg != null) {
4734                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4735                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4736                    if (versionedPackages == null) {
4737                        versionedPackages = new ArrayList<>();
4738                    }
4739                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4740                }
4741            }
4742        }
4743
4744        return versionedPackages;
4745    }
4746
4747    @Override
4748    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4749        if (!sUserManager.exists(userId)) return null;
4750        final int callingUid = Binder.getCallingUid();
4751        flags = updateFlagsForComponent(flags, userId, component);
4752        enforceCrossUserPermission(callingUid, userId,
4753                false /* requireFullPermission */, false /* checkShell */, "get service info");
4754        synchronized (mPackages) {
4755            PackageParser.Service s = mServices.mServices.get(component);
4756            if (DEBUG_PACKAGE_INFO) Log.v(
4757                TAG, "getServiceInfo " + component + ": " + s);
4758            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4759                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4760                if (ps == null) return null;
4761                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4762                    return null;
4763                }
4764                return PackageParser.generateServiceInfo(
4765                        s, flags, ps.readUserState(userId), userId);
4766            }
4767        }
4768        return null;
4769    }
4770
4771    @Override
4772    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4773        if (!sUserManager.exists(userId)) return null;
4774        final int callingUid = Binder.getCallingUid();
4775        flags = updateFlagsForComponent(flags, userId, component);
4776        enforceCrossUserPermission(callingUid, userId,
4777                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4778        synchronized (mPackages) {
4779            PackageParser.Provider p = mProviders.mProviders.get(component);
4780            if (DEBUG_PACKAGE_INFO) Log.v(
4781                TAG, "getProviderInfo " + component + ": " + p);
4782            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4783                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4784                if (ps == null) return null;
4785                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4786                    return null;
4787                }
4788                return PackageParser.generateProviderInfo(
4789                        p, flags, ps.readUserState(userId), userId);
4790            }
4791        }
4792        return null;
4793    }
4794
4795    @Override
4796    public String[] getSystemSharedLibraryNames() {
4797        // allow instant applications
4798        synchronized (mPackages) {
4799            Set<String> libs = null;
4800            final int libCount = mSharedLibraries.size();
4801            for (int i = 0; i < libCount; i++) {
4802                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4803                if (versionedLib == null) {
4804                    continue;
4805                }
4806                final int versionCount = versionedLib.size();
4807                for (int j = 0; j < versionCount; j++) {
4808                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4809                    if (!libEntry.info.isStatic()) {
4810                        if (libs == null) {
4811                            libs = new ArraySet<>();
4812                        }
4813                        libs.add(libEntry.info.getName());
4814                        break;
4815                    }
4816                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4817                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4818                            UserHandle.getUserId(Binder.getCallingUid()),
4819                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4820                        if (libs == null) {
4821                            libs = new ArraySet<>();
4822                        }
4823                        libs.add(libEntry.info.getName());
4824                        break;
4825                    }
4826                }
4827            }
4828
4829            if (libs != null) {
4830                String[] libsArray = new String[libs.size()];
4831                libs.toArray(libsArray);
4832                return libsArray;
4833            }
4834
4835            return null;
4836        }
4837    }
4838
4839    @Override
4840    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4841        // allow instant applications
4842        synchronized (mPackages) {
4843            return mServicesSystemSharedLibraryPackageName;
4844        }
4845    }
4846
4847    @Override
4848    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4849        // allow instant applications
4850        synchronized (mPackages) {
4851            return mSharedSystemSharedLibraryPackageName;
4852        }
4853    }
4854
4855    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4856        for (int i = userList.length - 1; i >= 0; --i) {
4857            final int userId = userList[i];
4858            // don't add instant app to the list of updates
4859            if (pkgSetting.getInstantApp(userId)) {
4860                continue;
4861            }
4862            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4863            if (changedPackages == null) {
4864                changedPackages = new SparseArray<>();
4865                mChangedPackages.put(userId, changedPackages);
4866            }
4867            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4868            if (sequenceNumbers == null) {
4869                sequenceNumbers = new HashMap<>();
4870                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4871            }
4872            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4873            if (sequenceNumber != null) {
4874                changedPackages.remove(sequenceNumber);
4875            }
4876            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4877            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4878        }
4879        mChangedPackagesSequenceNumber++;
4880    }
4881
4882    @Override
4883    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4884        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4885            return null;
4886        }
4887        synchronized (mPackages) {
4888            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4889                return null;
4890            }
4891            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4892            if (changedPackages == null) {
4893                return null;
4894            }
4895            final List<String> packageNames =
4896                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4897            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4898                final String packageName = changedPackages.get(i);
4899                if (packageName != null) {
4900                    packageNames.add(packageName);
4901                }
4902            }
4903            return packageNames.isEmpty()
4904                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4905        }
4906    }
4907
4908    @Override
4909    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4910        // allow instant applications
4911        ArrayList<FeatureInfo> res;
4912        synchronized (mAvailableFeatures) {
4913            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4914            res.addAll(mAvailableFeatures.values());
4915        }
4916        final FeatureInfo fi = new FeatureInfo();
4917        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4918                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4919        res.add(fi);
4920
4921        return new ParceledListSlice<>(res);
4922    }
4923
4924    @Override
4925    public boolean hasSystemFeature(String name, int version) {
4926        // allow instant applications
4927        synchronized (mAvailableFeatures) {
4928            final FeatureInfo feat = mAvailableFeatures.get(name);
4929            if (feat == null) {
4930                return false;
4931            } else {
4932                return feat.version >= version;
4933            }
4934        }
4935    }
4936
4937    @Override
4938    public int checkPermission(String permName, String pkgName, int userId) {
4939        if (!sUserManager.exists(userId)) {
4940            return PackageManager.PERMISSION_DENIED;
4941        }
4942        final int callingUid = Binder.getCallingUid();
4943
4944        synchronized (mPackages) {
4945            final PackageParser.Package p = mPackages.get(pkgName);
4946            if (p != null && p.mExtras != null) {
4947                final PackageSetting ps = (PackageSetting) p.mExtras;
4948                if (filterAppAccessLPr(ps, callingUid, userId)) {
4949                    return PackageManager.PERMISSION_DENIED;
4950                }
4951                final boolean instantApp = ps.getInstantApp(userId);
4952                final PermissionsState permissionsState = ps.getPermissionsState();
4953                if (permissionsState.hasPermission(permName, userId)) {
4954                    if (instantApp) {
4955                        BasePermission bp = mSettings.mPermissions.get(permName);
4956                        if (bp != null && bp.isInstant()) {
4957                            return PackageManager.PERMISSION_GRANTED;
4958                        }
4959                    } else {
4960                        return PackageManager.PERMISSION_GRANTED;
4961                    }
4962                }
4963                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4964                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4965                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4966                    return PackageManager.PERMISSION_GRANTED;
4967                }
4968            }
4969        }
4970
4971        return PackageManager.PERMISSION_DENIED;
4972    }
4973
4974    @Override
4975    public int checkUidPermission(String permName, int uid) {
4976        final int callingUid = Binder.getCallingUid();
4977        final int callingUserId = UserHandle.getUserId(callingUid);
4978        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
4979        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
4980        final int userId = UserHandle.getUserId(uid);
4981        if (!sUserManager.exists(userId)) {
4982            return PackageManager.PERMISSION_DENIED;
4983        }
4984
4985        synchronized (mPackages) {
4986            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4987            if (obj != null) {
4988                if (obj instanceof SharedUserSetting) {
4989                    if (isCallerInstantApp) {
4990                        return PackageManager.PERMISSION_DENIED;
4991                    }
4992                } else if (obj instanceof PackageSetting) {
4993                    final PackageSetting ps = (PackageSetting) obj;
4994                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
4995                        return PackageManager.PERMISSION_DENIED;
4996                    }
4997                }
4998                final SettingBase settingBase = (SettingBase) obj;
4999                final PermissionsState permissionsState = settingBase.getPermissionsState();
5000                if (permissionsState.hasPermission(permName, userId)) {
5001                    if (isUidInstantApp) {
5002                        BasePermission bp = mSettings.mPermissions.get(permName);
5003                        if (bp != null && bp.isInstant()) {
5004                            return PackageManager.PERMISSION_GRANTED;
5005                        }
5006                    } else {
5007                        return PackageManager.PERMISSION_GRANTED;
5008                    }
5009                }
5010                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5011                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5012                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5013                    return PackageManager.PERMISSION_GRANTED;
5014                }
5015            } else {
5016                ArraySet<String> perms = mSystemPermissions.get(uid);
5017                if (perms != null) {
5018                    if (perms.contains(permName)) {
5019                        return PackageManager.PERMISSION_GRANTED;
5020                    }
5021                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5022                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5023                        return PackageManager.PERMISSION_GRANTED;
5024                    }
5025                }
5026            }
5027        }
5028
5029        return PackageManager.PERMISSION_DENIED;
5030    }
5031
5032    @Override
5033    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5034        if (UserHandle.getCallingUserId() != userId) {
5035            mContext.enforceCallingPermission(
5036                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5037                    "isPermissionRevokedByPolicy for user " + userId);
5038        }
5039
5040        if (checkPermission(permission, packageName, userId)
5041                == PackageManager.PERMISSION_GRANTED) {
5042            return false;
5043        }
5044
5045        final int callingUid = Binder.getCallingUid();
5046        if (getInstantAppPackageName(callingUid) != null) {
5047            if (!isCallerSameApp(packageName, callingUid)) {
5048                return false;
5049            }
5050        } else {
5051            if (isInstantApp(packageName, userId)) {
5052                return false;
5053            }
5054        }
5055
5056        final long identity = Binder.clearCallingIdentity();
5057        try {
5058            final int flags = getPermissionFlags(permission, packageName, userId);
5059            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5060        } finally {
5061            Binder.restoreCallingIdentity(identity);
5062        }
5063    }
5064
5065    @Override
5066    public String getPermissionControllerPackageName() {
5067        synchronized (mPackages) {
5068            return mRequiredInstallerPackage;
5069        }
5070    }
5071
5072    /**
5073     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5074     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5075     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5076     * @param message the message to log on security exception
5077     */
5078    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5079            boolean checkShell, String message) {
5080        if (userId < 0) {
5081            throw new IllegalArgumentException("Invalid userId " + userId);
5082        }
5083        if (checkShell) {
5084            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5085        }
5086        if (userId == UserHandle.getUserId(callingUid)) return;
5087        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5088            if (requireFullPermission) {
5089                mContext.enforceCallingOrSelfPermission(
5090                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5091            } else {
5092                try {
5093                    mContext.enforceCallingOrSelfPermission(
5094                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5095                } catch (SecurityException se) {
5096                    mContext.enforceCallingOrSelfPermission(
5097                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5098                }
5099            }
5100        }
5101    }
5102
5103    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5104        if (callingUid == Process.SHELL_UID) {
5105            if (userHandle >= 0
5106                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5107                throw new SecurityException("Shell does not have permission to access user "
5108                        + userHandle);
5109            } else if (userHandle < 0) {
5110                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5111                        + Debug.getCallers(3));
5112            }
5113        }
5114    }
5115
5116    private BasePermission findPermissionTreeLP(String permName) {
5117        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5118            if (permName.startsWith(bp.name) &&
5119                    permName.length() > bp.name.length() &&
5120                    permName.charAt(bp.name.length()) == '.') {
5121                return bp;
5122            }
5123        }
5124        return null;
5125    }
5126
5127    private BasePermission checkPermissionTreeLP(String permName) {
5128        if (permName != null) {
5129            BasePermission bp = findPermissionTreeLP(permName);
5130            if (bp != null) {
5131                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5132                    return bp;
5133                }
5134                throw new SecurityException("Calling uid "
5135                        + Binder.getCallingUid()
5136                        + " is not allowed to add to permission tree "
5137                        + bp.name + " owned by uid " + bp.uid);
5138            }
5139        }
5140        throw new SecurityException("No permission tree found for " + permName);
5141    }
5142
5143    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5144        if (s1 == null) {
5145            return s2 == null;
5146        }
5147        if (s2 == null) {
5148            return false;
5149        }
5150        if (s1.getClass() != s2.getClass()) {
5151            return false;
5152        }
5153        return s1.equals(s2);
5154    }
5155
5156    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5157        if (pi1.icon != pi2.icon) return false;
5158        if (pi1.logo != pi2.logo) return false;
5159        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5160        if (!compareStrings(pi1.name, pi2.name)) return false;
5161        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5162        // We'll take care of setting this one.
5163        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5164        // These are not currently stored in settings.
5165        //if (!compareStrings(pi1.group, pi2.group)) return false;
5166        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5167        //if (pi1.labelRes != pi2.labelRes) return false;
5168        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5169        return true;
5170    }
5171
5172    int permissionInfoFootprint(PermissionInfo info) {
5173        int size = info.name.length();
5174        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5175        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5176        return size;
5177    }
5178
5179    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5180        int size = 0;
5181        for (BasePermission perm : mSettings.mPermissions.values()) {
5182            if (perm.uid == tree.uid) {
5183                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5184            }
5185        }
5186        return size;
5187    }
5188
5189    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5190        // We calculate the max size of permissions defined by this uid and throw
5191        // if that plus the size of 'info' would exceed our stated maximum.
5192        if (tree.uid != Process.SYSTEM_UID) {
5193            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5194            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5195                throw new SecurityException("Permission tree size cap exceeded");
5196            }
5197        }
5198    }
5199
5200    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5201        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5202            throw new SecurityException("Instant apps can't add permissions");
5203        }
5204        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5205            throw new SecurityException("Label must be specified in permission");
5206        }
5207        BasePermission tree = checkPermissionTreeLP(info.name);
5208        BasePermission bp = mSettings.mPermissions.get(info.name);
5209        boolean added = bp == null;
5210        boolean changed = true;
5211        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5212        if (added) {
5213            enforcePermissionCapLocked(info, tree);
5214            bp = new BasePermission(info.name, tree.sourcePackage,
5215                    BasePermission.TYPE_DYNAMIC);
5216        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5217            throw new SecurityException(
5218                    "Not allowed to modify non-dynamic permission "
5219                    + info.name);
5220        } else {
5221            if (bp.protectionLevel == fixedLevel
5222                    && bp.perm.owner.equals(tree.perm.owner)
5223                    && bp.uid == tree.uid
5224                    && comparePermissionInfos(bp.perm.info, info)) {
5225                changed = false;
5226            }
5227        }
5228        bp.protectionLevel = fixedLevel;
5229        info = new PermissionInfo(info);
5230        info.protectionLevel = fixedLevel;
5231        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5232        bp.perm.info.packageName = tree.perm.info.packageName;
5233        bp.uid = tree.uid;
5234        if (added) {
5235            mSettings.mPermissions.put(info.name, bp);
5236        }
5237        if (changed) {
5238            if (!async) {
5239                mSettings.writeLPr();
5240            } else {
5241                scheduleWriteSettingsLocked();
5242            }
5243        }
5244        return added;
5245    }
5246
5247    @Override
5248    public boolean addPermission(PermissionInfo info) {
5249        synchronized (mPackages) {
5250            return addPermissionLocked(info, false);
5251        }
5252    }
5253
5254    @Override
5255    public boolean addPermissionAsync(PermissionInfo info) {
5256        synchronized (mPackages) {
5257            return addPermissionLocked(info, true);
5258        }
5259    }
5260
5261    @Override
5262    public void removePermission(String name) {
5263        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5264            throw new SecurityException("Instant applications don't have access to this method");
5265        }
5266        synchronized (mPackages) {
5267            checkPermissionTreeLP(name);
5268            BasePermission bp = mSettings.mPermissions.get(name);
5269            if (bp != null) {
5270                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5271                    throw new SecurityException(
5272                            "Not allowed to modify non-dynamic permission "
5273                            + name);
5274                }
5275                mSettings.mPermissions.remove(name);
5276                mSettings.writeLPr();
5277            }
5278        }
5279    }
5280
5281    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5282            PackageParser.Package pkg, BasePermission bp) {
5283        int index = pkg.requestedPermissions.indexOf(bp.name);
5284        if (index == -1) {
5285            throw new SecurityException("Package " + pkg.packageName
5286                    + " has not requested permission " + bp.name);
5287        }
5288        if (!bp.isRuntime() && !bp.isDevelopment()) {
5289            throw new SecurityException("Permission " + bp.name
5290                    + " is not a changeable permission type");
5291        }
5292    }
5293
5294    @Override
5295    public void grantRuntimePermission(String packageName, String name, final int userId) {
5296        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5297    }
5298
5299    private void grantRuntimePermission(String packageName, String name, final int userId,
5300            boolean overridePolicy) {
5301        if (!sUserManager.exists(userId)) {
5302            Log.e(TAG, "No such user:" + userId);
5303            return;
5304        }
5305        final int callingUid = Binder.getCallingUid();
5306
5307        mContext.enforceCallingOrSelfPermission(
5308                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5309                "grantRuntimePermission");
5310
5311        enforceCrossUserPermission(callingUid, userId,
5312                true /* requireFullPermission */, true /* checkShell */,
5313                "grantRuntimePermission");
5314
5315        final int uid;
5316        final PackageSetting ps;
5317
5318        synchronized (mPackages) {
5319            final PackageParser.Package pkg = mPackages.get(packageName);
5320            if (pkg == null) {
5321                throw new IllegalArgumentException("Unknown package: " + packageName);
5322            }
5323            final BasePermission bp = mSettings.mPermissions.get(name);
5324            if (bp == null) {
5325                throw new IllegalArgumentException("Unknown permission: " + name);
5326            }
5327            ps = (PackageSetting) pkg.mExtras;
5328            if (ps == null
5329                    || filterAppAccessLPr(ps, callingUid, userId)) {
5330                throw new IllegalArgumentException("Unknown package: " + packageName);
5331            }
5332
5333            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5334
5335            // If a permission review is required for legacy apps we represent
5336            // their permissions as always granted runtime ones since we need
5337            // to keep the review required permission flag per user while an
5338            // install permission's state is shared across all users.
5339            if (mPermissionReviewRequired
5340                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5341                    && bp.isRuntime()) {
5342                return;
5343            }
5344
5345            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5346
5347            final PermissionsState permissionsState = ps.getPermissionsState();
5348
5349            final int flags = permissionsState.getPermissionFlags(name, userId);
5350            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5351                throw new SecurityException("Cannot grant system fixed permission "
5352                        + name + " for package " + packageName);
5353            }
5354            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5355                throw new SecurityException("Cannot grant policy fixed permission "
5356                        + name + " for package " + packageName);
5357            }
5358
5359            if (bp.isDevelopment()) {
5360                // Development permissions must be handled specially, since they are not
5361                // normal runtime permissions.  For now they apply to all users.
5362                if (permissionsState.grantInstallPermission(bp) !=
5363                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5364                    scheduleWriteSettingsLocked();
5365                }
5366                return;
5367            }
5368
5369            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5370                throw new SecurityException("Cannot grant non-ephemeral permission"
5371                        + name + " for package " + packageName);
5372            }
5373
5374            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5375                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5376                return;
5377            }
5378
5379            final int result = permissionsState.grantRuntimePermission(bp, userId);
5380            switch (result) {
5381                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5382                    return;
5383                }
5384
5385                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5386                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5387                    mHandler.post(new Runnable() {
5388                        @Override
5389                        public void run() {
5390                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5391                        }
5392                    });
5393                }
5394                break;
5395            }
5396
5397            if (bp.isRuntime()) {
5398                logPermissionGranted(mContext, name, packageName);
5399            }
5400
5401            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5402
5403            // Not critical if that is lost - app has to request again.
5404            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5405        }
5406
5407        // Only need to do this if user is initialized. Otherwise it's a new user
5408        // and there are no processes running as the user yet and there's no need
5409        // to make an expensive call to remount processes for the changed permissions.
5410        if (READ_EXTERNAL_STORAGE.equals(name)
5411                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5412            final long token = Binder.clearCallingIdentity();
5413            try {
5414                if (sUserManager.isInitialized(userId)) {
5415                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5416                            StorageManagerInternal.class);
5417                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5418                }
5419            } finally {
5420                Binder.restoreCallingIdentity(token);
5421            }
5422        }
5423    }
5424
5425    @Override
5426    public void revokeRuntimePermission(String packageName, String name, int userId) {
5427        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5428    }
5429
5430    private void revokeRuntimePermission(String packageName, String name, int userId,
5431            boolean overridePolicy) {
5432        if (!sUserManager.exists(userId)) {
5433            Log.e(TAG, "No such user:" + userId);
5434            return;
5435        }
5436
5437        mContext.enforceCallingOrSelfPermission(
5438                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5439                "revokeRuntimePermission");
5440
5441        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5442                true /* requireFullPermission */, true /* checkShell */,
5443                "revokeRuntimePermission");
5444
5445        final int appId;
5446
5447        synchronized (mPackages) {
5448            final PackageParser.Package pkg = mPackages.get(packageName);
5449            if (pkg == null) {
5450                throw new IllegalArgumentException("Unknown package: " + packageName);
5451            }
5452            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5453            if (ps == null
5454                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5455                throw new IllegalArgumentException("Unknown package: " + packageName);
5456            }
5457            final BasePermission bp = mSettings.mPermissions.get(name);
5458            if (bp == null) {
5459                throw new IllegalArgumentException("Unknown permission: " + name);
5460            }
5461
5462            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5463
5464            // If a permission review is required for legacy apps we represent
5465            // their permissions as always granted runtime ones since we need
5466            // to keep the review required permission flag per user while an
5467            // install permission's state is shared across all users.
5468            if (mPermissionReviewRequired
5469                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5470                    && bp.isRuntime()) {
5471                return;
5472            }
5473
5474            final PermissionsState permissionsState = ps.getPermissionsState();
5475
5476            final int flags = permissionsState.getPermissionFlags(name, userId);
5477            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5478                throw new SecurityException("Cannot revoke system fixed permission "
5479                        + name + " for package " + packageName);
5480            }
5481            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5482                throw new SecurityException("Cannot revoke policy fixed permission "
5483                        + name + " for package " + packageName);
5484            }
5485
5486            if (bp.isDevelopment()) {
5487                // Development permissions must be handled specially, since they are not
5488                // normal runtime permissions.  For now they apply to all users.
5489                if (permissionsState.revokeInstallPermission(bp) !=
5490                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5491                    scheduleWriteSettingsLocked();
5492                }
5493                return;
5494            }
5495
5496            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5497                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5498                return;
5499            }
5500
5501            if (bp.isRuntime()) {
5502                logPermissionRevoked(mContext, name, packageName);
5503            }
5504
5505            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5506
5507            // Critical, after this call app should never have the permission.
5508            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5509
5510            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5511        }
5512
5513        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5514    }
5515
5516    /**
5517     * Get the first event id for the permission.
5518     *
5519     * <p>There are four events for each permission: <ul>
5520     *     <li>Request permission: first id + 0</li>
5521     *     <li>Grant permission: first id + 1</li>
5522     *     <li>Request for permission denied: first id + 2</li>
5523     *     <li>Revoke permission: first id + 3</li>
5524     * </ul></p>
5525     *
5526     * @param name name of the permission
5527     *
5528     * @return The first event id for the permission
5529     */
5530    private static int getBaseEventId(@NonNull String name) {
5531        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5532
5533        if (eventIdIndex == -1) {
5534            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5535                    || "user".equals(Build.TYPE)) {
5536                Log.i(TAG, "Unknown permission " + name);
5537
5538                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5539            } else {
5540                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5541                //
5542                // Also update
5543                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5544                // - metrics_constants.proto
5545                throw new IllegalStateException("Unknown permission " + name);
5546            }
5547        }
5548
5549        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5550    }
5551
5552    /**
5553     * Log that a permission was revoked.
5554     *
5555     * @param context Context of the caller
5556     * @param name name of the permission
5557     * @param packageName package permission if for
5558     */
5559    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5560            @NonNull String packageName) {
5561        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5562    }
5563
5564    /**
5565     * Log that a permission request was granted.
5566     *
5567     * @param context Context of the caller
5568     * @param name name of the permission
5569     * @param packageName package permission if for
5570     */
5571    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5572            @NonNull String packageName) {
5573        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5574    }
5575
5576    @Override
5577    public void resetRuntimePermissions() {
5578        mContext.enforceCallingOrSelfPermission(
5579                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5580                "revokeRuntimePermission");
5581
5582        int callingUid = Binder.getCallingUid();
5583        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5584            mContext.enforceCallingOrSelfPermission(
5585                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5586                    "resetRuntimePermissions");
5587        }
5588
5589        synchronized (mPackages) {
5590            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5591            for (int userId : UserManagerService.getInstance().getUserIds()) {
5592                final int packageCount = mPackages.size();
5593                for (int i = 0; i < packageCount; i++) {
5594                    PackageParser.Package pkg = mPackages.valueAt(i);
5595                    if (!(pkg.mExtras instanceof PackageSetting)) {
5596                        continue;
5597                    }
5598                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5599                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5600                }
5601            }
5602        }
5603    }
5604
5605    @Override
5606    public int getPermissionFlags(String name, String packageName, int userId) {
5607        if (!sUserManager.exists(userId)) {
5608            return 0;
5609        }
5610
5611        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5612
5613        final int callingUid = Binder.getCallingUid();
5614        enforceCrossUserPermission(callingUid, userId,
5615                true /* requireFullPermission */, false /* checkShell */,
5616                "getPermissionFlags");
5617
5618        synchronized (mPackages) {
5619            final PackageParser.Package pkg = mPackages.get(packageName);
5620            if (pkg == null) {
5621                return 0;
5622            }
5623            final BasePermission bp = mSettings.mPermissions.get(name);
5624            if (bp == null) {
5625                return 0;
5626            }
5627            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5628            if (ps == null
5629                    || filterAppAccessLPr(ps, callingUid, userId)) {
5630                return 0;
5631            }
5632            PermissionsState permissionsState = ps.getPermissionsState();
5633            return permissionsState.getPermissionFlags(name, userId);
5634        }
5635    }
5636
5637    @Override
5638    public void updatePermissionFlags(String name, String packageName, int flagMask,
5639            int flagValues, int userId) {
5640        if (!sUserManager.exists(userId)) {
5641            return;
5642        }
5643
5644        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5645
5646        final int callingUid = Binder.getCallingUid();
5647        enforceCrossUserPermission(callingUid, userId,
5648                true /* requireFullPermission */, true /* checkShell */,
5649                "updatePermissionFlags");
5650
5651        // Only the system can change these flags and nothing else.
5652        if (getCallingUid() != Process.SYSTEM_UID) {
5653            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5654            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5655            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5656            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5657            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5658        }
5659
5660        synchronized (mPackages) {
5661            final PackageParser.Package pkg = mPackages.get(packageName);
5662            if (pkg == null) {
5663                throw new IllegalArgumentException("Unknown package: " + packageName);
5664            }
5665            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5666            if (ps == null
5667                    || filterAppAccessLPr(ps, callingUid, userId)) {
5668                throw new IllegalArgumentException("Unknown package: " + packageName);
5669            }
5670
5671            final BasePermission bp = mSettings.mPermissions.get(name);
5672            if (bp == null) {
5673                throw new IllegalArgumentException("Unknown permission: " + name);
5674            }
5675
5676            PermissionsState permissionsState = ps.getPermissionsState();
5677
5678            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5679
5680            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5681                // Install and runtime permissions are stored in different places,
5682                // so figure out what permission changed and persist the change.
5683                if (permissionsState.getInstallPermissionState(name) != null) {
5684                    scheduleWriteSettingsLocked();
5685                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5686                        || hadState) {
5687                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5688                }
5689            }
5690        }
5691    }
5692
5693    /**
5694     * Update the permission flags for all packages and runtime permissions of a user in order
5695     * to allow device or profile owner to remove POLICY_FIXED.
5696     */
5697    @Override
5698    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5699        if (!sUserManager.exists(userId)) {
5700            return;
5701        }
5702
5703        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5704
5705        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5706                true /* requireFullPermission */, true /* checkShell */,
5707                "updatePermissionFlagsForAllApps");
5708
5709        // Only the system can change system fixed flags.
5710        if (getCallingUid() != Process.SYSTEM_UID) {
5711            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5712            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5713        }
5714
5715        synchronized (mPackages) {
5716            boolean changed = false;
5717            final int packageCount = mPackages.size();
5718            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5719                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5720                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5721                if (ps == null) {
5722                    continue;
5723                }
5724                PermissionsState permissionsState = ps.getPermissionsState();
5725                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5726                        userId, flagMask, flagValues);
5727            }
5728            if (changed) {
5729                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5730            }
5731        }
5732    }
5733
5734    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5735        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5736                != PackageManager.PERMISSION_GRANTED
5737            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5738                != PackageManager.PERMISSION_GRANTED) {
5739            throw new SecurityException(message + " requires "
5740                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5741                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5742        }
5743    }
5744
5745    @Override
5746    public boolean shouldShowRequestPermissionRationale(String permissionName,
5747            String packageName, int userId) {
5748        if (UserHandle.getCallingUserId() != userId) {
5749            mContext.enforceCallingPermission(
5750                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5751                    "canShowRequestPermissionRationale for user " + userId);
5752        }
5753
5754        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5755        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5756            return false;
5757        }
5758
5759        if (checkPermission(permissionName, packageName, userId)
5760                == PackageManager.PERMISSION_GRANTED) {
5761            return false;
5762        }
5763
5764        final int flags;
5765
5766        final long identity = Binder.clearCallingIdentity();
5767        try {
5768            flags = getPermissionFlags(permissionName,
5769                    packageName, userId);
5770        } finally {
5771            Binder.restoreCallingIdentity(identity);
5772        }
5773
5774        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5775                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5776                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5777
5778        if ((flags & fixedFlags) != 0) {
5779            return false;
5780        }
5781
5782        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5783    }
5784
5785    @Override
5786    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5787        mContext.enforceCallingOrSelfPermission(
5788                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5789                "addOnPermissionsChangeListener");
5790
5791        synchronized (mPackages) {
5792            mOnPermissionChangeListeners.addListenerLocked(listener);
5793        }
5794    }
5795
5796    @Override
5797    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5798        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5799            throw new SecurityException("Instant applications don't have access to this method");
5800        }
5801        synchronized (mPackages) {
5802            mOnPermissionChangeListeners.removeListenerLocked(listener);
5803        }
5804    }
5805
5806    @Override
5807    public boolean isProtectedBroadcast(String actionName) {
5808        // allow instant applications
5809        synchronized (mPackages) {
5810            if (mProtectedBroadcasts.contains(actionName)) {
5811                return true;
5812            } else if (actionName != null) {
5813                // TODO: remove these terrible hacks
5814                if (actionName.startsWith("android.net.netmon.lingerExpired")
5815                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5816                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5817                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5818                    return true;
5819                }
5820            }
5821        }
5822        return false;
5823    }
5824
5825    @Override
5826    public int checkSignatures(String pkg1, String pkg2) {
5827        synchronized (mPackages) {
5828            final PackageParser.Package p1 = mPackages.get(pkg1);
5829            final PackageParser.Package p2 = mPackages.get(pkg2);
5830            if (p1 == null || p1.mExtras == null
5831                    || p2 == null || p2.mExtras == null) {
5832                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5833            }
5834            final int callingUid = Binder.getCallingUid();
5835            final int callingUserId = UserHandle.getUserId(callingUid);
5836            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5837            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5838            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5839                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5840                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5841            }
5842            return compareSignatures(p1.mSignatures, p2.mSignatures);
5843        }
5844    }
5845
5846    @Override
5847    public int checkUidSignatures(int uid1, int uid2) {
5848        final int callingUid = Binder.getCallingUid();
5849        final int callingUserId = UserHandle.getUserId(callingUid);
5850        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5851        // Map to base uids.
5852        uid1 = UserHandle.getAppId(uid1);
5853        uid2 = UserHandle.getAppId(uid2);
5854        // reader
5855        synchronized (mPackages) {
5856            Signature[] s1;
5857            Signature[] s2;
5858            Object obj = mSettings.getUserIdLPr(uid1);
5859            if (obj != null) {
5860                if (obj instanceof SharedUserSetting) {
5861                    if (isCallerInstantApp) {
5862                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5863                    }
5864                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5865                } else if (obj instanceof PackageSetting) {
5866                    final PackageSetting ps = (PackageSetting) obj;
5867                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5868                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5869                    }
5870                    s1 = ps.signatures.mSignatures;
5871                } else {
5872                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5873                }
5874            } else {
5875                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5876            }
5877            obj = mSettings.getUserIdLPr(uid2);
5878            if (obj != null) {
5879                if (obj instanceof SharedUserSetting) {
5880                    if (isCallerInstantApp) {
5881                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5882                    }
5883                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5884                } else if (obj instanceof PackageSetting) {
5885                    final PackageSetting ps = (PackageSetting) obj;
5886                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5887                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5888                    }
5889                    s2 = ps.signatures.mSignatures;
5890                } else {
5891                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5892                }
5893            } else {
5894                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5895            }
5896            return compareSignatures(s1, s2);
5897        }
5898    }
5899
5900    /**
5901     * This method should typically only be used when granting or revoking
5902     * permissions, since the app may immediately restart after this call.
5903     * <p>
5904     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5905     * guard your work against the app being relaunched.
5906     */
5907    private void killUid(int appId, int userId, String reason) {
5908        final long identity = Binder.clearCallingIdentity();
5909        try {
5910            IActivityManager am = ActivityManager.getService();
5911            if (am != null) {
5912                try {
5913                    am.killUid(appId, userId, reason);
5914                } catch (RemoteException e) {
5915                    /* ignore - same process */
5916                }
5917            }
5918        } finally {
5919            Binder.restoreCallingIdentity(identity);
5920        }
5921    }
5922
5923    /**
5924     * Compares two sets of signatures. Returns:
5925     * <br />
5926     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5927     * <br />
5928     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5929     * <br />
5930     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5931     * <br />
5932     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5933     * <br />
5934     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5935     */
5936    static int compareSignatures(Signature[] s1, Signature[] s2) {
5937        if (s1 == null) {
5938            return s2 == null
5939                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5940                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5941        }
5942
5943        if (s2 == null) {
5944            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5945        }
5946
5947        if (s1.length != s2.length) {
5948            return PackageManager.SIGNATURE_NO_MATCH;
5949        }
5950
5951        // Since both signature sets are of size 1, we can compare without HashSets.
5952        if (s1.length == 1) {
5953            return s1[0].equals(s2[0]) ?
5954                    PackageManager.SIGNATURE_MATCH :
5955                    PackageManager.SIGNATURE_NO_MATCH;
5956        }
5957
5958        ArraySet<Signature> set1 = new ArraySet<Signature>();
5959        for (Signature sig : s1) {
5960            set1.add(sig);
5961        }
5962        ArraySet<Signature> set2 = new ArraySet<Signature>();
5963        for (Signature sig : s2) {
5964            set2.add(sig);
5965        }
5966        // Make sure s2 contains all signatures in s1.
5967        if (set1.equals(set2)) {
5968            return PackageManager.SIGNATURE_MATCH;
5969        }
5970        return PackageManager.SIGNATURE_NO_MATCH;
5971    }
5972
5973    /**
5974     * If the database version for this type of package (internal storage or
5975     * external storage) is less than the version where package signatures
5976     * were updated, return true.
5977     */
5978    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5979        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5980        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5981    }
5982
5983    /**
5984     * Used for backward compatibility to make sure any packages with
5985     * certificate chains get upgraded to the new style. {@code existingSigs}
5986     * will be in the old format (since they were stored on disk from before the
5987     * system upgrade) and {@code scannedSigs} will be in the newer format.
5988     */
5989    private int compareSignaturesCompat(PackageSignatures existingSigs,
5990            PackageParser.Package scannedPkg) {
5991        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5992            return PackageManager.SIGNATURE_NO_MATCH;
5993        }
5994
5995        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5996        for (Signature sig : existingSigs.mSignatures) {
5997            existingSet.add(sig);
5998        }
5999        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6000        for (Signature sig : scannedPkg.mSignatures) {
6001            try {
6002                Signature[] chainSignatures = sig.getChainSignatures();
6003                for (Signature chainSig : chainSignatures) {
6004                    scannedCompatSet.add(chainSig);
6005                }
6006            } catch (CertificateEncodingException e) {
6007                scannedCompatSet.add(sig);
6008            }
6009        }
6010        /*
6011         * Make sure the expanded scanned set contains all signatures in the
6012         * existing one.
6013         */
6014        if (scannedCompatSet.equals(existingSet)) {
6015            // Migrate the old signatures to the new scheme.
6016            existingSigs.assignSignatures(scannedPkg.mSignatures);
6017            // The new KeySets will be re-added later in the scanning process.
6018            synchronized (mPackages) {
6019                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6020            }
6021            return PackageManager.SIGNATURE_MATCH;
6022        }
6023        return PackageManager.SIGNATURE_NO_MATCH;
6024    }
6025
6026    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6027        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6028        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6029    }
6030
6031    private int compareSignaturesRecover(PackageSignatures existingSigs,
6032            PackageParser.Package scannedPkg) {
6033        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6034            return PackageManager.SIGNATURE_NO_MATCH;
6035        }
6036
6037        String msg = null;
6038        try {
6039            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6040                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6041                        + scannedPkg.packageName);
6042                return PackageManager.SIGNATURE_MATCH;
6043            }
6044        } catch (CertificateException e) {
6045            msg = e.getMessage();
6046        }
6047
6048        logCriticalInfo(Log.INFO,
6049                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6050        return PackageManager.SIGNATURE_NO_MATCH;
6051    }
6052
6053    @Override
6054    public List<String> getAllPackages() {
6055        final int callingUid = Binder.getCallingUid();
6056        final int callingUserId = UserHandle.getUserId(callingUid);
6057        synchronized (mPackages) {
6058            if (canViewInstantApps(callingUid, callingUserId)) {
6059                return new ArrayList<String>(mPackages.keySet());
6060            }
6061            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6062            final List<String> result = new ArrayList<>();
6063            if (instantAppPkgName != null) {
6064                // caller is an instant application; filter unexposed applications
6065                for (PackageParser.Package pkg : mPackages.values()) {
6066                    if (!pkg.visibleToInstantApps) {
6067                        continue;
6068                    }
6069                    result.add(pkg.packageName);
6070                }
6071            } else {
6072                // caller is a normal application; filter instant applications
6073                for (PackageParser.Package pkg : mPackages.values()) {
6074                    final PackageSetting ps =
6075                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6076                    if (ps != null
6077                            && ps.getInstantApp(callingUserId)
6078                            && !mInstantAppRegistry.isInstantAccessGranted(
6079                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6080                        continue;
6081                    }
6082                    result.add(pkg.packageName);
6083                }
6084            }
6085            return result;
6086        }
6087    }
6088
6089    @Override
6090    public String[] getPackagesForUid(int uid) {
6091        final int callingUid = Binder.getCallingUid();
6092        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6093        final int userId = UserHandle.getUserId(uid);
6094        uid = UserHandle.getAppId(uid);
6095        // reader
6096        synchronized (mPackages) {
6097            Object obj = mSettings.getUserIdLPr(uid);
6098            if (obj instanceof SharedUserSetting) {
6099                if (isCallerInstantApp) {
6100                    return null;
6101                }
6102                final SharedUserSetting sus = (SharedUserSetting) obj;
6103                final int N = sus.packages.size();
6104                String[] res = new String[N];
6105                final Iterator<PackageSetting> it = sus.packages.iterator();
6106                int i = 0;
6107                while (it.hasNext()) {
6108                    PackageSetting ps = it.next();
6109                    if (ps.getInstalled(userId)) {
6110                        res[i++] = ps.name;
6111                    } else {
6112                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6113                    }
6114                }
6115                return res;
6116            } else if (obj instanceof PackageSetting) {
6117                final PackageSetting ps = (PackageSetting) obj;
6118                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6119                    return new String[]{ps.name};
6120                }
6121            }
6122        }
6123        return null;
6124    }
6125
6126    @Override
6127    public String getNameForUid(int uid) {
6128        final int callingUid = Binder.getCallingUid();
6129        if (getInstantAppPackageName(callingUid) != null) {
6130            return null;
6131        }
6132        synchronized (mPackages) {
6133            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6134            if (obj instanceof SharedUserSetting) {
6135                final SharedUserSetting sus = (SharedUserSetting) obj;
6136                return sus.name + ":" + sus.userId;
6137            } else if (obj instanceof PackageSetting) {
6138                final PackageSetting ps = (PackageSetting) obj;
6139                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6140                    return null;
6141                }
6142                return ps.name;
6143            }
6144        }
6145        return null;
6146    }
6147
6148    @Override
6149    public int getUidForSharedUser(String sharedUserName) {
6150        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6151            return -1;
6152        }
6153        if (sharedUserName == null) {
6154            return -1;
6155        }
6156        // reader
6157        synchronized (mPackages) {
6158            SharedUserSetting suid;
6159            try {
6160                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6161                if (suid != null) {
6162                    return suid.userId;
6163                }
6164            } catch (PackageManagerException ignore) {
6165                // can't happen, but, still need to catch it
6166            }
6167            return -1;
6168        }
6169    }
6170
6171    @Override
6172    public int getFlagsForUid(int uid) {
6173        final int callingUid = Binder.getCallingUid();
6174        if (getInstantAppPackageName(callingUid) != null) {
6175            return 0;
6176        }
6177        synchronized (mPackages) {
6178            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6179            if (obj instanceof SharedUserSetting) {
6180                final SharedUserSetting sus = (SharedUserSetting) obj;
6181                return sus.pkgFlags;
6182            } else if (obj instanceof PackageSetting) {
6183                final PackageSetting ps = (PackageSetting) obj;
6184                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6185                    return 0;
6186                }
6187                return ps.pkgFlags;
6188            }
6189        }
6190        return 0;
6191    }
6192
6193    @Override
6194    public int getPrivateFlagsForUid(int uid) {
6195        final int callingUid = Binder.getCallingUid();
6196        if (getInstantAppPackageName(callingUid) != null) {
6197            return 0;
6198        }
6199        synchronized (mPackages) {
6200            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6201            if (obj instanceof SharedUserSetting) {
6202                final SharedUserSetting sus = (SharedUserSetting) obj;
6203                return sus.pkgPrivateFlags;
6204            } else if (obj instanceof PackageSetting) {
6205                final PackageSetting ps = (PackageSetting) obj;
6206                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6207                    return 0;
6208                }
6209                return ps.pkgPrivateFlags;
6210            }
6211        }
6212        return 0;
6213    }
6214
6215    @Override
6216    public boolean isUidPrivileged(int uid) {
6217        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6218            return false;
6219        }
6220        uid = UserHandle.getAppId(uid);
6221        // reader
6222        synchronized (mPackages) {
6223            Object obj = mSettings.getUserIdLPr(uid);
6224            if (obj instanceof SharedUserSetting) {
6225                final SharedUserSetting sus = (SharedUserSetting) obj;
6226                final Iterator<PackageSetting> it = sus.packages.iterator();
6227                while (it.hasNext()) {
6228                    if (it.next().isPrivileged()) {
6229                        return true;
6230                    }
6231                }
6232            } else if (obj instanceof PackageSetting) {
6233                final PackageSetting ps = (PackageSetting) obj;
6234                return ps.isPrivileged();
6235            }
6236        }
6237        return false;
6238    }
6239
6240    @Override
6241    public String[] getAppOpPermissionPackages(String permissionName) {
6242        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6243            return null;
6244        }
6245        synchronized (mPackages) {
6246            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6247            if (pkgs == null) {
6248                return null;
6249            }
6250            return pkgs.toArray(new String[pkgs.size()]);
6251        }
6252    }
6253
6254    @Override
6255    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6256            int flags, int userId) {
6257        return resolveIntentInternal(
6258                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6259    }
6260
6261    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6262            int flags, int userId, boolean resolveForStart) {
6263        try {
6264            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6265
6266            if (!sUserManager.exists(userId)) return null;
6267            final int callingUid = Binder.getCallingUid();
6268            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6269            enforceCrossUserPermission(callingUid, userId,
6270                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6271
6272            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6273            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6274                    flags, callingUid, userId, resolveForStart);
6275            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6276
6277            final ResolveInfo bestChoice =
6278                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6279            return bestChoice;
6280        } finally {
6281            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6282        }
6283    }
6284
6285    @Override
6286    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6287        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6288            throw new SecurityException(
6289                    "findPersistentPreferredActivity can only be run by the system");
6290        }
6291        if (!sUserManager.exists(userId)) {
6292            return null;
6293        }
6294        final int callingUid = Binder.getCallingUid();
6295        intent = updateIntentForResolve(intent);
6296        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6297        final int flags = updateFlagsForResolve(
6298                0, userId, intent, callingUid, false /*includeInstantApps*/);
6299        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6300                userId);
6301        synchronized (mPackages) {
6302            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6303                    userId);
6304        }
6305    }
6306
6307    @Override
6308    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6309            IntentFilter filter, int match, ComponentName activity) {
6310        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6311            return;
6312        }
6313        final int userId = UserHandle.getCallingUserId();
6314        if (DEBUG_PREFERRED) {
6315            Log.v(TAG, "setLastChosenActivity intent=" + intent
6316                + " resolvedType=" + resolvedType
6317                + " flags=" + flags
6318                + " filter=" + filter
6319                + " match=" + match
6320                + " activity=" + activity);
6321            filter.dump(new PrintStreamPrinter(System.out), "    ");
6322        }
6323        intent.setComponent(null);
6324        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6325                userId);
6326        // Find any earlier preferred or last chosen entries and nuke them
6327        findPreferredActivity(intent, resolvedType,
6328                flags, query, 0, false, true, false, userId);
6329        // Add the new activity as the last chosen for this filter
6330        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6331                "Setting last chosen");
6332    }
6333
6334    @Override
6335    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6336        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6337            return null;
6338        }
6339        final int userId = UserHandle.getCallingUserId();
6340        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6341        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6342                userId);
6343        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6344                false, false, false, userId);
6345    }
6346
6347    /**
6348     * Returns whether or not instant apps have been disabled remotely.
6349     */
6350    private boolean isEphemeralDisabled() {
6351        return mEphemeralAppsDisabled;
6352    }
6353
6354    private boolean isInstantAppAllowed(
6355            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6356            boolean skipPackageCheck) {
6357        if (mInstantAppResolverConnection == null) {
6358            return false;
6359        }
6360        if (mInstantAppInstallerActivity == null) {
6361            return false;
6362        }
6363        if (intent.getComponent() != null) {
6364            return false;
6365        }
6366        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6367            return false;
6368        }
6369        if (!skipPackageCheck && intent.getPackage() != null) {
6370            return false;
6371        }
6372        final boolean isWebUri = hasWebURI(intent);
6373        if (!isWebUri || intent.getData().getHost() == null) {
6374            return false;
6375        }
6376        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6377        // Or if there's already an ephemeral app installed that handles the action
6378        synchronized (mPackages) {
6379            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6380            for (int n = 0; n < count; n++) {
6381                final ResolveInfo info = resolvedActivities.get(n);
6382                final String packageName = info.activityInfo.packageName;
6383                final PackageSetting ps = mSettings.mPackages.get(packageName);
6384                if (ps != null) {
6385                    // only check domain verification status if the app is not a browser
6386                    if (!info.handleAllWebDataURI) {
6387                        // Try to get the status from User settings first
6388                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6389                        final int status = (int) (packedStatus >> 32);
6390                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6391                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6392                            if (DEBUG_EPHEMERAL) {
6393                                Slog.v(TAG, "DENY instant app;"
6394                                    + " pkg: " + packageName + ", status: " + status);
6395                            }
6396                            return false;
6397                        }
6398                    }
6399                    if (ps.getInstantApp(userId)) {
6400                        if (DEBUG_EPHEMERAL) {
6401                            Slog.v(TAG, "DENY instant app installed;"
6402                                    + " pkg: " + packageName);
6403                        }
6404                        return false;
6405                    }
6406                }
6407            }
6408        }
6409        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6410        return true;
6411    }
6412
6413    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6414            Intent origIntent, String resolvedType, String callingPackage,
6415            Bundle verificationBundle, int userId) {
6416        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6417                new InstantAppRequest(responseObj, origIntent, resolvedType,
6418                        callingPackage, userId, verificationBundle));
6419        mHandler.sendMessage(msg);
6420    }
6421
6422    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6423            int flags, List<ResolveInfo> query, int userId) {
6424        if (query != null) {
6425            final int N = query.size();
6426            if (N == 1) {
6427                return query.get(0);
6428            } else if (N > 1) {
6429                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6430                // If there is more than one activity with the same priority,
6431                // then let the user decide between them.
6432                ResolveInfo r0 = query.get(0);
6433                ResolveInfo r1 = query.get(1);
6434                if (DEBUG_INTENT_MATCHING || debug) {
6435                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6436                            + r1.activityInfo.name + "=" + r1.priority);
6437                }
6438                // If the first activity has a higher priority, or a different
6439                // default, then it is always desirable to pick it.
6440                if (r0.priority != r1.priority
6441                        || r0.preferredOrder != r1.preferredOrder
6442                        || r0.isDefault != r1.isDefault) {
6443                    return query.get(0);
6444                }
6445                // If we have saved a preference for a preferred activity for
6446                // this Intent, use that.
6447                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6448                        flags, query, r0.priority, true, false, debug, userId);
6449                if (ri != null) {
6450                    return ri;
6451                }
6452                // If we have an ephemeral app, use it
6453                for (int i = 0; i < N; i++) {
6454                    ri = query.get(i);
6455                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6456                        final String packageName = ri.activityInfo.packageName;
6457                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6458                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6459                        final int status = (int)(packedStatus >> 32);
6460                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6461                            return ri;
6462                        }
6463                    }
6464                }
6465                ri = new ResolveInfo(mResolveInfo);
6466                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6467                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6468                // If all of the options come from the same package, show the application's
6469                // label and icon instead of the generic resolver's.
6470                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6471                // and then throw away the ResolveInfo itself, meaning that the caller loses
6472                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6473                // a fallback for this case; we only set the target package's resources on
6474                // the ResolveInfo, not the ActivityInfo.
6475                final String intentPackage = intent.getPackage();
6476                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6477                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6478                    ri.resolvePackageName = intentPackage;
6479                    if (userNeedsBadging(userId)) {
6480                        ri.noResourceId = true;
6481                    } else {
6482                        ri.icon = appi.icon;
6483                    }
6484                    ri.iconResourceId = appi.icon;
6485                    ri.labelRes = appi.labelRes;
6486                }
6487                ri.activityInfo.applicationInfo = new ApplicationInfo(
6488                        ri.activityInfo.applicationInfo);
6489                if (userId != 0) {
6490                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6491                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6492                }
6493                // Make sure that the resolver is displayable in car mode
6494                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6495                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6496                return ri;
6497            }
6498        }
6499        return null;
6500    }
6501
6502    /**
6503     * Return true if the given list is not empty and all of its contents have
6504     * an activityInfo with the given package name.
6505     */
6506    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6507        if (ArrayUtils.isEmpty(list)) {
6508            return false;
6509        }
6510        for (int i = 0, N = list.size(); i < N; i++) {
6511            final ResolveInfo ri = list.get(i);
6512            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6513            if (ai == null || !packageName.equals(ai.packageName)) {
6514                return false;
6515            }
6516        }
6517        return true;
6518    }
6519
6520    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6521            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6522        final int N = query.size();
6523        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6524                .get(userId);
6525        // Get the list of persistent preferred activities that handle the intent
6526        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6527        List<PersistentPreferredActivity> pprefs = ppir != null
6528                ? ppir.queryIntent(intent, resolvedType,
6529                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6530                        userId)
6531                : null;
6532        if (pprefs != null && pprefs.size() > 0) {
6533            final int M = pprefs.size();
6534            for (int i=0; i<M; i++) {
6535                final PersistentPreferredActivity ppa = pprefs.get(i);
6536                if (DEBUG_PREFERRED || debug) {
6537                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6538                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6539                            + "\n  component=" + ppa.mComponent);
6540                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6541                }
6542                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6543                        flags | MATCH_DISABLED_COMPONENTS, userId);
6544                if (DEBUG_PREFERRED || debug) {
6545                    Slog.v(TAG, "Found persistent preferred activity:");
6546                    if (ai != null) {
6547                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6548                    } else {
6549                        Slog.v(TAG, "  null");
6550                    }
6551                }
6552                if (ai == null) {
6553                    // This previously registered persistent preferred activity
6554                    // component is no longer known. Ignore it and do NOT remove it.
6555                    continue;
6556                }
6557                for (int j=0; j<N; j++) {
6558                    final ResolveInfo ri = query.get(j);
6559                    if (!ri.activityInfo.applicationInfo.packageName
6560                            .equals(ai.applicationInfo.packageName)) {
6561                        continue;
6562                    }
6563                    if (!ri.activityInfo.name.equals(ai.name)) {
6564                        continue;
6565                    }
6566                    //  Found a persistent preference that can handle the intent.
6567                    if (DEBUG_PREFERRED || debug) {
6568                        Slog.v(TAG, "Returning persistent preferred activity: " +
6569                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6570                    }
6571                    return ri;
6572                }
6573            }
6574        }
6575        return null;
6576    }
6577
6578    // TODO: handle preferred activities missing while user has amnesia
6579    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6580            List<ResolveInfo> query, int priority, boolean always,
6581            boolean removeMatches, boolean debug, int userId) {
6582        if (!sUserManager.exists(userId)) return null;
6583        final int callingUid = Binder.getCallingUid();
6584        flags = updateFlagsForResolve(
6585                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6586        intent = updateIntentForResolve(intent);
6587        // writer
6588        synchronized (mPackages) {
6589            // Try to find a matching persistent preferred activity.
6590            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6591                    debug, userId);
6592
6593            // If a persistent preferred activity matched, use it.
6594            if (pri != null) {
6595                return pri;
6596            }
6597
6598            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6599            // Get the list of preferred activities that handle the intent
6600            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6601            List<PreferredActivity> prefs = pir != null
6602                    ? pir.queryIntent(intent, resolvedType,
6603                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6604                            userId)
6605                    : null;
6606            if (prefs != null && prefs.size() > 0) {
6607                boolean changed = false;
6608                try {
6609                    // First figure out how good the original match set is.
6610                    // We will only allow preferred activities that came
6611                    // from the same match quality.
6612                    int match = 0;
6613
6614                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6615
6616                    final int N = query.size();
6617                    for (int j=0; j<N; j++) {
6618                        final ResolveInfo ri = query.get(j);
6619                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6620                                + ": 0x" + Integer.toHexString(match));
6621                        if (ri.match > match) {
6622                            match = ri.match;
6623                        }
6624                    }
6625
6626                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6627                            + Integer.toHexString(match));
6628
6629                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6630                    final int M = prefs.size();
6631                    for (int i=0; i<M; i++) {
6632                        final PreferredActivity pa = prefs.get(i);
6633                        if (DEBUG_PREFERRED || debug) {
6634                            Slog.v(TAG, "Checking PreferredActivity ds="
6635                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6636                                    + "\n  component=" + pa.mPref.mComponent);
6637                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6638                        }
6639                        if (pa.mPref.mMatch != match) {
6640                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6641                                    + Integer.toHexString(pa.mPref.mMatch));
6642                            continue;
6643                        }
6644                        // If it's not an "always" type preferred activity and that's what we're
6645                        // looking for, skip it.
6646                        if (always && !pa.mPref.mAlways) {
6647                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6648                            continue;
6649                        }
6650                        final ActivityInfo ai = getActivityInfo(
6651                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6652                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6653                                userId);
6654                        if (DEBUG_PREFERRED || debug) {
6655                            Slog.v(TAG, "Found preferred activity:");
6656                            if (ai != null) {
6657                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6658                            } else {
6659                                Slog.v(TAG, "  null");
6660                            }
6661                        }
6662                        if (ai == null) {
6663                            // This previously registered preferred activity
6664                            // component is no longer known.  Most likely an update
6665                            // to the app was installed and in the new version this
6666                            // component no longer exists.  Clean it up by removing
6667                            // it from the preferred activities list, and skip it.
6668                            Slog.w(TAG, "Removing dangling preferred activity: "
6669                                    + pa.mPref.mComponent);
6670                            pir.removeFilter(pa);
6671                            changed = true;
6672                            continue;
6673                        }
6674                        for (int j=0; j<N; j++) {
6675                            final ResolveInfo ri = query.get(j);
6676                            if (!ri.activityInfo.applicationInfo.packageName
6677                                    .equals(ai.applicationInfo.packageName)) {
6678                                continue;
6679                            }
6680                            if (!ri.activityInfo.name.equals(ai.name)) {
6681                                continue;
6682                            }
6683
6684                            if (removeMatches) {
6685                                pir.removeFilter(pa);
6686                                changed = true;
6687                                if (DEBUG_PREFERRED) {
6688                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6689                                }
6690                                break;
6691                            }
6692
6693                            // Okay we found a previously set preferred or last chosen app.
6694                            // If the result set is different from when this
6695                            // was created, we need to clear it and re-ask the
6696                            // user their preference, if we're looking for an "always" type entry.
6697                            if (always && !pa.mPref.sameSet(query)) {
6698                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6699                                        + intent + " type " + resolvedType);
6700                                if (DEBUG_PREFERRED) {
6701                                    Slog.v(TAG, "Removing preferred activity since set changed "
6702                                            + pa.mPref.mComponent);
6703                                }
6704                                pir.removeFilter(pa);
6705                                // Re-add the filter as a "last chosen" entry (!always)
6706                                PreferredActivity lastChosen = new PreferredActivity(
6707                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6708                                pir.addFilter(lastChosen);
6709                                changed = true;
6710                                return null;
6711                            }
6712
6713                            // Yay! Either the set matched or we're looking for the last chosen
6714                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6715                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6716                            return ri;
6717                        }
6718                    }
6719                } finally {
6720                    if (changed) {
6721                        if (DEBUG_PREFERRED) {
6722                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6723                        }
6724                        scheduleWritePackageRestrictionsLocked(userId);
6725                    }
6726                }
6727            }
6728        }
6729        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6730        return null;
6731    }
6732
6733    /*
6734     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6735     */
6736    @Override
6737    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6738            int targetUserId) {
6739        mContext.enforceCallingOrSelfPermission(
6740                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6741        List<CrossProfileIntentFilter> matches =
6742                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6743        if (matches != null) {
6744            int size = matches.size();
6745            for (int i = 0; i < size; i++) {
6746                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6747            }
6748        }
6749        if (hasWebURI(intent)) {
6750            // cross-profile app linking works only towards the parent.
6751            final int callingUid = Binder.getCallingUid();
6752            final UserInfo parent = getProfileParent(sourceUserId);
6753            synchronized(mPackages) {
6754                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6755                        false /*includeInstantApps*/);
6756                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6757                        intent, resolvedType, flags, sourceUserId, parent.id);
6758                return xpDomainInfo != null;
6759            }
6760        }
6761        return false;
6762    }
6763
6764    private UserInfo getProfileParent(int userId) {
6765        final long identity = Binder.clearCallingIdentity();
6766        try {
6767            return sUserManager.getProfileParent(userId);
6768        } finally {
6769            Binder.restoreCallingIdentity(identity);
6770        }
6771    }
6772
6773    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6774            String resolvedType, int userId) {
6775        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6776        if (resolver != null) {
6777            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6778        }
6779        return null;
6780    }
6781
6782    @Override
6783    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6784            String resolvedType, int flags, int userId) {
6785        try {
6786            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6787
6788            return new ParceledListSlice<>(
6789                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6790        } finally {
6791            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6792        }
6793    }
6794
6795    /**
6796     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6797     * instant, returns {@code null}.
6798     */
6799    private String getInstantAppPackageName(int callingUid) {
6800        synchronized (mPackages) {
6801            // If the caller is an isolated app use the owner's uid for the lookup.
6802            if (Process.isIsolated(callingUid)) {
6803                callingUid = mIsolatedOwners.get(callingUid);
6804            }
6805            final int appId = UserHandle.getAppId(callingUid);
6806            final Object obj = mSettings.getUserIdLPr(appId);
6807            if (obj instanceof PackageSetting) {
6808                final PackageSetting ps = (PackageSetting) obj;
6809                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6810                return isInstantApp ? ps.pkg.packageName : null;
6811            }
6812        }
6813        return null;
6814    }
6815
6816    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6817            String resolvedType, int flags, int userId) {
6818        return queryIntentActivitiesInternal(
6819                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6820    }
6821
6822    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6823            String resolvedType, int flags, int filterCallingUid, int userId,
6824            boolean resolveForStart) {
6825        if (!sUserManager.exists(userId)) return Collections.emptyList();
6826        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6827        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6828                false /* requireFullPermission */, false /* checkShell */,
6829                "query intent activities");
6830        final String pkgName = intent.getPackage();
6831        ComponentName comp = intent.getComponent();
6832        if (comp == null) {
6833            if (intent.getSelector() != null) {
6834                intent = intent.getSelector();
6835                comp = intent.getComponent();
6836            }
6837        }
6838
6839        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6840                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6841        if (comp != null) {
6842            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6843            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6844            if (ai != null) {
6845                // When specifying an explicit component, we prevent the activity from being
6846                // used when either 1) the calling package is normal and the activity is within
6847                // an ephemeral application or 2) the calling package is ephemeral and the
6848                // activity is not visible to ephemeral applications.
6849                final boolean matchInstantApp =
6850                        (flags & PackageManager.MATCH_INSTANT) != 0;
6851                final boolean matchVisibleToInstantAppOnly =
6852                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6853                final boolean matchExplicitlyVisibleOnly =
6854                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6855                final boolean isCallerInstantApp =
6856                        instantAppPkgName != null;
6857                final boolean isTargetSameInstantApp =
6858                        comp.getPackageName().equals(instantAppPkgName);
6859                final boolean isTargetInstantApp =
6860                        (ai.applicationInfo.privateFlags
6861                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6862                final boolean isTargetVisibleToInstantApp =
6863                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6864                final boolean isTargetExplicitlyVisibleToInstantApp =
6865                        isTargetVisibleToInstantApp
6866                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6867                final boolean isTargetHiddenFromInstantApp =
6868                        !isTargetVisibleToInstantApp
6869                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6870                final boolean blockResolution =
6871                        !isTargetSameInstantApp
6872                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6873                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6874                                        && isTargetHiddenFromInstantApp));
6875                if (!blockResolution) {
6876                    final ResolveInfo ri = new ResolveInfo();
6877                    ri.activityInfo = ai;
6878                    list.add(ri);
6879                }
6880            }
6881            return applyPostResolutionFilter(list, instantAppPkgName);
6882        }
6883
6884        // reader
6885        boolean sortResult = false;
6886        boolean addEphemeral = false;
6887        List<ResolveInfo> result;
6888        final boolean ephemeralDisabled = isEphemeralDisabled();
6889        synchronized (mPackages) {
6890            if (pkgName == null) {
6891                List<CrossProfileIntentFilter> matchingFilters =
6892                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6893                // Check for results that need to skip the current profile.
6894                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6895                        resolvedType, flags, userId);
6896                if (xpResolveInfo != null) {
6897                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6898                    xpResult.add(xpResolveInfo);
6899                    return applyPostResolutionFilter(
6900                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6901                }
6902
6903                // Check for results in the current profile.
6904                result = filterIfNotSystemUser(mActivities.queryIntent(
6905                        intent, resolvedType, flags, userId), userId);
6906                addEphemeral = !ephemeralDisabled
6907                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6908                // Check for cross profile results.
6909                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6910                xpResolveInfo = queryCrossProfileIntents(
6911                        matchingFilters, intent, resolvedType, flags, userId,
6912                        hasNonNegativePriorityResult);
6913                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6914                    boolean isVisibleToUser = filterIfNotSystemUser(
6915                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6916                    if (isVisibleToUser) {
6917                        result.add(xpResolveInfo);
6918                        sortResult = true;
6919                    }
6920                }
6921                if (hasWebURI(intent)) {
6922                    CrossProfileDomainInfo xpDomainInfo = null;
6923                    final UserInfo parent = getProfileParent(userId);
6924                    if (parent != null) {
6925                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6926                                flags, userId, parent.id);
6927                    }
6928                    if (xpDomainInfo != null) {
6929                        if (xpResolveInfo != null) {
6930                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6931                            // in the result.
6932                            result.remove(xpResolveInfo);
6933                        }
6934                        if (result.size() == 0 && !addEphemeral) {
6935                            // No result in current profile, but found candidate in parent user.
6936                            // And we are not going to add emphemeral app, so we can return the
6937                            // result straight away.
6938                            result.add(xpDomainInfo.resolveInfo);
6939                            return applyPostResolutionFilter(result, instantAppPkgName);
6940                        }
6941                    } else if (result.size() <= 1 && !addEphemeral) {
6942                        // No result in parent user and <= 1 result in current profile, and we
6943                        // are not going to add emphemeral app, so we can return the result without
6944                        // further processing.
6945                        return applyPostResolutionFilter(result, instantAppPkgName);
6946                    }
6947                    // We have more than one candidate (combining results from current and parent
6948                    // profile), so we need filtering and sorting.
6949                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6950                            intent, flags, result, xpDomainInfo, userId);
6951                    sortResult = true;
6952                }
6953            } else {
6954                final PackageParser.Package pkg = mPackages.get(pkgName);
6955                result = null;
6956                if (pkg != null) {
6957                    result = filterIfNotSystemUser(
6958                            mActivities.queryIntentForPackage(
6959                                    intent, resolvedType, flags, pkg.activities, userId),
6960                            userId);
6961                }
6962                if (result == null || result.size() == 0) {
6963                    // the caller wants to resolve for a particular package; however, there
6964                    // were no installed results, so, try to find an ephemeral result
6965                    addEphemeral = !ephemeralDisabled
6966                            && isInstantAppAllowed(
6967                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6968                    if (result == null) {
6969                        result = new ArrayList<>();
6970                    }
6971                }
6972            }
6973        }
6974        if (addEphemeral) {
6975            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
6976        }
6977        if (sortResult) {
6978            Collections.sort(result, mResolvePrioritySorter);
6979        }
6980        return applyPostResolutionFilter(result, instantAppPkgName);
6981    }
6982
6983    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6984            String resolvedType, int flags, int userId) {
6985        // first, check to see if we've got an instant app already installed
6986        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6987        ResolveInfo localInstantApp = null;
6988        boolean blockResolution = false;
6989        if (!alreadyResolvedLocally) {
6990            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6991                    flags
6992                        | PackageManager.GET_RESOLVED_FILTER
6993                        | PackageManager.MATCH_INSTANT
6994                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6995                    userId);
6996            for (int i = instantApps.size() - 1; i >= 0; --i) {
6997                final ResolveInfo info = instantApps.get(i);
6998                final String packageName = info.activityInfo.packageName;
6999                final PackageSetting ps = mSettings.mPackages.get(packageName);
7000                if (ps.getInstantApp(userId)) {
7001                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7002                    final int status = (int)(packedStatus >> 32);
7003                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7004                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7005                        // there's a local instant application installed, but, the user has
7006                        // chosen to never use it; skip resolution and don't acknowledge
7007                        // an instant application is even available
7008                        if (DEBUG_EPHEMERAL) {
7009                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7010                        }
7011                        blockResolution = true;
7012                        break;
7013                    } else {
7014                        // we have a locally installed instant application; skip resolution
7015                        // but acknowledge there's an instant application available
7016                        if (DEBUG_EPHEMERAL) {
7017                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7018                        }
7019                        localInstantApp = info;
7020                        break;
7021                    }
7022                }
7023            }
7024        }
7025        // no app installed, let's see if one's available
7026        AuxiliaryResolveInfo auxiliaryResponse = null;
7027        if (!blockResolution) {
7028            if (localInstantApp == null) {
7029                // we don't have an instant app locally, resolve externally
7030                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7031                final InstantAppRequest requestObject = new InstantAppRequest(
7032                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7033                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7034                auxiliaryResponse =
7035                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7036                                mContext, mInstantAppResolverConnection, requestObject);
7037                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7038            } else {
7039                // we have an instant application locally, but, we can't admit that since
7040                // callers shouldn't be able to determine prior browsing. create a dummy
7041                // auxiliary response so the downstream code behaves as if there's an
7042                // instant application available externally. when it comes time to start
7043                // the instant application, we'll do the right thing.
7044                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7045                auxiliaryResponse = new AuxiliaryResolveInfo(
7046                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7047            }
7048        }
7049        if (auxiliaryResponse != null) {
7050            if (DEBUG_EPHEMERAL) {
7051                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7052            }
7053            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7054            final PackageSetting ps =
7055                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7056            if (ps != null) {
7057                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7058                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7059                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7060                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7061                // make sure this resolver is the default
7062                ephemeralInstaller.isDefault = true;
7063                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7064                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7065                // add a non-generic filter
7066                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7067                ephemeralInstaller.filter.addDataPath(
7068                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7069                ephemeralInstaller.isInstantAppAvailable = true;
7070                result.add(ephemeralInstaller);
7071            }
7072        }
7073        return result;
7074    }
7075
7076    private static class CrossProfileDomainInfo {
7077        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7078        ResolveInfo resolveInfo;
7079        /* Best domain verification status of the activities found in the other profile */
7080        int bestDomainVerificationStatus;
7081    }
7082
7083    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7084            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7085        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7086                sourceUserId)) {
7087            return null;
7088        }
7089        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7090                resolvedType, flags, parentUserId);
7091
7092        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7093            return null;
7094        }
7095        CrossProfileDomainInfo result = null;
7096        int size = resultTargetUser.size();
7097        for (int i = 0; i < size; i++) {
7098            ResolveInfo riTargetUser = resultTargetUser.get(i);
7099            // Intent filter verification is only for filters that specify a host. So don't return
7100            // those that handle all web uris.
7101            if (riTargetUser.handleAllWebDataURI) {
7102                continue;
7103            }
7104            String packageName = riTargetUser.activityInfo.packageName;
7105            PackageSetting ps = mSettings.mPackages.get(packageName);
7106            if (ps == null) {
7107                continue;
7108            }
7109            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7110            int status = (int)(verificationState >> 32);
7111            if (result == null) {
7112                result = new CrossProfileDomainInfo();
7113                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7114                        sourceUserId, parentUserId);
7115                result.bestDomainVerificationStatus = status;
7116            } else {
7117                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7118                        result.bestDomainVerificationStatus);
7119            }
7120        }
7121        // Don't consider matches with status NEVER across profiles.
7122        if (result != null && result.bestDomainVerificationStatus
7123                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7124            return null;
7125        }
7126        return result;
7127    }
7128
7129    /**
7130     * Verification statuses are ordered from the worse to the best, except for
7131     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7132     */
7133    private int bestDomainVerificationStatus(int status1, int status2) {
7134        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7135            return status2;
7136        }
7137        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7138            return status1;
7139        }
7140        return (int) MathUtils.max(status1, status2);
7141    }
7142
7143    private boolean isUserEnabled(int userId) {
7144        long callingId = Binder.clearCallingIdentity();
7145        try {
7146            UserInfo userInfo = sUserManager.getUserInfo(userId);
7147            return userInfo != null && userInfo.isEnabled();
7148        } finally {
7149            Binder.restoreCallingIdentity(callingId);
7150        }
7151    }
7152
7153    /**
7154     * Filter out activities with systemUserOnly flag set, when current user is not System.
7155     *
7156     * @return filtered list
7157     */
7158    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7159        if (userId == UserHandle.USER_SYSTEM) {
7160            return resolveInfos;
7161        }
7162        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7163            ResolveInfo info = resolveInfos.get(i);
7164            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7165                resolveInfos.remove(i);
7166            }
7167        }
7168        return resolveInfos;
7169    }
7170
7171    /**
7172     * Filters out ephemeral activities.
7173     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7174     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7175     *
7176     * @param resolveInfos The pre-filtered list of resolved activities
7177     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7178     *          is performed.
7179     * @return A filtered list of resolved activities.
7180     */
7181    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7182            String ephemeralPkgName) {
7183        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7184            final ResolveInfo info = resolveInfos.get(i);
7185            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7186            // TODO: When adding on-demand split support for non-instant apps, remove this check
7187            // and always apply post filtering
7188            // allow activities that are defined in the provided package
7189            if (isEphemeralApp) {
7190                if (info.activityInfo.splitName != null
7191                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7192                                info.activityInfo.splitName)) {
7193                    // requested activity is defined in a split that hasn't been installed yet.
7194                    // add the installer to the resolve list
7195                    if (DEBUG_EPHEMERAL) {
7196                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7197                    }
7198                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7199                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7200                            info.activityInfo.packageName, info.activityInfo.splitName,
7201                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7202                    // make sure this resolver is the default
7203                    installerInfo.isDefault = true;
7204                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7205                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7206                    // add a non-generic filter
7207                    installerInfo.filter = new IntentFilter();
7208                    // load resources from the correct package
7209                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7210                    resolveInfos.set(i, installerInfo);
7211                    continue;
7212                }
7213            }
7214            // caller is a full app, don't need to apply any other filtering
7215            if (ephemeralPkgName == null) {
7216                continue;
7217            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7218                // caller is same app; don't need to apply any other filtering
7219                continue;
7220            }
7221            // allow activities that have been explicitly exposed to ephemeral apps
7222            if (!isEphemeralApp
7223                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7224                continue;
7225            }
7226            resolveInfos.remove(i);
7227        }
7228        return resolveInfos;
7229    }
7230
7231    /**
7232     * @param resolveInfos list of resolve infos in descending priority order
7233     * @return if the list contains a resolve info with non-negative priority
7234     */
7235    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7236        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7237    }
7238
7239    private static boolean hasWebURI(Intent intent) {
7240        if (intent.getData() == null) {
7241            return false;
7242        }
7243        final String scheme = intent.getScheme();
7244        if (TextUtils.isEmpty(scheme)) {
7245            return false;
7246        }
7247        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7248    }
7249
7250    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7251            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7252            int userId) {
7253        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7254
7255        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7256            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7257                    candidates.size());
7258        }
7259
7260        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7261        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7262        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7263        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7264        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7265        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7266
7267        synchronized (mPackages) {
7268            final int count = candidates.size();
7269            // First, try to use linked apps. Partition the candidates into four lists:
7270            // one for the final results, one for the "do not use ever", one for "undefined status"
7271            // and finally one for "browser app type".
7272            for (int n=0; n<count; n++) {
7273                ResolveInfo info = candidates.get(n);
7274                String packageName = info.activityInfo.packageName;
7275                PackageSetting ps = mSettings.mPackages.get(packageName);
7276                if (ps != null) {
7277                    // Add to the special match all list (Browser use case)
7278                    if (info.handleAllWebDataURI) {
7279                        matchAllList.add(info);
7280                        continue;
7281                    }
7282                    // Try to get the status from User settings first
7283                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7284                    int status = (int)(packedStatus >> 32);
7285                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7286                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7287                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7288                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7289                                    + " : linkgen=" + linkGeneration);
7290                        }
7291                        // Use link-enabled generation as preferredOrder, i.e.
7292                        // prefer newly-enabled over earlier-enabled.
7293                        info.preferredOrder = linkGeneration;
7294                        alwaysList.add(info);
7295                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7296                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7297                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7298                        }
7299                        neverList.add(info);
7300                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7301                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7302                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7303                        }
7304                        alwaysAskList.add(info);
7305                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7306                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7307                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7308                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7309                        }
7310                        undefinedList.add(info);
7311                    }
7312                }
7313            }
7314
7315            // We'll want to include browser possibilities in a few cases
7316            boolean includeBrowser = false;
7317
7318            // First try to add the "always" resolution(s) for the current user, if any
7319            if (alwaysList.size() > 0) {
7320                result.addAll(alwaysList);
7321            } else {
7322                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7323                result.addAll(undefinedList);
7324                // Maybe add one for the other profile.
7325                if (xpDomainInfo != null && (
7326                        xpDomainInfo.bestDomainVerificationStatus
7327                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7328                    result.add(xpDomainInfo.resolveInfo);
7329                }
7330                includeBrowser = true;
7331            }
7332
7333            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7334            // If there were 'always' entries their preferred order has been set, so we also
7335            // back that off to make the alternatives equivalent
7336            if (alwaysAskList.size() > 0) {
7337                for (ResolveInfo i : result) {
7338                    i.preferredOrder = 0;
7339                }
7340                result.addAll(alwaysAskList);
7341                includeBrowser = true;
7342            }
7343
7344            if (includeBrowser) {
7345                // Also add browsers (all of them or only the default one)
7346                if (DEBUG_DOMAIN_VERIFICATION) {
7347                    Slog.v(TAG, "   ...including browsers in candidate set");
7348                }
7349                if ((matchFlags & MATCH_ALL) != 0) {
7350                    result.addAll(matchAllList);
7351                } else {
7352                    // Browser/generic handling case.  If there's a default browser, go straight
7353                    // to that (but only if there is no other higher-priority match).
7354                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7355                    int maxMatchPrio = 0;
7356                    ResolveInfo defaultBrowserMatch = null;
7357                    final int numCandidates = matchAllList.size();
7358                    for (int n = 0; n < numCandidates; n++) {
7359                        ResolveInfo info = matchAllList.get(n);
7360                        // track the highest overall match priority...
7361                        if (info.priority > maxMatchPrio) {
7362                            maxMatchPrio = info.priority;
7363                        }
7364                        // ...and the highest-priority default browser match
7365                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7366                            if (defaultBrowserMatch == null
7367                                    || (defaultBrowserMatch.priority < info.priority)) {
7368                                if (debug) {
7369                                    Slog.v(TAG, "Considering default browser match " + info);
7370                                }
7371                                defaultBrowserMatch = info;
7372                            }
7373                        }
7374                    }
7375                    if (defaultBrowserMatch != null
7376                            && defaultBrowserMatch.priority >= maxMatchPrio
7377                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7378                    {
7379                        if (debug) {
7380                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7381                        }
7382                        result.add(defaultBrowserMatch);
7383                    } else {
7384                        result.addAll(matchAllList);
7385                    }
7386                }
7387
7388                // If there is nothing selected, add all candidates and remove the ones that the user
7389                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7390                if (result.size() == 0) {
7391                    result.addAll(candidates);
7392                    result.removeAll(neverList);
7393                }
7394            }
7395        }
7396        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7397            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7398                    result.size());
7399            for (ResolveInfo info : result) {
7400                Slog.v(TAG, "  + " + info.activityInfo);
7401            }
7402        }
7403        return result;
7404    }
7405
7406    // Returns a packed value as a long:
7407    //
7408    // high 'int'-sized word: link status: undefined/ask/never/always.
7409    // low 'int'-sized word: relative priority among 'always' results.
7410    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7411        long result = ps.getDomainVerificationStatusForUser(userId);
7412        // if none available, get the master status
7413        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7414            if (ps.getIntentFilterVerificationInfo() != null) {
7415                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7416            }
7417        }
7418        return result;
7419    }
7420
7421    private ResolveInfo querySkipCurrentProfileIntents(
7422            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7423            int flags, int sourceUserId) {
7424        if (matchingFilters != null) {
7425            int size = matchingFilters.size();
7426            for (int i = 0; i < size; i ++) {
7427                CrossProfileIntentFilter filter = matchingFilters.get(i);
7428                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7429                    // Checking if there are activities in the target user that can handle the
7430                    // intent.
7431                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7432                            resolvedType, flags, sourceUserId);
7433                    if (resolveInfo != null) {
7434                        return resolveInfo;
7435                    }
7436                }
7437            }
7438        }
7439        return null;
7440    }
7441
7442    // Return matching ResolveInfo in target user if any.
7443    private ResolveInfo queryCrossProfileIntents(
7444            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7445            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7446        if (matchingFilters != null) {
7447            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7448            // match the same intent. For performance reasons, it is better not to
7449            // run queryIntent twice for the same userId
7450            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7451            int size = matchingFilters.size();
7452            for (int i = 0; i < size; i++) {
7453                CrossProfileIntentFilter filter = matchingFilters.get(i);
7454                int targetUserId = filter.getTargetUserId();
7455                boolean skipCurrentProfile =
7456                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7457                boolean skipCurrentProfileIfNoMatchFound =
7458                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7459                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7460                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7461                    // Checking if there are activities in the target user that can handle the
7462                    // intent.
7463                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7464                            resolvedType, flags, sourceUserId);
7465                    if (resolveInfo != null) return resolveInfo;
7466                    alreadyTriedUserIds.put(targetUserId, true);
7467                }
7468            }
7469        }
7470        return null;
7471    }
7472
7473    /**
7474     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7475     * will forward the intent to the filter's target user.
7476     * Otherwise, returns null.
7477     */
7478    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7479            String resolvedType, int flags, int sourceUserId) {
7480        int targetUserId = filter.getTargetUserId();
7481        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7482                resolvedType, flags, targetUserId);
7483        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7484            // If all the matches in the target profile are suspended, return null.
7485            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7486                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7487                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7488                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7489                            targetUserId);
7490                }
7491            }
7492        }
7493        return null;
7494    }
7495
7496    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7497            int sourceUserId, int targetUserId) {
7498        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7499        long ident = Binder.clearCallingIdentity();
7500        boolean targetIsProfile;
7501        try {
7502            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7503        } finally {
7504            Binder.restoreCallingIdentity(ident);
7505        }
7506        String className;
7507        if (targetIsProfile) {
7508            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7509        } else {
7510            className = FORWARD_INTENT_TO_PARENT;
7511        }
7512        ComponentName forwardingActivityComponentName = new ComponentName(
7513                mAndroidApplication.packageName, className);
7514        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7515                sourceUserId);
7516        if (!targetIsProfile) {
7517            forwardingActivityInfo.showUserIcon = targetUserId;
7518            forwardingResolveInfo.noResourceId = true;
7519        }
7520        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7521        forwardingResolveInfo.priority = 0;
7522        forwardingResolveInfo.preferredOrder = 0;
7523        forwardingResolveInfo.match = 0;
7524        forwardingResolveInfo.isDefault = true;
7525        forwardingResolveInfo.filter = filter;
7526        forwardingResolveInfo.targetUserId = targetUserId;
7527        return forwardingResolveInfo;
7528    }
7529
7530    @Override
7531    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7532            Intent[] specifics, String[] specificTypes, Intent intent,
7533            String resolvedType, int flags, int userId) {
7534        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7535                specificTypes, intent, resolvedType, flags, userId));
7536    }
7537
7538    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7539            Intent[] specifics, String[] specificTypes, Intent intent,
7540            String resolvedType, int flags, int userId) {
7541        if (!sUserManager.exists(userId)) return Collections.emptyList();
7542        final int callingUid = Binder.getCallingUid();
7543        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7544                false /*includeInstantApps*/);
7545        enforceCrossUserPermission(callingUid, userId,
7546                false /*requireFullPermission*/, false /*checkShell*/,
7547                "query intent activity options");
7548        final String resultsAction = intent.getAction();
7549
7550        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7551                | PackageManager.GET_RESOLVED_FILTER, userId);
7552
7553        if (DEBUG_INTENT_MATCHING) {
7554            Log.v(TAG, "Query " + intent + ": " + results);
7555        }
7556
7557        int specificsPos = 0;
7558        int N;
7559
7560        // todo: note that the algorithm used here is O(N^2).  This
7561        // isn't a problem in our current environment, but if we start running
7562        // into situations where we have more than 5 or 10 matches then this
7563        // should probably be changed to something smarter...
7564
7565        // First we go through and resolve each of the specific items
7566        // that were supplied, taking care of removing any corresponding
7567        // duplicate items in the generic resolve list.
7568        if (specifics != null) {
7569            for (int i=0; i<specifics.length; i++) {
7570                final Intent sintent = specifics[i];
7571                if (sintent == null) {
7572                    continue;
7573                }
7574
7575                if (DEBUG_INTENT_MATCHING) {
7576                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7577                }
7578
7579                String action = sintent.getAction();
7580                if (resultsAction != null && resultsAction.equals(action)) {
7581                    // If this action was explicitly requested, then don't
7582                    // remove things that have it.
7583                    action = null;
7584                }
7585
7586                ResolveInfo ri = null;
7587                ActivityInfo ai = null;
7588
7589                ComponentName comp = sintent.getComponent();
7590                if (comp == null) {
7591                    ri = resolveIntent(
7592                        sintent,
7593                        specificTypes != null ? specificTypes[i] : null,
7594                            flags, userId);
7595                    if (ri == null) {
7596                        continue;
7597                    }
7598                    if (ri == mResolveInfo) {
7599                        // ACK!  Must do something better with this.
7600                    }
7601                    ai = ri.activityInfo;
7602                    comp = new ComponentName(ai.applicationInfo.packageName,
7603                            ai.name);
7604                } else {
7605                    ai = getActivityInfo(comp, flags, userId);
7606                    if (ai == null) {
7607                        continue;
7608                    }
7609                }
7610
7611                // Look for any generic query activities that are duplicates
7612                // of this specific one, and remove them from the results.
7613                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7614                N = results.size();
7615                int j;
7616                for (j=specificsPos; j<N; j++) {
7617                    ResolveInfo sri = results.get(j);
7618                    if ((sri.activityInfo.name.equals(comp.getClassName())
7619                            && sri.activityInfo.applicationInfo.packageName.equals(
7620                                    comp.getPackageName()))
7621                        || (action != null && sri.filter.matchAction(action))) {
7622                        results.remove(j);
7623                        if (DEBUG_INTENT_MATCHING) Log.v(
7624                            TAG, "Removing duplicate item from " + j
7625                            + " due to specific " + specificsPos);
7626                        if (ri == null) {
7627                            ri = sri;
7628                        }
7629                        j--;
7630                        N--;
7631                    }
7632                }
7633
7634                // Add this specific item to its proper place.
7635                if (ri == null) {
7636                    ri = new ResolveInfo();
7637                    ri.activityInfo = ai;
7638                }
7639                results.add(specificsPos, ri);
7640                ri.specificIndex = i;
7641                specificsPos++;
7642            }
7643        }
7644
7645        // Now we go through the remaining generic results and remove any
7646        // duplicate actions that are found here.
7647        N = results.size();
7648        for (int i=specificsPos; i<N-1; i++) {
7649            final ResolveInfo rii = results.get(i);
7650            if (rii.filter == null) {
7651                continue;
7652            }
7653
7654            // Iterate over all of the actions of this result's intent
7655            // filter...  typically this should be just one.
7656            final Iterator<String> it = rii.filter.actionsIterator();
7657            if (it == null) {
7658                continue;
7659            }
7660            while (it.hasNext()) {
7661                final String action = it.next();
7662                if (resultsAction != null && resultsAction.equals(action)) {
7663                    // If this action was explicitly requested, then don't
7664                    // remove things that have it.
7665                    continue;
7666                }
7667                for (int j=i+1; j<N; j++) {
7668                    final ResolveInfo rij = results.get(j);
7669                    if (rij.filter != null && rij.filter.hasAction(action)) {
7670                        results.remove(j);
7671                        if (DEBUG_INTENT_MATCHING) Log.v(
7672                            TAG, "Removing duplicate item from " + j
7673                            + " due to action " + action + " at " + i);
7674                        j--;
7675                        N--;
7676                    }
7677                }
7678            }
7679
7680            // If the caller didn't request filter information, drop it now
7681            // so we don't have to marshall/unmarshall it.
7682            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7683                rii.filter = null;
7684            }
7685        }
7686
7687        // Filter out the caller activity if so requested.
7688        if (caller != null) {
7689            N = results.size();
7690            for (int i=0; i<N; i++) {
7691                ActivityInfo ainfo = results.get(i).activityInfo;
7692                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7693                        && caller.getClassName().equals(ainfo.name)) {
7694                    results.remove(i);
7695                    break;
7696                }
7697            }
7698        }
7699
7700        // If the caller didn't request filter information,
7701        // drop them now so we don't have to
7702        // marshall/unmarshall it.
7703        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7704            N = results.size();
7705            for (int i=0; i<N; i++) {
7706                results.get(i).filter = null;
7707            }
7708        }
7709
7710        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7711        return results;
7712    }
7713
7714    @Override
7715    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7716            String resolvedType, int flags, int userId) {
7717        return new ParceledListSlice<>(
7718                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7719    }
7720
7721    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7722            String resolvedType, int flags, int userId) {
7723        if (!sUserManager.exists(userId)) return Collections.emptyList();
7724        final int callingUid = Binder.getCallingUid();
7725        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7726        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7727                false /*includeInstantApps*/);
7728        ComponentName comp = intent.getComponent();
7729        if (comp == null) {
7730            if (intent.getSelector() != null) {
7731                intent = intent.getSelector();
7732                comp = intent.getComponent();
7733            }
7734        }
7735        if (comp != null) {
7736            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7737            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7738            if (ai != null) {
7739                // When specifying an explicit component, we prevent the activity from being
7740                // used when either 1) the calling package is normal and the activity is within
7741                // an instant application or 2) the calling package is ephemeral and the
7742                // activity is not visible to instant applications.
7743                final boolean matchInstantApp =
7744                        (flags & PackageManager.MATCH_INSTANT) != 0;
7745                final boolean matchVisibleToInstantAppOnly =
7746                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7747                final boolean matchExplicitlyVisibleOnly =
7748                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7749                final boolean isCallerInstantApp =
7750                        instantAppPkgName != null;
7751                final boolean isTargetSameInstantApp =
7752                        comp.getPackageName().equals(instantAppPkgName);
7753                final boolean isTargetInstantApp =
7754                        (ai.applicationInfo.privateFlags
7755                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7756                final boolean isTargetVisibleToInstantApp =
7757                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7758                final boolean isTargetExplicitlyVisibleToInstantApp =
7759                        isTargetVisibleToInstantApp
7760                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7761                final boolean isTargetHiddenFromInstantApp =
7762                        !isTargetVisibleToInstantApp
7763                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7764                final boolean blockResolution =
7765                        !isTargetSameInstantApp
7766                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7767                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7768                                        && isTargetHiddenFromInstantApp));
7769                if (!blockResolution) {
7770                    ResolveInfo ri = new ResolveInfo();
7771                    ri.activityInfo = ai;
7772                    list.add(ri);
7773                }
7774            }
7775            return applyPostResolutionFilter(list, instantAppPkgName);
7776        }
7777
7778        // reader
7779        synchronized (mPackages) {
7780            String pkgName = intent.getPackage();
7781            if (pkgName == null) {
7782                final List<ResolveInfo> result =
7783                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7784                return applyPostResolutionFilter(result, instantAppPkgName);
7785            }
7786            final PackageParser.Package pkg = mPackages.get(pkgName);
7787            if (pkg != null) {
7788                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7789                        intent, resolvedType, flags, pkg.receivers, userId);
7790                return applyPostResolutionFilter(result, instantAppPkgName);
7791            }
7792            return Collections.emptyList();
7793        }
7794    }
7795
7796    @Override
7797    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7798        final int callingUid = Binder.getCallingUid();
7799        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7800    }
7801
7802    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7803            int userId, int callingUid) {
7804        if (!sUserManager.exists(userId)) return null;
7805        flags = updateFlagsForResolve(
7806                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7807        List<ResolveInfo> query = queryIntentServicesInternal(
7808                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7809        if (query != null) {
7810            if (query.size() >= 1) {
7811                // If there is more than one service with the same priority,
7812                // just arbitrarily pick the first one.
7813                return query.get(0);
7814            }
7815        }
7816        return null;
7817    }
7818
7819    @Override
7820    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7821            String resolvedType, int flags, int userId) {
7822        final int callingUid = Binder.getCallingUid();
7823        return new ParceledListSlice<>(queryIntentServicesInternal(
7824                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7825    }
7826
7827    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7828            String resolvedType, int flags, int userId, int callingUid,
7829            boolean includeInstantApps) {
7830        if (!sUserManager.exists(userId)) return Collections.emptyList();
7831        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7832        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7833        ComponentName comp = intent.getComponent();
7834        if (comp == null) {
7835            if (intent.getSelector() != null) {
7836                intent = intent.getSelector();
7837                comp = intent.getComponent();
7838            }
7839        }
7840        if (comp != null) {
7841            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7842            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7843            if (si != null) {
7844                // When specifying an explicit component, we prevent the service from being
7845                // used when either 1) the service is in an instant application and the
7846                // caller is not the same instant application or 2) the calling package is
7847                // ephemeral and the activity is not visible to ephemeral applications.
7848                final boolean matchInstantApp =
7849                        (flags & PackageManager.MATCH_INSTANT) != 0;
7850                final boolean matchVisibleToInstantAppOnly =
7851                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7852                final boolean isCallerInstantApp =
7853                        instantAppPkgName != null;
7854                final boolean isTargetSameInstantApp =
7855                        comp.getPackageName().equals(instantAppPkgName);
7856                final boolean isTargetInstantApp =
7857                        (si.applicationInfo.privateFlags
7858                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7859                final boolean isTargetHiddenFromInstantApp =
7860                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7861                final boolean blockResolution =
7862                        !isTargetSameInstantApp
7863                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7864                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7865                                        && isTargetHiddenFromInstantApp));
7866                if (!blockResolution) {
7867                    final ResolveInfo ri = new ResolveInfo();
7868                    ri.serviceInfo = si;
7869                    list.add(ri);
7870                }
7871            }
7872            return list;
7873        }
7874
7875        // reader
7876        synchronized (mPackages) {
7877            String pkgName = intent.getPackage();
7878            if (pkgName == null) {
7879                return applyPostServiceResolutionFilter(
7880                        mServices.queryIntent(intent, resolvedType, flags, userId),
7881                        instantAppPkgName);
7882            }
7883            final PackageParser.Package pkg = mPackages.get(pkgName);
7884            if (pkg != null) {
7885                return applyPostServiceResolutionFilter(
7886                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7887                                userId),
7888                        instantAppPkgName);
7889            }
7890            return Collections.emptyList();
7891        }
7892    }
7893
7894    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7895            String instantAppPkgName) {
7896        // TODO: When adding on-demand split support for non-instant apps, remove this check
7897        // and always apply post filtering
7898        if (instantAppPkgName == null) {
7899            return resolveInfos;
7900        }
7901        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7902            final ResolveInfo info = resolveInfos.get(i);
7903            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7904            // allow services that are defined in the provided package
7905            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7906                if (info.serviceInfo.splitName != null
7907                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7908                                info.serviceInfo.splitName)) {
7909                    // requested service is defined in a split that hasn't been installed yet.
7910                    // add the installer to the resolve list
7911                    if (DEBUG_EPHEMERAL) {
7912                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7913                    }
7914                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7915                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7916                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7917                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7918                    // make sure this resolver is the default
7919                    installerInfo.isDefault = true;
7920                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7921                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7922                    // add a non-generic filter
7923                    installerInfo.filter = new IntentFilter();
7924                    // load resources from the correct package
7925                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7926                    resolveInfos.set(i, installerInfo);
7927                }
7928                continue;
7929            }
7930            // allow services that have been explicitly exposed to ephemeral apps
7931            if (!isEphemeralApp
7932                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7933                continue;
7934            }
7935            resolveInfos.remove(i);
7936        }
7937        return resolveInfos;
7938    }
7939
7940    @Override
7941    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7942            String resolvedType, int flags, int userId) {
7943        return new ParceledListSlice<>(
7944                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7945    }
7946
7947    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7948            Intent intent, String resolvedType, int flags, int userId) {
7949        if (!sUserManager.exists(userId)) return Collections.emptyList();
7950        final int callingUid = Binder.getCallingUid();
7951        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7952        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7953                false /*includeInstantApps*/);
7954        ComponentName comp = intent.getComponent();
7955        if (comp == null) {
7956            if (intent.getSelector() != null) {
7957                intent = intent.getSelector();
7958                comp = intent.getComponent();
7959            }
7960        }
7961        if (comp != null) {
7962            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7963            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7964            if (pi != null) {
7965                // When specifying an explicit component, we prevent the provider from being
7966                // used when either 1) the provider is in an instant application and the
7967                // caller is not the same instant application or 2) the calling package is an
7968                // instant application and the provider is not visible to instant applications.
7969                final boolean matchInstantApp =
7970                        (flags & PackageManager.MATCH_INSTANT) != 0;
7971                final boolean matchVisibleToInstantAppOnly =
7972                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7973                final boolean isCallerInstantApp =
7974                        instantAppPkgName != null;
7975                final boolean isTargetSameInstantApp =
7976                        comp.getPackageName().equals(instantAppPkgName);
7977                final boolean isTargetInstantApp =
7978                        (pi.applicationInfo.privateFlags
7979                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7980                final boolean isTargetHiddenFromInstantApp =
7981                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7982                final boolean blockResolution =
7983                        !isTargetSameInstantApp
7984                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7985                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7986                                        && isTargetHiddenFromInstantApp));
7987                if (!blockResolution) {
7988                    final ResolveInfo ri = new ResolveInfo();
7989                    ri.providerInfo = pi;
7990                    list.add(ri);
7991                }
7992            }
7993            return list;
7994        }
7995
7996        // reader
7997        synchronized (mPackages) {
7998            String pkgName = intent.getPackage();
7999            if (pkgName == null) {
8000                return applyPostContentProviderResolutionFilter(
8001                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8002                        instantAppPkgName);
8003            }
8004            final PackageParser.Package pkg = mPackages.get(pkgName);
8005            if (pkg != null) {
8006                return applyPostContentProviderResolutionFilter(
8007                        mProviders.queryIntentForPackage(
8008                        intent, resolvedType, flags, pkg.providers, userId),
8009                        instantAppPkgName);
8010            }
8011            return Collections.emptyList();
8012        }
8013    }
8014
8015    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8016            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8017        // TODO: When adding on-demand split support for non-instant applications, remove
8018        // this check and always apply post filtering
8019        if (instantAppPkgName == null) {
8020            return resolveInfos;
8021        }
8022        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8023            final ResolveInfo info = resolveInfos.get(i);
8024            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8025            // allow providers that are defined in the provided package
8026            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8027                if (info.providerInfo.splitName != null
8028                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8029                                info.providerInfo.splitName)) {
8030                    // requested provider is defined in a split that hasn't been installed yet.
8031                    // add the installer to the resolve list
8032                    if (DEBUG_EPHEMERAL) {
8033                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8034                    }
8035                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8036                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8037                            info.providerInfo.packageName, info.providerInfo.splitName,
8038                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8039                    // make sure this resolver is the default
8040                    installerInfo.isDefault = true;
8041                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8042                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8043                    // add a non-generic filter
8044                    installerInfo.filter = new IntentFilter();
8045                    // load resources from the correct package
8046                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8047                    resolveInfos.set(i, installerInfo);
8048                }
8049                continue;
8050            }
8051            // allow providers that have been explicitly exposed to instant applications
8052            if (!isEphemeralApp
8053                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8054                continue;
8055            }
8056            resolveInfos.remove(i);
8057        }
8058        return resolveInfos;
8059    }
8060
8061    @Override
8062    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8063        final int callingUid = Binder.getCallingUid();
8064        if (getInstantAppPackageName(callingUid) != null) {
8065            return ParceledListSlice.emptyList();
8066        }
8067        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8068        flags = updateFlagsForPackage(flags, userId, null);
8069        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8070        enforceCrossUserPermission(callingUid, userId,
8071                true /* requireFullPermission */, false /* checkShell */,
8072                "get installed packages");
8073
8074        // writer
8075        synchronized (mPackages) {
8076            ArrayList<PackageInfo> list;
8077            if (listUninstalled) {
8078                list = new ArrayList<>(mSettings.mPackages.size());
8079                for (PackageSetting ps : mSettings.mPackages.values()) {
8080                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8081                        continue;
8082                    }
8083                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8084                        return null;
8085                    }
8086                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8087                    if (pi != null) {
8088                        list.add(pi);
8089                    }
8090                }
8091            } else {
8092                list = new ArrayList<>(mPackages.size());
8093                for (PackageParser.Package p : mPackages.values()) {
8094                    final PackageSetting ps = (PackageSetting) p.mExtras;
8095                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8096                        continue;
8097                    }
8098                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8099                        return null;
8100                    }
8101                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8102                            p.mExtras, flags, userId);
8103                    if (pi != null) {
8104                        list.add(pi);
8105                    }
8106                }
8107            }
8108
8109            return new ParceledListSlice<>(list);
8110        }
8111    }
8112
8113    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8114            String[] permissions, boolean[] tmp, int flags, int userId) {
8115        int numMatch = 0;
8116        final PermissionsState permissionsState = ps.getPermissionsState();
8117        for (int i=0; i<permissions.length; i++) {
8118            final String permission = permissions[i];
8119            if (permissionsState.hasPermission(permission, userId)) {
8120                tmp[i] = true;
8121                numMatch++;
8122            } else {
8123                tmp[i] = false;
8124            }
8125        }
8126        if (numMatch == 0) {
8127            return;
8128        }
8129        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8130
8131        // The above might return null in cases of uninstalled apps or install-state
8132        // skew across users/profiles.
8133        if (pi != null) {
8134            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8135                if (numMatch == permissions.length) {
8136                    pi.requestedPermissions = permissions;
8137                } else {
8138                    pi.requestedPermissions = new String[numMatch];
8139                    numMatch = 0;
8140                    for (int i=0; i<permissions.length; i++) {
8141                        if (tmp[i]) {
8142                            pi.requestedPermissions[numMatch] = permissions[i];
8143                            numMatch++;
8144                        }
8145                    }
8146                }
8147            }
8148            list.add(pi);
8149        }
8150    }
8151
8152    @Override
8153    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8154            String[] permissions, int flags, int userId) {
8155        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8156        flags = updateFlagsForPackage(flags, userId, permissions);
8157        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8158                true /* requireFullPermission */, false /* checkShell */,
8159                "get packages holding permissions");
8160        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8161
8162        // writer
8163        synchronized (mPackages) {
8164            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8165            boolean[] tmpBools = new boolean[permissions.length];
8166            if (listUninstalled) {
8167                for (PackageSetting ps : mSettings.mPackages.values()) {
8168                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8169                            userId);
8170                }
8171            } else {
8172                for (PackageParser.Package pkg : mPackages.values()) {
8173                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8174                    if (ps != null) {
8175                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8176                                userId);
8177                    }
8178                }
8179            }
8180
8181            return new ParceledListSlice<PackageInfo>(list);
8182        }
8183    }
8184
8185    @Override
8186    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8187        final int callingUid = Binder.getCallingUid();
8188        if (getInstantAppPackageName(callingUid) != null) {
8189            return ParceledListSlice.emptyList();
8190        }
8191        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8192        flags = updateFlagsForApplication(flags, userId, null);
8193        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8194
8195        // writer
8196        synchronized (mPackages) {
8197            ArrayList<ApplicationInfo> list;
8198            if (listUninstalled) {
8199                list = new ArrayList<>(mSettings.mPackages.size());
8200                for (PackageSetting ps : mSettings.mPackages.values()) {
8201                    ApplicationInfo ai;
8202                    int effectiveFlags = flags;
8203                    if (ps.isSystem()) {
8204                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8205                    }
8206                    if (ps.pkg != null) {
8207                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8208                            continue;
8209                        }
8210                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8211                            return null;
8212                        }
8213                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8214                                ps.readUserState(userId), userId);
8215                        if (ai != null) {
8216                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8217                        }
8218                    } else {
8219                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8220                        // and already converts to externally visible package name
8221                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8222                                callingUid, effectiveFlags, userId);
8223                    }
8224                    if (ai != null) {
8225                        list.add(ai);
8226                    }
8227                }
8228            } else {
8229                list = new ArrayList<>(mPackages.size());
8230                for (PackageParser.Package p : mPackages.values()) {
8231                    if (p.mExtras != null) {
8232                        PackageSetting ps = (PackageSetting) p.mExtras;
8233                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8234                            continue;
8235                        }
8236                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8237                            return null;
8238                        }
8239                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8240                                ps.readUserState(userId), userId);
8241                        if (ai != null) {
8242                            ai.packageName = resolveExternalPackageNameLPr(p);
8243                            list.add(ai);
8244                        }
8245                    }
8246                }
8247            }
8248
8249            return new ParceledListSlice<>(list);
8250        }
8251    }
8252
8253    @Override
8254    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8255        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8256            return null;
8257        }
8258        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8259                "getEphemeralApplications");
8260        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8261                true /* requireFullPermission */, false /* checkShell */,
8262                "getEphemeralApplications");
8263        synchronized (mPackages) {
8264            List<InstantAppInfo> instantApps = mInstantAppRegistry
8265                    .getInstantAppsLPr(userId);
8266            if (instantApps != null) {
8267                return new ParceledListSlice<>(instantApps);
8268            }
8269        }
8270        return null;
8271    }
8272
8273    @Override
8274    public boolean isInstantApp(String packageName, int userId) {
8275        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8276                true /* requireFullPermission */, false /* checkShell */,
8277                "isInstantApp");
8278        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8279            return false;
8280        }
8281        int callingUid = Binder.getCallingUid();
8282        if (Process.isIsolated(callingUid)) {
8283            callingUid = mIsolatedOwners.get(callingUid);
8284        }
8285
8286        synchronized (mPackages) {
8287            final PackageSetting ps = mSettings.mPackages.get(packageName);
8288            PackageParser.Package pkg = mPackages.get(packageName);
8289            final boolean returnAllowed =
8290                    ps != null
8291                    && (isCallerSameApp(packageName, callingUid)
8292                            || canViewInstantApps(callingUid, userId)
8293                            || mInstantAppRegistry.isInstantAccessGranted(
8294                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8295            if (returnAllowed) {
8296                return ps.getInstantApp(userId);
8297            }
8298        }
8299        return false;
8300    }
8301
8302    @Override
8303    public byte[] getInstantAppCookie(String packageName, int userId) {
8304        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8305            return null;
8306        }
8307
8308        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8309                true /* requireFullPermission */, false /* checkShell */,
8310                "getInstantAppCookie");
8311        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8312            return null;
8313        }
8314        synchronized (mPackages) {
8315            return mInstantAppRegistry.getInstantAppCookieLPw(
8316                    packageName, userId);
8317        }
8318    }
8319
8320    @Override
8321    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8322        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8323            return true;
8324        }
8325
8326        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8327                true /* requireFullPermission */, true /* checkShell */,
8328                "setInstantAppCookie");
8329        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8330            return false;
8331        }
8332        synchronized (mPackages) {
8333            return mInstantAppRegistry.setInstantAppCookieLPw(
8334                    packageName, cookie, userId);
8335        }
8336    }
8337
8338    @Override
8339    public Bitmap getInstantAppIcon(String packageName, int userId) {
8340        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8341            return null;
8342        }
8343
8344        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8345                "getInstantAppIcon");
8346
8347        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8348                true /* requireFullPermission */, false /* checkShell */,
8349                "getInstantAppIcon");
8350
8351        synchronized (mPackages) {
8352            return mInstantAppRegistry.getInstantAppIconLPw(
8353                    packageName, userId);
8354        }
8355    }
8356
8357    private boolean isCallerSameApp(String packageName, int uid) {
8358        PackageParser.Package pkg = mPackages.get(packageName);
8359        return pkg != null
8360                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8361    }
8362
8363    @Override
8364    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8365        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8366            return ParceledListSlice.emptyList();
8367        }
8368        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8369    }
8370
8371    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8372        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8373
8374        // reader
8375        synchronized (mPackages) {
8376            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8377            final int userId = UserHandle.getCallingUserId();
8378            while (i.hasNext()) {
8379                final PackageParser.Package p = i.next();
8380                if (p.applicationInfo == null) continue;
8381
8382                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8383                        && !p.applicationInfo.isDirectBootAware();
8384                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8385                        && p.applicationInfo.isDirectBootAware();
8386
8387                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8388                        && (!mSafeMode || isSystemApp(p))
8389                        && (matchesUnaware || matchesAware)) {
8390                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8391                    if (ps != null) {
8392                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8393                                ps.readUserState(userId), userId);
8394                        if (ai != null) {
8395                            finalList.add(ai);
8396                        }
8397                    }
8398                }
8399            }
8400        }
8401
8402        return finalList;
8403    }
8404
8405    @Override
8406    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8407        if (!sUserManager.exists(userId)) return null;
8408        flags = updateFlagsForComponent(flags, userId, name);
8409        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8410        // reader
8411        synchronized (mPackages) {
8412            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8413            PackageSetting ps = provider != null
8414                    ? mSettings.mPackages.get(provider.owner.packageName)
8415                    : null;
8416            if (ps != null) {
8417                final boolean isInstantApp = ps.getInstantApp(userId);
8418                // normal application; filter out instant application provider
8419                if (instantAppPkgName == null && isInstantApp) {
8420                    return null;
8421                }
8422                // instant application; filter out other instant applications
8423                if (instantAppPkgName != null
8424                        && isInstantApp
8425                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8426                    return null;
8427                }
8428                // instant application; filter out non-exposed provider
8429                if (instantAppPkgName != null
8430                        && !isInstantApp
8431                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8432                    return null;
8433                }
8434                // provider not enabled
8435                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8436                    return null;
8437                }
8438                return PackageParser.generateProviderInfo(
8439                        provider, flags, ps.readUserState(userId), userId);
8440            }
8441            return null;
8442        }
8443    }
8444
8445    /**
8446     * @deprecated
8447     */
8448    @Deprecated
8449    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8450        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8451            return;
8452        }
8453        // reader
8454        synchronized (mPackages) {
8455            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8456                    .entrySet().iterator();
8457            final int userId = UserHandle.getCallingUserId();
8458            while (i.hasNext()) {
8459                Map.Entry<String, PackageParser.Provider> entry = i.next();
8460                PackageParser.Provider p = entry.getValue();
8461                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8462
8463                if (ps != null && p.syncable
8464                        && (!mSafeMode || (p.info.applicationInfo.flags
8465                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8466                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8467                            ps.readUserState(userId), userId);
8468                    if (info != null) {
8469                        outNames.add(entry.getKey());
8470                        outInfo.add(info);
8471                    }
8472                }
8473            }
8474        }
8475    }
8476
8477    @Override
8478    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8479            int uid, int flags, String metaDataKey) {
8480        final int callingUid = Binder.getCallingUid();
8481        final int userId = processName != null ? UserHandle.getUserId(uid)
8482                : UserHandle.getCallingUserId();
8483        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8484        flags = updateFlagsForComponent(flags, userId, processName);
8485        ArrayList<ProviderInfo> finalList = null;
8486        // reader
8487        synchronized (mPackages) {
8488            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8489            while (i.hasNext()) {
8490                final PackageParser.Provider p = i.next();
8491                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8492                if (ps != null && p.info.authority != null
8493                        && (processName == null
8494                                || (p.info.processName.equals(processName)
8495                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8496                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8497
8498                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8499                    // parameter.
8500                    if (metaDataKey != null
8501                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8502                        continue;
8503                    }
8504                    final ComponentName component =
8505                            new ComponentName(p.info.packageName, p.info.name);
8506                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8507                        continue;
8508                    }
8509                    if (finalList == null) {
8510                        finalList = new ArrayList<ProviderInfo>(3);
8511                    }
8512                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8513                            ps.readUserState(userId), userId);
8514                    if (info != null) {
8515                        finalList.add(info);
8516                    }
8517                }
8518            }
8519        }
8520
8521        if (finalList != null) {
8522            Collections.sort(finalList, mProviderInitOrderSorter);
8523            return new ParceledListSlice<ProviderInfo>(finalList);
8524        }
8525
8526        return ParceledListSlice.emptyList();
8527    }
8528
8529    @Override
8530    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8531        // reader
8532        synchronized (mPackages) {
8533            final int callingUid = Binder.getCallingUid();
8534            final int callingUserId = UserHandle.getUserId(callingUid);
8535            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8536            if (ps == null) return null;
8537            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8538                return null;
8539            }
8540            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8541            return PackageParser.generateInstrumentationInfo(i, flags);
8542        }
8543    }
8544
8545    @Override
8546    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8547            String targetPackage, int flags) {
8548        final int callingUid = Binder.getCallingUid();
8549        final int callingUserId = UserHandle.getUserId(callingUid);
8550        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8551        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8552            return ParceledListSlice.emptyList();
8553        }
8554        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8555    }
8556
8557    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8558            int flags) {
8559        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8560
8561        // reader
8562        synchronized (mPackages) {
8563            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8564            while (i.hasNext()) {
8565                final PackageParser.Instrumentation p = i.next();
8566                if (targetPackage == null
8567                        || targetPackage.equals(p.info.targetPackage)) {
8568                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8569                            flags);
8570                    if (ii != null) {
8571                        finalList.add(ii);
8572                    }
8573                }
8574            }
8575        }
8576
8577        return finalList;
8578    }
8579
8580    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8581        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8582        try {
8583            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8584        } finally {
8585            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8586        }
8587    }
8588
8589    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8590        final File[] files = dir.listFiles();
8591        if (ArrayUtils.isEmpty(files)) {
8592            Log.d(TAG, "No files in app dir " + dir);
8593            return;
8594        }
8595
8596        if (DEBUG_PACKAGE_SCANNING) {
8597            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8598                    + " flags=0x" + Integer.toHexString(parseFlags));
8599        }
8600        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8601                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8602                mParallelPackageParserCallback);
8603
8604        // Submit files for parsing in parallel
8605        int fileCount = 0;
8606        for (File file : files) {
8607            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8608                    && !PackageInstallerService.isStageName(file.getName());
8609            if (!isPackage) {
8610                // Ignore entries which are not packages
8611                continue;
8612            }
8613            parallelPackageParser.submit(file, parseFlags);
8614            fileCount++;
8615        }
8616
8617        // Process results one by one
8618        for (; fileCount > 0; fileCount--) {
8619            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8620            Throwable throwable = parseResult.throwable;
8621            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8622
8623            if (throwable == null) {
8624                // Static shared libraries have synthetic package names
8625                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8626                    renameStaticSharedLibraryPackage(parseResult.pkg);
8627                }
8628                try {
8629                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8630                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8631                                currentTime, null);
8632                    }
8633                } catch (PackageManagerException e) {
8634                    errorCode = e.error;
8635                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8636                }
8637            } else if (throwable instanceof PackageParser.PackageParserException) {
8638                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8639                        throwable;
8640                errorCode = e.error;
8641                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8642            } else {
8643                throw new IllegalStateException("Unexpected exception occurred while parsing "
8644                        + parseResult.scanFile, throwable);
8645            }
8646
8647            // Delete invalid userdata apps
8648            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8649                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8650                logCriticalInfo(Log.WARN,
8651                        "Deleting invalid package at " + parseResult.scanFile);
8652                removeCodePathLI(parseResult.scanFile);
8653            }
8654        }
8655        parallelPackageParser.close();
8656    }
8657
8658    private static File getSettingsProblemFile() {
8659        File dataDir = Environment.getDataDirectory();
8660        File systemDir = new File(dataDir, "system");
8661        File fname = new File(systemDir, "uiderrors.txt");
8662        return fname;
8663    }
8664
8665    static void reportSettingsProblem(int priority, String msg) {
8666        logCriticalInfo(priority, msg);
8667    }
8668
8669    public static void logCriticalInfo(int priority, String msg) {
8670        Slog.println(priority, TAG, msg);
8671        EventLogTags.writePmCriticalInfo(msg);
8672        try {
8673            File fname = getSettingsProblemFile();
8674            FileOutputStream out = new FileOutputStream(fname, true);
8675            PrintWriter pw = new FastPrintWriter(out);
8676            SimpleDateFormat formatter = new SimpleDateFormat();
8677            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8678            pw.println(dateString + ": " + msg);
8679            pw.close();
8680            FileUtils.setPermissions(
8681                    fname.toString(),
8682                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8683                    -1, -1);
8684        } catch (java.io.IOException e) {
8685        }
8686    }
8687
8688    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8689        if (srcFile.isDirectory()) {
8690            final File baseFile = new File(pkg.baseCodePath);
8691            long maxModifiedTime = baseFile.lastModified();
8692            if (pkg.splitCodePaths != null) {
8693                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8694                    final File splitFile = new File(pkg.splitCodePaths[i]);
8695                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8696                }
8697            }
8698            return maxModifiedTime;
8699        }
8700        return srcFile.lastModified();
8701    }
8702
8703    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8704            final int policyFlags) throws PackageManagerException {
8705        // When upgrading from pre-N MR1, verify the package time stamp using the package
8706        // directory and not the APK file.
8707        final long lastModifiedTime = mIsPreNMR1Upgrade
8708                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8709        if (ps != null
8710                && ps.codePath.equals(srcFile)
8711                && ps.timeStamp == lastModifiedTime
8712                && !isCompatSignatureUpdateNeeded(pkg)
8713                && !isRecoverSignatureUpdateNeeded(pkg)) {
8714            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8715            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8716            ArraySet<PublicKey> signingKs;
8717            synchronized (mPackages) {
8718                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8719            }
8720            if (ps.signatures.mSignatures != null
8721                    && ps.signatures.mSignatures.length != 0
8722                    && signingKs != null) {
8723                // Optimization: reuse the existing cached certificates
8724                // if the package appears to be unchanged.
8725                pkg.mSignatures = ps.signatures.mSignatures;
8726                pkg.mSigningKeys = signingKs;
8727                return;
8728            }
8729
8730            Slog.w(TAG, "PackageSetting for " + ps.name
8731                    + " is missing signatures.  Collecting certs again to recover them.");
8732        } else {
8733            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8734        }
8735
8736        try {
8737            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8738            PackageParser.collectCertificates(pkg, policyFlags);
8739        } catch (PackageParserException e) {
8740            throw PackageManagerException.from(e);
8741        } finally {
8742            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8743        }
8744    }
8745
8746    /**
8747     *  Traces a package scan.
8748     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8749     */
8750    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8751            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8752        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8753        try {
8754            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8755        } finally {
8756            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8757        }
8758    }
8759
8760    /**
8761     *  Scans a package and returns the newly parsed package.
8762     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8763     */
8764    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8765            long currentTime, UserHandle user) throws PackageManagerException {
8766        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8767        PackageParser pp = new PackageParser();
8768        pp.setSeparateProcesses(mSeparateProcesses);
8769        pp.setOnlyCoreApps(mOnlyCore);
8770        pp.setDisplayMetrics(mMetrics);
8771        pp.setCallback(mPackageParserCallback);
8772
8773        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8774            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8775        }
8776
8777        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8778        final PackageParser.Package pkg;
8779        try {
8780            pkg = pp.parsePackage(scanFile, parseFlags);
8781        } catch (PackageParserException e) {
8782            throw PackageManagerException.from(e);
8783        } finally {
8784            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8785        }
8786
8787        // Static shared libraries have synthetic package names
8788        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8789            renameStaticSharedLibraryPackage(pkg);
8790        }
8791
8792        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8793    }
8794
8795    /**
8796     *  Scans a package and returns the newly parsed package.
8797     *  @throws PackageManagerException on a parse error.
8798     */
8799    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8800            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8801            throws PackageManagerException {
8802        // If the package has children and this is the first dive in the function
8803        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8804        // packages (parent and children) would be successfully scanned before the
8805        // actual scan since scanning mutates internal state and we want to atomically
8806        // install the package and its children.
8807        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8808            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8809                scanFlags |= SCAN_CHECK_ONLY;
8810            }
8811        } else {
8812            scanFlags &= ~SCAN_CHECK_ONLY;
8813        }
8814
8815        // Scan the parent
8816        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8817                scanFlags, currentTime, user);
8818
8819        // Scan the children
8820        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8821        for (int i = 0; i < childCount; i++) {
8822            PackageParser.Package childPackage = pkg.childPackages.get(i);
8823            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8824                    currentTime, user);
8825        }
8826
8827
8828        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8829            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8830        }
8831
8832        return scannedPkg;
8833    }
8834
8835    /**
8836     *  Scans a package and returns the newly parsed package.
8837     *  @throws PackageManagerException on a parse error.
8838     */
8839    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8840            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8841            throws PackageManagerException {
8842        PackageSetting ps = null;
8843        PackageSetting updatedPkg;
8844        // reader
8845        synchronized (mPackages) {
8846            // Look to see if we already know about this package.
8847            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8848            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8849                // This package has been renamed to its original name.  Let's
8850                // use that.
8851                ps = mSettings.getPackageLPr(oldName);
8852            }
8853            // If there was no original package, see one for the real package name.
8854            if (ps == null) {
8855                ps = mSettings.getPackageLPr(pkg.packageName);
8856            }
8857            // Check to see if this package could be hiding/updating a system
8858            // package.  Must look for it either under the original or real
8859            // package name depending on our state.
8860            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8861            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8862
8863            // If this is a package we don't know about on the system partition, we
8864            // may need to remove disabled child packages on the system partition
8865            // or may need to not add child packages if the parent apk is updated
8866            // on the data partition and no longer defines this child package.
8867            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8868                // If this is a parent package for an updated system app and this system
8869                // app got an OTA update which no longer defines some of the child packages
8870                // we have to prune them from the disabled system packages.
8871                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8872                if (disabledPs != null) {
8873                    final int scannedChildCount = (pkg.childPackages != null)
8874                            ? pkg.childPackages.size() : 0;
8875                    final int disabledChildCount = disabledPs.childPackageNames != null
8876                            ? disabledPs.childPackageNames.size() : 0;
8877                    for (int i = 0; i < disabledChildCount; i++) {
8878                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8879                        boolean disabledPackageAvailable = false;
8880                        for (int j = 0; j < scannedChildCount; j++) {
8881                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8882                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8883                                disabledPackageAvailable = true;
8884                                break;
8885                            }
8886                         }
8887                         if (!disabledPackageAvailable) {
8888                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8889                         }
8890                    }
8891                }
8892            }
8893        }
8894
8895        boolean updatedPkgBetter = false;
8896        // First check if this is a system package that may involve an update
8897        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8898            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8899            // it needs to drop FLAG_PRIVILEGED.
8900            if (locationIsPrivileged(scanFile)) {
8901                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8902            } else {
8903                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8904            }
8905
8906            if (ps != null && !ps.codePath.equals(scanFile)) {
8907                // The path has changed from what was last scanned...  check the
8908                // version of the new path against what we have stored to determine
8909                // what to do.
8910                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8911                if (pkg.mVersionCode <= ps.versionCode) {
8912                    // The system package has been updated and the code path does not match
8913                    // Ignore entry. Skip it.
8914                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8915                            + " ignored: updated version " + ps.versionCode
8916                            + " better than this " + pkg.mVersionCode);
8917                    if (!updatedPkg.codePath.equals(scanFile)) {
8918                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8919                                + ps.name + " changing from " + updatedPkg.codePathString
8920                                + " to " + scanFile);
8921                        updatedPkg.codePath = scanFile;
8922                        updatedPkg.codePathString = scanFile.toString();
8923                        updatedPkg.resourcePath = scanFile;
8924                        updatedPkg.resourcePathString = scanFile.toString();
8925                    }
8926                    updatedPkg.pkg = pkg;
8927                    updatedPkg.versionCode = pkg.mVersionCode;
8928
8929                    // Update the disabled system child packages to point to the package too.
8930                    final int childCount = updatedPkg.childPackageNames != null
8931                            ? updatedPkg.childPackageNames.size() : 0;
8932                    for (int i = 0; i < childCount; i++) {
8933                        String childPackageName = updatedPkg.childPackageNames.get(i);
8934                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8935                                childPackageName);
8936                        if (updatedChildPkg != null) {
8937                            updatedChildPkg.pkg = pkg;
8938                            updatedChildPkg.versionCode = pkg.mVersionCode;
8939                        }
8940                    }
8941
8942                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8943                            + scanFile + " ignored: updated version " + ps.versionCode
8944                            + " better than this " + pkg.mVersionCode);
8945                } else {
8946                    // The current app on the system partition is better than
8947                    // what we have updated to on the data partition; switch
8948                    // back to the system partition version.
8949                    // At this point, its safely assumed that package installation for
8950                    // apps in system partition will go through. If not there won't be a working
8951                    // version of the app
8952                    // writer
8953                    synchronized (mPackages) {
8954                        // Just remove the loaded entries from package lists.
8955                        mPackages.remove(ps.name);
8956                    }
8957
8958                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8959                            + " reverting from " + ps.codePathString
8960                            + ": new version " + pkg.mVersionCode
8961                            + " better than installed " + ps.versionCode);
8962
8963                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8964                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8965                    synchronized (mInstallLock) {
8966                        args.cleanUpResourcesLI();
8967                    }
8968                    synchronized (mPackages) {
8969                        mSettings.enableSystemPackageLPw(ps.name);
8970                    }
8971                    updatedPkgBetter = true;
8972                }
8973            }
8974        }
8975
8976        if (updatedPkg != null) {
8977            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8978            // initially
8979            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8980
8981            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8982            // flag set initially
8983            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8984                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8985            }
8986        }
8987
8988        // Verify certificates against what was last scanned
8989        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8990
8991        /*
8992         * A new system app appeared, but we already had a non-system one of the
8993         * same name installed earlier.
8994         */
8995        boolean shouldHideSystemApp = false;
8996        if (updatedPkg == null && ps != null
8997                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8998            /*
8999             * Check to make sure the signatures match first. If they don't,
9000             * wipe the installed application and its data.
9001             */
9002            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9003                    != PackageManager.SIGNATURE_MATCH) {
9004                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9005                        + " signatures don't match existing userdata copy; removing");
9006                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9007                        "scanPackageInternalLI")) {
9008                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9009                }
9010                ps = null;
9011            } else {
9012                /*
9013                 * If the newly-added system app is an older version than the
9014                 * already installed version, hide it. It will be scanned later
9015                 * and re-added like an update.
9016                 */
9017                if (pkg.mVersionCode <= ps.versionCode) {
9018                    shouldHideSystemApp = true;
9019                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9020                            + " but new version " + pkg.mVersionCode + " better than installed "
9021                            + ps.versionCode + "; hiding system");
9022                } else {
9023                    /*
9024                     * The newly found system app is a newer version that the
9025                     * one previously installed. Simply remove the
9026                     * already-installed application and replace it with our own
9027                     * while keeping the application data.
9028                     */
9029                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9030                            + " reverting from " + ps.codePathString + ": new version "
9031                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9032                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9033                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9034                    synchronized (mInstallLock) {
9035                        args.cleanUpResourcesLI();
9036                    }
9037                }
9038            }
9039        }
9040
9041        // The apk is forward locked (not public) if its code and resources
9042        // are kept in different files. (except for app in either system or
9043        // vendor path).
9044        // TODO grab this value from PackageSettings
9045        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9046            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9047                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9048            }
9049        }
9050
9051        // TODO: extend to support forward-locked splits
9052        String resourcePath = null;
9053        String baseResourcePath = null;
9054        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
9055            if (ps != null && ps.resourcePathString != null) {
9056                resourcePath = ps.resourcePathString;
9057                baseResourcePath = ps.resourcePathString;
9058            } else {
9059                // Should not happen at all. Just log an error.
9060                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9061            }
9062        } else {
9063            resourcePath = pkg.codePath;
9064            baseResourcePath = pkg.baseCodePath;
9065        }
9066
9067        // Set application objects path explicitly.
9068        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9069        pkg.setApplicationInfoCodePath(pkg.codePath);
9070        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9071        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9072        pkg.setApplicationInfoResourcePath(resourcePath);
9073        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9074        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9075
9076        final int userId = ((user == null) ? 0 : user.getIdentifier());
9077        if (ps != null && ps.getInstantApp(userId)) {
9078            scanFlags |= SCAN_AS_INSTANT_APP;
9079        }
9080
9081        // Note that we invoke the following method only if we are about to unpack an application
9082        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9083                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9084
9085        /*
9086         * If the system app should be overridden by a previously installed
9087         * data, hide the system app now and let the /data/app scan pick it up
9088         * again.
9089         */
9090        if (shouldHideSystemApp) {
9091            synchronized (mPackages) {
9092                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9093            }
9094        }
9095
9096        return scannedPkg;
9097    }
9098
9099    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9100        // Derive the new package synthetic package name
9101        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9102                + pkg.staticSharedLibVersion);
9103    }
9104
9105    private static String fixProcessName(String defProcessName,
9106            String processName) {
9107        if (processName == null) {
9108            return defProcessName;
9109        }
9110        return processName;
9111    }
9112
9113    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9114            throws PackageManagerException {
9115        if (pkgSetting.signatures.mSignatures != null) {
9116            // Already existing package. Make sure signatures match
9117            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9118                    == PackageManager.SIGNATURE_MATCH;
9119            if (!match) {
9120                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9121                        == PackageManager.SIGNATURE_MATCH;
9122            }
9123            if (!match) {
9124                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9125                        == PackageManager.SIGNATURE_MATCH;
9126            }
9127            if (!match) {
9128                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9129                        + pkg.packageName + " signatures do not match the "
9130                        + "previously installed version; ignoring!");
9131            }
9132        }
9133
9134        // Check for shared user signatures
9135        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9136            // Already existing package. Make sure signatures match
9137            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9138                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9139            if (!match) {
9140                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9141                        == PackageManager.SIGNATURE_MATCH;
9142            }
9143            if (!match) {
9144                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9145                        == PackageManager.SIGNATURE_MATCH;
9146            }
9147            if (!match) {
9148                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9149                        "Package " + pkg.packageName
9150                        + " has no signatures that match those in shared user "
9151                        + pkgSetting.sharedUser.name + "; ignoring!");
9152            }
9153        }
9154    }
9155
9156    /**
9157     * Enforces that only the system UID or root's UID can call a method exposed
9158     * via Binder.
9159     *
9160     * @param message used as message if SecurityException is thrown
9161     * @throws SecurityException if the caller is not system or root
9162     */
9163    private static final void enforceSystemOrRoot(String message) {
9164        final int uid = Binder.getCallingUid();
9165        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9166            throw new SecurityException(message);
9167        }
9168    }
9169
9170    @Override
9171    public void performFstrimIfNeeded() {
9172        enforceSystemOrRoot("Only the system can request fstrim");
9173
9174        // Before everything else, see whether we need to fstrim.
9175        try {
9176            IStorageManager sm = PackageHelper.getStorageManager();
9177            if (sm != null) {
9178                boolean doTrim = false;
9179                final long interval = android.provider.Settings.Global.getLong(
9180                        mContext.getContentResolver(),
9181                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9182                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9183                if (interval > 0) {
9184                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9185                    if (timeSinceLast > interval) {
9186                        doTrim = true;
9187                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9188                                + "; running immediately");
9189                    }
9190                }
9191                if (doTrim) {
9192                    final boolean dexOptDialogShown;
9193                    synchronized (mPackages) {
9194                        dexOptDialogShown = mDexOptDialogShown;
9195                    }
9196                    if (!isFirstBoot() && dexOptDialogShown) {
9197                        try {
9198                            ActivityManager.getService().showBootMessage(
9199                                    mContext.getResources().getString(
9200                                            R.string.android_upgrading_fstrim), true);
9201                        } catch (RemoteException e) {
9202                        }
9203                    }
9204                    sm.runMaintenance();
9205                }
9206            } else {
9207                Slog.e(TAG, "storageManager service unavailable!");
9208            }
9209        } catch (RemoteException e) {
9210            // Can't happen; StorageManagerService is local
9211        }
9212    }
9213
9214    @Override
9215    public void updatePackagesIfNeeded() {
9216        enforceSystemOrRoot("Only the system can request package update");
9217
9218        // We need to re-extract after an OTA.
9219        boolean causeUpgrade = isUpgrade();
9220
9221        // First boot or factory reset.
9222        // Note: we also handle devices that are upgrading to N right now as if it is their
9223        //       first boot, as they do not have profile data.
9224        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9225
9226        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9227        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9228
9229        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9230            return;
9231        }
9232
9233        List<PackageParser.Package> pkgs;
9234        synchronized (mPackages) {
9235            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9236        }
9237
9238        final long startTime = System.nanoTime();
9239        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9240                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9241                    false /* bootComplete */);
9242
9243        final int elapsedTimeSeconds =
9244                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9245
9246        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9247        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9248        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9249        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9250        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9251    }
9252
9253    /**
9254     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9255     * containing statistics about the invocation. The array consists of three elements,
9256     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9257     * and {@code numberOfPackagesFailed}.
9258     */
9259    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9260            String compilerFilter, boolean bootComplete) {
9261
9262        int numberOfPackagesVisited = 0;
9263        int numberOfPackagesOptimized = 0;
9264        int numberOfPackagesSkipped = 0;
9265        int numberOfPackagesFailed = 0;
9266        final int numberOfPackagesToDexopt = pkgs.size();
9267
9268        for (PackageParser.Package pkg : pkgs) {
9269            numberOfPackagesVisited++;
9270
9271            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9272                if (DEBUG_DEXOPT) {
9273                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9274                }
9275                numberOfPackagesSkipped++;
9276                continue;
9277            }
9278
9279            if (DEBUG_DEXOPT) {
9280                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9281                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9282            }
9283
9284            if (showDialog) {
9285                try {
9286                    ActivityManager.getService().showBootMessage(
9287                            mContext.getResources().getString(R.string.android_upgrading_apk,
9288                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9289                } catch (RemoteException e) {
9290                }
9291                synchronized (mPackages) {
9292                    mDexOptDialogShown = true;
9293                }
9294            }
9295
9296            // If the OTA updates a system app which was previously preopted to a non-preopted state
9297            // the app might end up being verified at runtime. That's because by default the apps
9298            // are verify-profile but for preopted apps there's no profile.
9299            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9300            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9301            // filter (by default 'quicken').
9302            // Note that at this stage unused apps are already filtered.
9303            if (isSystemApp(pkg) &&
9304                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9305                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9306                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9307            }
9308
9309            // checkProfiles is false to avoid merging profiles during boot which
9310            // might interfere with background compilation (b/28612421).
9311            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9312            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9313            // trade-off worth doing to save boot time work.
9314            int dexOptStatus = performDexOptTraced(pkg.packageName,
9315                    false /* checkProfiles */,
9316                    compilerFilter,
9317                    false /* force */,
9318                    bootComplete);
9319            switch (dexOptStatus) {
9320                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9321                    numberOfPackagesOptimized++;
9322                    break;
9323                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9324                    numberOfPackagesSkipped++;
9325                    break;
9326                case PackageDexOptimizer.DEX_OPT_FAILED:
9327                    numberOfPackagesFailed++;
9328                    break;
9329                default:
9330                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
9331                    break;
9332            }
9333        }
9334
9335        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9336                numberOfPackagesFailed };
9337    }
9338
9339    @Override
9340    public void notifyPackageUse(String packageName, int reason) {
9341        synchronized (mPackages) {
9342            final int callingUid = Binder.getCallingUid();
9343            final int callingUserId = UserHandle.getUserId(callingUid);
9344            if (getInstantAppPackageName(callingUid) != null) {
9345                if (!isCallerSameApp(packageName, callingUid)) {
9346                    return;
9347                }
9348            } else {
9349                if (isInstantApp(packageName, callingUserId)) {
9350                    return;
9351                }
9352            }
9353            final PackageParser.Package p = mPackages.get(packageName);
9354            if (p == null) {
9355                return;
9356            }
9357            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9358        }
9359    }
9360
9361    @Override
9362    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9363        int userId = UserHandle.getCallingUserId();
9364        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9365        if (ai == null) {
9366            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9367                + loadingPackageName + ", user=" + userId);
9368            return;
9369        }
9370        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9371    }
9372
9373    @Override
9374    public boolean performDexOpt(String packageName,
9375            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9376        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9377            return false;
9378        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9379            return false;
9380        }
9381        int dexoptStatus = performDexOptWithStatus(
9382              packageName, checkProfiles, compileReason, force, bootComplete);
9383        return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9384    }
9385
9386    /**
9387     * Perform dexopt on the given package and return one of following result:
9388     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9389     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9390     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9391     */
9392    /* package */ int performDexOptWithStatus(String packageName,
9393            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9394        return performDexOptTraced(packageName, checkProfiles,
9395                getCompilerFilterForReason(compileReason), force, bootComplete);
9396    }
9397
9398    @Override
9399    public boolean performDexOptMode(String packageName,
9400            boolean checkProfiles, String targetCompilerFilter, boolean force,
9401            boolean bootComplete) {
9402        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9403            return false;
9404        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9405            return false;
9406        }
9407        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9408                targetCompilerFilter, force, bootComplete);
9409        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9410    }
9411
9412    private int performDexOptTraced(String packageName,
9413                boolean checkProfiles, String targetCompilerFilter, boolean force,
9414                boolean bootComplete) {
9415        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9416        try {
9417            return performDexOptInternal(packageName, checkProfiles,
9418                    targetCompilerFilter, force, bootComplete);
9419        } finally {
9420            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9421        }
9422    }
9423
9424    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9425    // if the package can now be considered up to date for the given filter.
9426    private int performDexOptInternal(String packageName,
9427                boolean checkProfiles, String targetCompilerFilter, boolean force,
9428                boolean bootComplete) {
9429        PackageParser.Package p;
9430        synchronized (mPackages) {
9431            p = mPackages.get(packageName);
9432            if (p == null) {
9433                // Package could not be found. Report failure.
9434                return PackageDexOptimizer.DEX_OPT_FAILED;
9435            }
9436            mPackageUsage.maybeWriteAsync(mPackages);
9437            mCompilerStats.maybeWriteAsync();
9438        }
9439        long callingId = Binder.clearCallingIdentity();
9440        try {
9441            synchronized (mInstallLock) {
9442                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9443                        targetCompilerFilter, force, bootComplete);
9444            }
9445        } finally {
9446            Binder.restoreCallingIdentity(callingId);
9447        }
9448    }
9449
9450    public ArraySet<String> getOptimizablePackages() {
9451        ArraySet<String> pkgs = new ArraySet<String>();
9452        synchronized (mPackages) {
9453            for (PackageParser.Package p : mPackages.values()) {
9454                if (PackageDexOptimizer.canOptimizePackage(p)) {
9455                    pkgs.add(p.packageName);
9456                }
9457            }
9458        }
9459        return pkgs;
9460    }
9461
9462    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9463            boolean checkProfiles, String targetCompilerFilter,
9464            boolean force, boolean bootComplete) {
9465        // Select the dex optimizer based on the force parameter.
9466        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9467        //       allocate an object here.
9468        PackageDexOptimizer pdo = force
9469                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9470                : mPackageDexOptimizer;
9471
9472        // Dexopt all dependencies first. Note: we ignore the return value and march on
9473        // on errors.
9474        // Note that we are going to call performDexOpt on those libraries as many times as
9475        // they are referenced in packages. When we do a batch of performDexOpt (for example
9476        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9477        // and the first package that uses the library will dexopt it. The
9478        // others will see that the compiled code for the library is up to date.
9479        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9480        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9481        if (!deps.isEmpty()) {
9482            for (PackageParser.Package depPackage : deps) {
9483                // TODO: Analyze and investigate if we (should) profile libraries.
9484                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9485                        false /* checkProfiles */,
9486                        targetCompilerFilter,
9487                        getOrCreateCompilerPackageStats(depPackage),
9488                        true /* isUsedByOtherApps */,
9489                        bootComplete);
9490            }
9491        }
9492        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9493                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9494                mDexManager.isUsedByOtherApps(p.packageName), bootComplete);
9495    }
9496
9497    // Performs dexopt on the used secondary dex files belonging to the given package.
9498    // Returns true if all dex files were process successfully (which could mean either dexopt or
9499    // skip). Returns false if any of the files caused errors.
9500    @Override
9501    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9502            boolean force) {
9503        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9504            return false;
9505        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9506            return false;
9507        }
9508        mDexManager.reconcileSecondaryDexFiles(packageName);
9509        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
9510    }
9511
9512    public boolean performDexOptSecondary(String packageName, int compileReason,
9513            boolean force) {
9514        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9515    }
9516
9517    /**
9518     * Reconcile the information we have about the secondary dex files belonging to
9519     * {@code packagName} and the actual dex files. For all dex files that were
9520     * deleted, update the internal records and delete the generated oat files.
9521     */
9522    @Override
9523    public void reconcileSecondaryDexFiles(String packageName) {
9524        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9525            return;
9526        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9527            return;
9528        }
9529        mDexManager.reconcileSecondaryDexFiles(packageName);
9530    }
9531
9532    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9533    // a reference there.
9534    /*package*/ DexManager getDexManager() {
9535        return mDexManager;
9536    }
9537
9538    /**
9539     * Execute the background dexopt job immediately.
9540     */
9541    @Override
9542    public boolean runBackgroundDexoptJob() {
9543        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9544            return false;
9545        }
9546        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9547    }
9548
9549    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9550        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9551                || p.usesStaticLibraries != null) {
9552            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9553            Set<String> collectedNames = new HashSet<>();
9554            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9555
9556            retValue.remove(p);
9557
9558            return retValue;
9559        } else {
9560            return Collections.emptyList();
9561        }
9562    }
9563
9564    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9565            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9566        if (!collectedNames.contains(p.packageName)) {
9567            collectedNames.add(p.packageName);
9568            collected.add(p);
9569
9570            if (p.usesLibraries != null) {
9571                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9572                        null, collected, collectedNames);
9573            }
9574            if (p.usesOptionalLibraries != null) {
9575                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9576                        null, collected, collectedNames);
9577            }
9578            if (p.usesStaticLibraries != null) {
9579                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9580                        p.usesStaticLibrariesVersions, collected, collectedNames);
9581            }
9582        }
9583    }
9584
9585    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9586            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9587        final int libNameCount = libs.size();
9588        for (int i = 0; i < libNameCount; i++) {
9589            String libName = libs.get(i);
9590            int version = (versions != null && versions.length == libNameCount)
9591                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9592            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9593            if (libPkg != null) {
9594                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9595            }
9596        }
9597    }
9598
9599    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9600        synchronized (mPackages) {
9601            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9602            if (libEntry != null) {
9603                return mPackages.get(libEntry.apk);
9604            }
9605            return null;
9606        }
9607    }
9608
9609    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9610        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9611        if (versionedLib == null) {
9612            return null;
9613        }
9614        return versionedLib.get(version);
9615    }
9616
9617    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9618        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9619                pkg.staticSharedLibName);
9620        if (versionedLib == null) {
9621            return null;
9622        }
9623        int previousLibVersion = -1;
9624        final int versionCount = versionedLib.size();
9625        for (int i = 0; i < versionCount; i++) {
9626            final int libVersion = versionedLib.keyAt(i);
9627            if (libVersion < pkg.staticSharedLibVersion) {
9628                previousLibVersion = Math.max(previousLibVersion, libVersion);
9629            }
9630        }
9631        if (previousLibVersion >= 0) {
9632            return versionedLib.get(previousLibVersion);
9633        }
9634        return null;
9635    }
9636
9637    public void shutdown() {
9638        mPackageUsage.writeNow(mPackages);
9639        mCompilerStats.writeNow();
9640    }
9641
9642    @Override
9643    public void dumpProfiles(String packageName) {
9644        PackageParser.Package pkg;
9645        synchronized (mPackages) {
9646            pkg = mPackages.get(packageName);
9647            if (pkg == null) {
9648                throw new IllegalArgumentException("Unknown package: " + packageName);
9649            }
9650        }
9651        /* Only the shell, root, or the app user should be able to dump profiles. */
9652        int callingUid = Binder.getCallingUid();
9653        if (callingUid != Process.SHELL_UID &&
9654            callingUid != Process.ROOT_UID &&
9655            callingUid != pkg.applicationInfo.uid) {
9656            throw new SecurityException("dumpProfiles");
9657        }
9658
9659        synchronized (mInstallLock) {
9660            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9661            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9662            try {
9663                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9664                String codePaths = TextUtils.join(";", allCodePaths);
9665                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9666            } catch (InstallerException e) {
9667                Slog.w(TAG, "Failed to dump profiles", e);
9668            }
9669            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9670        }
9671    }
9672
9673    @Override
9674    public void forceDexOpt(String packageName) {
9675        enforceSystemOrRoot("forceDexOpt");
9676
9677        PackageParser.Package pkg;
9678        synchronized (mPackages) {
9679            pkg = mPackages.get(packageName);
9680            if (pkg == null) {
9681                throw new IllegalArgumentException("Unknown package: " + packageName);
9682            }
9683        }
9684
9685        synchronized (mInstallLock) {
9686            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9687
9688            // Whoever is calling forceDexOpt wants a compiled package.
9689            // Don't use profiles since that may cause compilation to be skipped.
9690            final int res = performDexOptInternalWithDependenciesLI(pkg,
9691                    false /* checkProfiles */, getDefaultCompilerFilter(),
9692                    true /* force */,
9693                    true /* bootComplete */);
9694
9695            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9696            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9697                throw new IllegalStateException("Failed to dexopt: " + res);
9698            }
9699        }
9700    }
9701
9702    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9703        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9704            Slog.w(TAG, "Unable to update from " + oldPkg.name
9705                    + " to " + newPkg.packageName
9706                    + ": old package not in system partition");
9707            return false;
9708        } else if (mPackages.get(oldPkg.name) != null) {
9709            Slog.w(TAG, "Unable to update from " + oldPkg.name
9710                    + " to " + newPkg.packageName
9711                    + ": old package still exists");
9712            return false;
9713        }
9714        return true;
9715    }
9716
9717    void removeCodePathLI(File codePath) {
9718        if (codePath.isDirectory()) {
9719            try {
9720                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9721            } catch (InstallerException e) {
9722                Slog.w(TAG, "Failed to remove code path", e);
9723            }
9724        } else {
9725            codePath.delete();
9726        }
9727    }
9728
9729    private int[] resolveUserIds(int userId) {
9730        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9731    }
9732
9733    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9734        if (pkg == null) {
9735            Slog.wtf(TAG, "Package was null!", new Throwable());
9736            return;
9737        }
9738        clearAppDataLeafLIF(pkg, userId, flags);
9739        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9740        for (int i = 0; i < childCount; i++) {
9741            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9742        }
9743    }
9744
9745    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9746        final PackageSetting ps;
9747        synchronized (mPackages) {
9748            ps = mSettings.mPackages.get(pkg.packageName);
9749        }
9750        for (int realUserId : resolveUserIds(userId)) {
9751            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9752            try {
9753                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9754                        ceDataInode);
9755            } catch (InstallerException e) {
9756                Slog.w(TAG, String.valueOf(e));
9757            }
9758        }
9759    }
9760
9761    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9762        if (pkg == null) {
9763            Slog.wtf(TAG, "Package was null!", new Throwable());
9764            return;
9765        }
9766        destroyAppDataLeafLIF(pkg, userId, flags);
9767        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9768        for (int i = 0; i < childCount; i++) {
9769            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9770        }
9771    }
9772
9773    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9774        final PackageSetting ps;
9775        synchronized (mPackages) {
9776            ps = mSettings.mPackages.get(pkg.packageName);
9777        }
9778        for (int realUserId : resolveUserIds(userId)) {
9779            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9780            try {
9781                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9782                        ceDataInode);
9783            } catch (InstallerException e) {
9784                Slog.w(TAG, String.valueOf(e));
9785            }
9786            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9787        }
9788    }
9789
9790    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9791        if (pkg == null) {
9792            Slog.wtf(TAG, "Package was null!", new Throwable());
9793            return;
9794        }
9795        destroyAppProfilesLeafLIF(pkg);
9796        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9797        for (int i = 0; i < childCount; i++) {
9798            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9799        }
9800    }
9801
9802    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9803        try {
9804            mInstaller.destroyAppProfiles(pkg.packageName);
9805        } catch (InstallerException e) {
9806            Slog.w(TAG, String.valueOf(e));
9807        }
9808    }
9809
9810    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9811        if (pkg == null) {
9812            Slog.wtf(TAG, "Package was null!", new Throwable());
9813            return;
9814        }
9815        clearAppProfilesLeafLIF(pkg);
9816        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9817        for (int i = 0; i < childCount; i++) {
9818            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9819        }
9820    }
9821
9822    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9823        try {
9824            mInstaller.clearAppProfiles(pkg.packageName);
9825        } catch (InstallerException e) {
9826            Slog.w(TAG, String.valueOf(e));
9827        }
9828    }
9829
9830    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9831            long lastUpdateTime) {
9832        // Set parent install/update time
9833        PackageSetting ps = (PackageSetting) pkg.mExtras;
9834        if (ps != null) {
9835            ps.firstInstallTime = firstInstallTime;
9836            ps.lastUpdateTime = lastUpdateTime;
9837        }
9838        // Set children install/update time
9839        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9840        for (int i = 0; i < childCount; i++) {
9841            PackageParser.Package childPkg = pkg.childPackages.get(i);
9842            ps = (PackageSetting) childPkg.mExtras;
9843            if (ps != null) {
9844                ps.firstInstallTime = firstInstallTime;
9845                ps.lastUpdateTime = lastUpdateTime;
9846            }
9847        }
9848    }
9849
9850    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9851            SharedLibraryEntry file,
9852            PackageParser.Package changingLib) {
9853        if (file.path != null) {
9854            usesLibraryFiles.add(file.path);
9855            return;
9856        }
9857        PackageParser.Package p = mPackages.get(file.apk);
9858        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9859            // If we are doing this while in the middle of updating a library apk,
9860            // then we need to make sure to use that new apk for determining the
9861            // dependencies here.  (We haven't yet finished committing the new apk
9862            // to the package manager state.)
9863            if (p == null || p.packageName.equals(changingLib.packageName)) {
9864                p = changingLib;
9865            }
9866        }
9867        if (p != null) {
9868            usesLibraryFiles.addAll(p.getAllCodePaths());
9869            if (p.usesLibraryFiles != null) {
9870                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9871            }
9872        }
9873    }
9874
9875    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9876            PackageParser.Package changingLib) throws PackageManagerException {
9877        if (pkg == null) {
9878            return;
9879        }
9880        // The collection used here must maintain the order of addition (so
9881        // that libraries are searched in the correct order) and must have no
9882        // duplicates.
9883        Set<String> usesLibraryFiles = null;
9884        if (pkg.usesLibraries != null) {
9885            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9886                    null, null, pkg.packageName, changingLib, true, null);
9887        }
9888        if (pkg.usesStaticLibraries != null) {
9889            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9890                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9891                    pkg.packageName, changingLib, true, usesLibraryFiles);
9892        }
9893        if (pkg.usesOptionalLibraries != null) {
9894            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9895                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9896        }
9897        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9898            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9899        } else {
9900            pkg.usesLibraryFiles = null;
9901        }
9902    }
9903
9904    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9905            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9906            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9907            boolean required, @Nullable Set<String> outUsedLibraries)
9908            throws PackageManagerException {
9909        final int libCount = requestedLibraries.size();
9910        for (int i = 0; i < libCount; i++) {
9911            final String libName = requestedLibraries.get(i);
9912            final int libVersion = requiredVersions != null ? requiredVersions[i]
9913                    : SharedLibraryInfo.VERSION_UNDEFINED;
9914            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9915            if (libEntry == null) {
9916                if (required) {
9917                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9918                            "Package " + packageName + " requires unavailable shared library "
9919                                    + libName + "; failing!");
9920                } else if (DEBUG_SHARED_LIBRARIES) {
9921                    Slog.i(TAG, "Package " + packageName
9922                            + " desires unavailable shared library "
9923                            + libName + "; ignoring!");
9924                }
9925            } else {
9926                if (requiredVersions != null && requiredCertDigests != null) {
9927                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9928                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9929                            "Package " + packageName + " requires unavailable static shared"
9930                                    + " library " + libName + " version "
9931                                    + libEntry.info.getVersion() + "; failing!");
9932                    }
9933
9934                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9935                    if (libPkg == null) {
9936                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9937                                "Package " + packageName + " requires unavailable static shared"
9938                                        + " library; failing!");
9939                    }
9940
9941                    String expectedCertDigest = requiredCertDigests[i];
9942                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9943                                libPkg.mSignatures[0]);
9944                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9945                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9946                                "Package " + packageName + " requires differently signed" +
9947                                        " static shared library; failing!");
9948                    }
9949                }
9950
9951                if (outUsedLibraries == null) {
9952                    // Use LinkedHashSet to preserve the order of files added to
9953                    // usesLibraryFiles while eliminating duplicates.
9954                    outUsedLibraries = new LinkedHashSet<>();
9955                }
9956                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9957            }
9958        }
9959        return outUsedLibraries;
9960    }
9961
9962    private static boolean hasString(List<String> list, List<String> which) {
9963        if (list == null) {
9964            return false;
9965        }
9966        for (int i=list.size()-1; i>=0; i--) {
9967            for (int j=which.size()-1; j>=0; j--) {
9968                if (which.get(j).equals(list.get(i))) {
9969                    return true;
9970                }
9971            }
9972        }
9973        return false;
9974    }
9975
9976    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9977            PackageParser.Package changingPkg) {
9978        ArrayList<PackageParser.Package> res = null;
9979        for (PackageParser.Package pkg : mPackages.values()) {
9980            if (changingPkg != null
9981                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9982                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9983                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9984                            changingPkg.staticSharedLibName)) {
9985                return null;
9986            }
9987            if (res == null) {
9988                res = new ArrayList<>();
9989            }
9990            res.add(pkg);
9991            try {
9992                updateSharedLibrariesLPr(pkg, changingPkg);
9993            } catch (PackageManagerException e) {
9994                // If a system app update or an app and a required lib missing we
9995                // delete the package and for updated system apps keep the data as
9996                // it is better for the user to reinstall than to be in an limbo
9997                // state. Also libs disappearing under an app should never happen
9998                // - just in case.
9999                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10000                    final int flags = pkg.isUpdatedSystemApp()
10001                            ? PackageManager.DELETE_KEEP_DATA : 0;
10002                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10003                            flags , null, true, null);
10004                }
10005                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10006            }
10007        }
10008        return res;
10009    }
10010
10011    /**
10012     * Derive the value of the {@code cpuAbiOverride} based on the provided
10013     * value and an optional stored value from the package settings.
10014     */
10015    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10016        String cpuAbiOverride = null;
10017
10018        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10019            cpuAbiOverride = null;
10020        } else if (abiOverride != null) {
10021            cpuAbiOverride = abiOverride;
10022        } else if (settings != null) {
10023            cpuAbiOverride = settings.cpuAbiOverrideString;
10024        }
10025
10026        return cpuAbiOverride;
10027    }
10028
10029    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10030            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10031                    throws PackageManagerException {
10032        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10033        // If the package has children and this is the first dive in the function
10034        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10035        // whether all packages (parent and children) would be successfully scanned
10036        // before the actual scan since scanning mutates internal state and we want
10037        // to atomically install the package and its children.
10038        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10039            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10040                scanFlags |= SCAN_CHECK_ONLY;
10041            }
10042        } else {
10043            scanFlags &= ~SCAN_CHECK_ONLY;
10044        }
10045
10046        final PackageParser.Package scannedPkg;
10047        try {
10048            // Scan the parent
10049            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10050            // Scan the children
10051            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10052            for (int i = 0; i < childCount; i++) {
10053                PackageParser.Package childPkg = pkg.childPackages.get(i);
10054                scanPackageLI(childPkg, policyFlags,
10055                        scanFlags, currentTime, user);
10056            }
10057        } finally {
10058            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10059        }
10060
10061        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10062            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10063        }
10064
10065        return scannedPkg;
10066    }
10067
10068    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10069            int scanFlags, long currentTime, @Nullable UserHandle user)
10070                    throws PackageManagerException {
10071        boolean success = false;
10072        try {
10073            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10074                    currentTime, user);
10075            success = true;
10076            return res;
10077        } finally {
10078            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10079                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10080                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10081                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10082                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10083            }
10084        }
10085    }
10086
10087    /**
10088     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10089     */
10090    private static boolean apkHasCode(String fileName) {
10091        StrictJarFile jarFile = null;
10092        try {
10093            jarFile = new StrictJarFile(fileName,
10094                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10095            return jarFile.findEntry("classes.dex") != null;
10096        } catch (IOException ignore) {
10097        } finally {
10098            try {
10099                if (jarFile != null) {
10100                    jarFile.close();
10101                }
10102            } catch (IOException ignore) {}
10103        }
10104        return false;
10105    }
10106
10107    /**
10108     * Enforces code policy for the package. This ensures that if an APK has
10109     * declared hasCode="true" in its manifest that the APK actually contains
10110     * code.
10111     *
10112     * @throws PackageManagerException If bytecode could not be found when it should exist
10113     */
10114    private static void assertCodePolicy(PackageParser.Package pkg)
10115            throws PackageManagerException {
10116        final boolean shouldHaveCode =
10117                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10118        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10119            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10120                    "Package " + pkg.baseCodePath + " code is missing");
10121        }
10122
10123        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10124            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10125                final boolean splitShouldHaveCode =
10126                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10127                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10128                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10129                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10130                }
10131            }
10132        }
10133    }
10134
10135    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10136            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10137                    throws PackageManagerException {
10138        if (DEBUG_PACKAGE_SCANNING) {
10139            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10140                Log.d(TAG, "Scanning package " + pkg.packageName);
10141        }
10142
10143        applyPolicy(pkg, policyFlags);
10144
10145        assertPackageIsValid(pkg, policyFlags, scanFlags);
10146
10147        if (Build.IS_DEBUGGABLE &&
10148                pkg.isPrivilegedApp() &&
10149                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10150            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10151        }
10152
10153        // Initialize package source and resource directories
10154        final File scanFile = new File(pkg.codePath);
10155        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10156        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10157
10158        SharedUserSetting suid = null;
10159        PackageSetting pkgSetting = null;
10160
10161        // Getting the package setting may have a side-effect, so if we
10162        // are only checking if scan would succeed, stash a copy of the
10163        // old setting to restore at the end.
10164        PackageSetting nonMutatedPs = null;
10165
10166        // We keep references to the derived CPU Abis from settings in oder to reuse
10167        // them in the case where we're not upgrading or booting for the first time.
10168        String primaryCpuAbiFromSettings = null;
10169        String secondaryCpuAbiFromSettings = null;
10170
10171        // writer
10172        synchronized (mPackages) {
10173            if (pkg.mSharedUserId != null) {
10174                // SIDE EFFECTS; may potentially allocate a new shared user
10175                suid = mSettings.getSharedUserLPw(
10176                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10177                if (DEBUG_PACKAGE_SCANNING) {
10178                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10179                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10180                                + "): packages=" + suid.packages);
10181                }
10182            }
10183
10184            // Check if we are renaming from an original package name.
10185            PackageSetting origPackage = null;
10186            String realName = null;
10187            if (pkg.mOriginalPackages != null) {
10188                // This package may need to be renamed to a previously
10189                // installed name.  Let's check on that...
10190                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10191                if (pkg.mOriginalPackages.contains(renamed)) {
10192                    // This package had originally been installed as the
10193                    // original name, and we have already taken care of
10194                    // transitioning to the new one.  Just update the new
10195                    // one to continue using the old name.
10196                    realName = pkg.mRealPackage;
10197                    if (!pkg.packageName.equals(renamed)) {
10198                        // Callers into this function may have already taken
10199                        // care of renaming the package; only do it here if
10200                        // it is not already done.
10201                        pkg.setPackageName(renamed);
10202                    }
10203                } else {
10204                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10205                        if ((origPackage = mSettings.getPackageLPr(
10206                                pkg.mOriginalPackages.get(i))) != null) {
10207                            // We do have the package already installed under its
10208                            // original name...  should we use it?
10209                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10210                                // New package is not compatible with original.
10211                                origPackage = null;
10212                                continue;
10213                            } else if (origPackage.sharedUser != null) {
10214                                // Make sure uid is compatible between packages.
10215                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10216                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10217                                            + " to " + pkg.packageName + ": old uid "
10218                                            + origPackage.sharedUser.name
10219                                            + " differs from " + pkg.mSharedUserId);
10220                                    origPackage = null;
10221                                    continue;
10222                                }
10223                                // TODO: Add case when shared user id is added [b/28144775]
10224                            } else {
10225                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10226                                        + pkg.packageName + " to old name " + origPackage.name);
10227                            }
10228                            break;
10229                        }
10230                    }
10231                }
10232            }
10233
10234            if (mTransferedPackages.contains(pkg.packageName)) {
10235                Slog.w(TAG, "Package " + pkg.packageName
10236                        + " was transferred to another, but its .apk remains");
10237            }
10238
10239            // See comments in nonMutatedPs declaration
10240            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10241                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10242                if (foundPs != null) {
10243                    nonMutatedPs = new PackageSetting(foundPs);
10244                }
10245            }
10246
10247            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10248                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10249                if (foundPs != null) {
10250                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10251                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10252                }
10253            }
10254
10255            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10256            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10257                PackageManagerService.reportSettingsProblem(Log.WARN,
10258                        "Package " + pkg.packageName + " shared user changed from "
10259                                + (pkgSetting.sharedUser != null
10260                                        ? pkgSetting.sharedUser.name : "<nothing>")
10261                                + " to "
10262                                + (suid != null ? suid.name : "<nothing>")
10263                                + "; replacing with new");
10264                pkgSetting = null;
10265            }
10266            final PackageSetting oldPkgSetting =
10267                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10268            final PackageSetting disabledPkgSetting =
10269                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10270
10271            String[] usesStaticLibraries = null;
10272            if (pkg.usesStaticLibraries != null) {
10273                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10274                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10275            }
10276
10277            if (pkgSetting == null) {
10278                final String parentPackageName = (pkg.parentPackage != null)
10279                        ? pkg.parentPackage.packageName : null;
10280                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10281                // REMOVE SharedUserSetting from method; update in a separate call
10282                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10283                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10284                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10285                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10286                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10287                        true /*allowInstall*/, instantApp, parentPackageName,
10288                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10289                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10290                // SIDE EFFECTS; updates system state; move elsewhere
10291                if (origPackage != null) {
10292                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10293                }
10294                mSettings.addUserToSettingLPw(pkgSetting);
10295            } else {
10296                // REMOVE SharedUserSetting from method; update in a separate call.
10297                //
10298                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10299                // secondaryCpuAbi are not known at this point so we always update them
10300                // to null here, only to reset them at a later point.
10301                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10302                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10303                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10304                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10305                        UserManagerService.getInstance(), usesStaticLibraries,
10306                        pkg.usesStaticLibrariesVersions);
10307            }
10308            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10309            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10310
10311            // SIDE EFFECTS; modifies system state; move elsewhere
10312            if (pkgSetting.origPackage != null) {
10313                // If we are first transitioning from an original package,
10314                // fix up the new package's name now.  We need to do this after
10315                // looking up the package under its new name, so getPackageLP
10316                // can take care of fiddling things correctly.
10317                pkg.setPackageName(origPackage.name);
10318
10319                // File a report about this.
10320                String msg = "New package " + pkgSetting.realName
10321                        + " renamed to replace old package " + pkgSetting.name;
10322                reportSettingsProblem(Log.WARN, msg);
10323
10324                // Make a note of it.
10325                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10326                    mTransferedPackages.add(origPackage.name);
10327                }
10328
10329                // No longer need to retain this.
10330                pkgSetting.origPackage = null;
10331            }
10332
10333            // SIDE EFFECTS; modifies system state; move elsewhere
10334            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10335                // Make a note of it.
10336                mTransferedPackages.add(pkg.packageName);
10337            }
10338
10339            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10340                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10341            }
10342
10343            if ((scanFlags & SCAN_BOOTING) == 0
10344                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10345                // Check all shared libraries and map to their actual file path.
10346                // We only do this here for apps not on a system dir, because those
10347                // are the only ones that can fail an install due to this.  We
10348                // will take care of the system apps by updating all of their
10349                // library paths after the scan is done. Also during the initial
10350                // scan don't update any libs as we do this wholesale after all
10351                // apps are scanned to avoid dependency based scanning.
10352                updateSharedLibrariesLPr(pkg, null);
10353            }
10354
10355            if (mFoundPolicyFile) {
10356                SELinuxMMAC.assignSeInfoValue(pkg);
10357            }
10358            pkg.applicationInfo.uid = pkgSetting.appId;
10359            pkg.mExtras = pkgSetting;
10360
10361
10362            // Static shared libs have same package with different versions where
10363            // we internally use a synthetic package name to allow multiple versions
10364            // of the same package, therefore we need to compare signatures against
10365            // the package setting for the latest library version.
10366            PackageSetting signatureCheckPs = pkgSetting;
10367            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10368                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10369                if (libraryEntry != null) {
10370                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10371                }
10372            }
10373
10374            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10375                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10376                    // We just determined the app is signed correctly, so bring
10377                    // over the latest parsed certs.
10378                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10379                } else {
10380                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10381                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10382                                "Package " + pkg.packageName + " upgrade keys do not match the "
10383                                + "previously installed version");
10384                    } else {
10385                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10386                        String msg = "System package " + pkg.packageName
10387                                + " signature changed; retaining data.";
10388                        reportSettingsProblem(Log.WARN, msg);
10389                    }
10390                }
10391            } else {
10392                try {
10393                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10394                    verifySignaturesLP(signatureCheckPs, pkg);
10395                    // We just determined the app is signed correctly, so bring
10396                    // over the latest parsed certs.
10397                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10398                } catch (PackageManagerException e) {
10399                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10400                        throw e;
10401                    }
10402                    // The signature has changed, but this package is in the system
10403                    // image...  let's recover!
10404                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10405                    // However...  if this package is part of a shared user, but it
10406                    // doesn't match the signature of the shared user, let's fail.
10407                    // What this means is that you can't change the signatures
10408                    // associated with an overall shared user, which doesn't seem all
10409                    // that unreasonable.
10410                    if (signatureCheckPs.sharedUser != null) {
10411                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10412                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10413                            throw new PackageManagerException(
10414                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10415                                    "Signature mismatch for shared user: "
10416                                            + pkgSetting.sharedUser);
10417                        }
10418                    }
10419                    // File a report about this.
10420                    String msg = "System package " + pkg.packageName
10421                            + " signature changed; retaining data.";
10422                    reportSettingsProblem(Log.WARN, msg);
10423                }
10424            }
10425
10426            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10427                // This package wants to adopt ownership of permissions from
10428                // another package.
10429                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10430                    final String origName = pkg.mAdoptPermissions.get(i);
10431                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10432                    if (orig != null) {
10433                        if (verifyPackageUpdateLPr(orig, pkg)) {
10434                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10435                                    + pkg.packageName);
10436                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10437                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10438                        }
10439                    }
10440                }
10441            }
10442        }
10443
10444        pkg.applicationInfo.processName = fixProcessName(
10445                pkg.applicationInfo.packageName,
10446                pkg.applicationInfo.processName);
10447
10448        if (pkg != mPlatformPackage) {
10449            // Get all of our default paths setup
10450            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10451        }
10452
10453        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10454
10455        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10456            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10457                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10458                final boolean extractNativeLibs = !pkg.isLibrary();
10459                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10460                        mAppLib32InstallDir);
10461                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10462
10463                // Some system apps still use directory structure for native libraries
10464                // in which case we might end up not detecting abi solely based on apk
10465                // structure. Try to detect abi based on directory structure.
10466                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10467                        pkg.applicationInfo.primaryCpuAbi == null) {
10468                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10469                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10470                }
10471            } else {
10472                // This is not a first boot or an upgrade, don't bother deriving the
10473                // ABI during the scan. Instead, trust the value that was stored in the
10474                // package setting.
10475                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10476                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10477
10478                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10479
10480                if (DEBUG_ABI_SELECTION) {
10481                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10482                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10483                        pkg.applicationInfo.secondaryCpuAbi);
10484                }
10485            }
10486        } else {
10487            if ((scanFlags & SCAN_MOVE) != 0) {
10488                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10489                // but we already have this packages package info in the PackageSetting. We just
10490                // use that and derive the native library path based on the new codepath.
10491                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10492                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10493            }
10494
10495            // Set native library paths again. For moves, the path will be updated based on the
10496            // ABIs we've determined above. For non-moves, the path will be updated based on the
10497            // ABIs we determined during compilation, but the path will depend on the final
10498            // package path (after the rename away from the stage path).
10499            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10500        }
10501
10502        // This is a special case for the "system" package, where the ABI is
10503        // dictated by the zygote configuration (and init.rc). We should keep track
10504        // of this ABI so that we can deal with "normal" applications that run under
10505        // the same UID correctly.
10506        if (mPlatformPackage == pkg) {
10507            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10508                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10509        }
10510
10511        // If there's a mismatch between the abi-override in the package setting
10512        // and the abiOverride specified for the install. Warn about this because we
10513        // would've already compiled the app without taking the package setting into
10514        // account.
10515        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10516            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10517                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10518                        " for package " + pkg.packageName);
10519            }
10520        }
10521
10522        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10523        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10524        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10525
10526        // Copy the derived override back to the parsed package, so that we can
10527        // update the package settings accordingly.
10528        pkg.cpuAbiOverride = cpuAbiOverride;
10529
10530        if (DEBUG_ABI_SELECTION) {
10531            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10532                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10533                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10534        }
10535
10536        // Push the derived path down into PackageSettings so we know what to
10537        // clean up at uninstall time.
10538        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10539
10540        if (DEBUG_ABI_SELECTION) {
10541            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10542                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10543                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10544        }
10545
10546        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10547        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10548            // We don't do this here during boot because we can do it all
10549            // at once after scanning all existing packages.
10550            //
10551            // We also do this *before* we perform dexopt on this package, so that
10552            // we can avoid redundant dexopts, and also to make sure we've got the
10553            // code and package path correct.
10554            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10555        }
10556
10557        if (mFactoryTest && pkg.requestedPermissions.contains(
10558                android.Manifest.permission.FACTORY_TEST)) {
10559            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10560        }
10561
10562        if (isSystemApp(pkg)) {
10563            pkgSetting.isOrphaned = true;
10564        }
10565
10566        // Take care of first install / last update times.
10567        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10568        if (currentTime != 0) {
10569            if (pkgSetting.firstInstallTime == 0) {
10570                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10571            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10572                pkgSetting.lastUpdateTime = currentTime;
10573            }
10574        } else if (pkgSetting.firstInstallTime == 0) {
10575            // We need *something*.  Take time time stamp of the file.
10576            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10577        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10578            if (scanFileTime != pkgSetting.timeStamp) {
10579                // A package on the system image has changed; consider this
10580                // to be an update.
10581                pkgSetting.lastUpdateTime = scanFileTime;
10582            }
10583        }
10584        pkgSetting.setTimeStamp(scanFileTime);
10585
10586        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10587            if (nonMutatedPs != null) {
10588                synchronized (mPackages) {
10589                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10590                }
10591            }
10592        } else {
10593            final int userId = user == null ? 0 : user.getIdentifier();
10594            // Modify state for the given package setting
10595            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10596                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10597            if (pkgSetting.getInstantApp(userId)) {
10598                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10599            }
10600        }
10601        return pkg;
10602    }
10603
10604    /**
10605     * Applies policy to the parsed package based upon the given policy flags.
10606     * Ensures the package is in a good state.
10607     * <p>
10608     * Implementation detail: This method must NOT have any side effect. It would
10609     * ideally be static, but, it requires locks to read system state.
10610     */
10611    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10612        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10613            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10614            if (pkg.applicationInfo.isDirectBootAware()) {
10615                // we're direct boot aware; set for all components
10616                for (PackageParser.Service s : pkg.services) {
10617                    s.info.encryptionAware = s.info.directBootAware = true;
10618                }
10619                for (PackageParser.Provider p : pkg.providers) {
10620                    p.info.encryptionAware = p.info.directBootAware = true;
10621                }
10622                for (PackageParser.Activity a : pkg.activities) {
10623                    a.info.encryptionAware = a.info.directBootAware = true;
10624                }
10625                for (PackageParser.Activity r : pkg.receivers) {
10626                    r.info.encryptionAware = r.info.directBootAware = true;
10627                }
10628            }
10629        } else {
10630            // Only allow system apps to be flagged as core apps.
10631            pkg.coreApp = false;
10632            // clear flags not applicable to regular apps
10633            pkg.applicationInfo.privateFlags &=
10634                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10635            pkg.applicationInfo.privateFlags &=
10636                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10637        }
10638        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10639
10640        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10641            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10642        }
10643
10644        if (!isSystemApp(pkg)) {
10645            // Only system apps can use these features.
10646            pkg.mOriginalPackages = null;
10647            pkg.mRealPackage = null;
10648            pkg.mAdoptPermissions = null;
10649        }
10650    }
10651
10652    /**
10653     * Asserts the parsed package is valid according to the given policy. If the
10654     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10655     * <p>
10656     * Implementation detail: This method must NOT have any side effects. It would
10657     * ideally be static, but, it requires locks to read system state.
10658     *
10659     * @throws PackageManagerException If the package fails any of the validation checks
10660     */
10661    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10662            throws PackageManagerException {
10663        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10664            assertCodePolicy(pkg);
10665        }
10666
10667        if (pkg.applicationInfo.getCodePath() == null ||
10668                pkg.applicationInfo.getResourcePath() == null) {
10669            // Bail out. The resource and code paths haven't been set.
10670            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10671                    "Code and resource paths haven't been set correctly");
10672        }
10673
10674        // Make sure we're not adding any bogus keyset info
10675        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10676        ksms.assertScannedPackageValid(pkg);
10677
10678        synchronized (mPackages) {
10679            // The special "android" package can only be defined once
10680            if (pkg.packageName.equals("android")) {
10681                if (mAndroidApplication != null) {
10682                    Slog.w(TAG, "*************************************************");
10683                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10684                    Slog.w(TAG, " codePath=" + pkg.codePath);
10685                    Slog.w(TAG, "*************************************************");
10686                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10687                            "Core android package being redefined.  Skipping.");
10688                }
10689            }
10690
10691            // A package name must be unique; don't allow duplicates
10692            if (mPackages.containsKey(pkg.packageName)) {
10693                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10694                        "Application package " + pkg.packageName
10695                        + " already installed.  Skipping duplicate.");
10696            }
10697
10698            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10699                // Static libs have a synthetic package name containing the version
10700                // but we still want the base name to be unique.
10701                if (mPackages.containsKey(pkg.manifestPackageName)) {
10702                    throw new PackageManagerException(
10703                            "Duplicate static shared lib provider package");
10704                }
10705
10706                // Static shared libraries should have at least O target SDK
10707                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10708                    throw new PackageManagerException(
10709                            "Packages declaring static-shared libs must target O SDK or higher");
10710                }
10711
10712                // Package declaring static a shared lib cannot be instant apps
10713                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10714                    throw new PackageManagerException(
10715                            "Packages declaring static-shared libs cannot be instant apps");
10716                }
10717
10718                // Package declaring static a shared lib cannot be renamed since the package
10719                // name is synthetic and apps can't code around package manager internals.
10720                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10721                    throw new PackageManagerException(
10722                            "Packages declaring static-shared libs cannot be renamed");
10723                }
10724
10725                // Package declaring static a shared lib cannot declare child packages
10726                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10727                    throw new PackageManagerException(
10728                            "Packages declaring static-shared libs cannot have child packages");
10729                }
10730
10731                // Package declaring static a shared lib cannot declare dynamic libs
10732                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10733                    throw new PackageManagerException(
10734                            "Packages declaring static-shared libs cannot declare dynamic libs");
10735                }
10736
10737                // Package declaring static a shared lib cannot declare shared users
10738                if (pkg.mSharedUserId != null) {
10739                    throw new PackageManagerException(
10740                            "Packages declaring static-shared libs cannot declare shared users");
10741                }
10742
10743                // Static shared libs cannot declare activities
10744                if (!pkg.activities.isEmpty()) {
10745                    throw new PackageManagerException(
10746                            "Static shared libs cannot declare activities");
10747                }
10748
10749                // Static shared libs cannot declare services
10750                if (!pkg.services.isEmpty()) {
10751                    throw new PackageManagerException(
10752                            "Static shared libs cannot declare services");
10753                }
10754
10755                // Static shared libs cannot declare providers
10756                if (!pkg.providers.isEmpty()) {
10757                    throw new PackageManagerException(
10758                            "Static shared libs cannot declare content providers");
10759                }
10760
10761                // Static shared libs cannot declare receivers
10762                if (!pkg.receivers.isEmpty()) {
10763                    throw new PackageManagerException(
10764                            "Static shared libs cannot declare broadcast receivers");
10765                }
10766
10767                // Static shared libs cannot declare permission groups
10768                if (!pkg.permissionGroups.isEmpty()) {
10769                    throw new PackageManagerException(
10770                            "Static shared libs cannot declare permission groups");
10771                }
10772
10773                // Static shared libs cannot declare permissions
10774                if (!pkg.permissions.isEmpty()) {
10775                    throw new PackageManagerException(
10776                            "Static shared libs cannot declare permissions");
10777                }
10778
10779                // Static shared libs cannot declare protected broadcasts
10780                if (pkg.protectedBroadcasts != null) {
10781                    throw new PackageManagerException(
10782                            "Static shared libs cannot declare protected broadcasts");
10783                }
10784
10785                // Static shared libs cannot be overlay targets
10786                if (pkg.mOverlayTarget != null) {
10787                    throw new PackageManagerException(
10788                            "Static shared libs cannot be overlay targets");
10789                }
10790
10791                // The version codes must be ordered as lib versions
10792                int minVersionCode = Integer.MIN_VALUE;
10793                int maxVersionCode = Integer.MAX_VALUE;
10794
10795                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10796                        pkg.staticSharedLibName);
10797                if (versionedLib != null) {
10798                    final int versionCount = versionedLib.size();
10799                    for (int i = 0; i < versionCount; i++) {
10800                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10801                        final int libVersionCode = libInfo.getDeclaringPackage()
10802                                .getVersionCode();
10803                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10804                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10805                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10806                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10807                        } else {
10808                            minVersionCode = maxVersionCode = libVersionCode;
10809                            break;
10810                        }
10811                    }
10812                }
10813                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10814                    throw new PackageManagerException("Static shared"
10815                            + " lib version codes must be ordered as lib versions");
10816                }
10817            }
10818
10819            // Only privileged apps and updated privileged apps can add child packages.
10820            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10821                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10822                    throw new PackageManagerException("Only privileged apps can add child "
10823                            + "packages. Ignoring package " + pkg.packageName);
10824                }
10825                final int childCount = pkg.childPackages.size();
10826                for (int i = 0; i < childCount; i++) {
10827                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10828                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10829                            childPkg.packageName)) {
10830                        throw new PackageManagerException("Can't override child of "
10831                                + "another disabled app. Ignoring package " + pkg.packageName);
10832                    }
10833                }
10834            }
10835
10836            // If we're only installing presumed-existing packages, require that the
10837            // scanned APK is both already known and at the path previously established
10838            // for it.  Previously unknown packages we pick up normally, but if we have an
10839            // a priori expectation about this package's install presence, enforce it.
10840            // With a singular exception for new system packages. When an OTA contains
10841            // a new system package, we allow the codepath to change from a system location
10842            // to the user-installed location. If we don't allow this change, any newer,
10843            // user-installed version of the application will be ignored.
10844            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10845                if (mExpectingBetter.containsKey(pkg.packageName)) {
10846                    logCriticalInfo(Log.WARN,
10847                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10848                } else {
10849                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10850                    if (known != null) {
10851                        if (DEBUG_PACKAGE_SCANNING) {
10852                            Log.d(TAG, "Examining " + pkg.codePath
10853                                    + " and requiring known paths " + known.codePathString
10854                                    + " & " + known.resourcePathString);
10855                        }
10856                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10857                                || !pkg.applicationInfo.getResourcePath().equals(
10858                                        known.resourcePathString)) {
10859                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10860                                    "Application package " + pkg.packageName
10861                                    + " found at " + pkg.applicationInfo.getCodePath()
10862                                    + " but expected at " + known.codePathString
10863                                    + "; ignoring.");
10864                        }
10865                    }
10866                }
10867            }
10868
10869            // Verify that this new package doesn't have any content providers
10870            // that conflict with existing packages.  Only do this if the
10871            // package isn't already installed, since we don't want to break
10872            // things that are installed.
10873            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10874                final int N = pkg.providers.size();
10875                int i;
10876                for (i=0; i<N; i++) {
10877                    PackageParser.Provider p = pkg.providers.get(i);
10878                    if (p.info.authority != null) {
10879                        String names[] = p.info.authority.split(";");
10880                        for (int j = 0; j < names.length; j++) {
10881                            if (mProvidersByAuthority.containsKey(names[j])) {
10882                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10883                                final String otherPackageName =
10884                                        ((other != null && other.getComponentName() != null) ?
10885                                                other.getComponentName().getPackageName() : "?");
10886                                throw new PackageManagerException(
10887                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10888                                        "Can't install because provider name " + names[j]
10889                                                + " (in package " + pkg.applicationInfo.packageName
10890                                                + ") is already used by " + otherPackageName);
10891                            }
10892                        }
10893                    }
10894                }
10895            }
10896        }
10897    }
10898
10899    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10900            int type, String declaringPackageName, int declaringVersionCode) {
10901        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10902        if (versionedLib == null) {
10903            versionedLib = new SparseArray<>();
10904            mSharedLibraries.put(name, versionedLib);
10905            if (type == SharedLibraryInfo.TYPE_STATIC) {
10906                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10907            }
10908        } else if (versionedLib.indexOfKey(version) >= 0) {
10909            return false;
10910        }
10911        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10912                version, type, declaringPackageName, declaringVersionCode);
10913        versionedLib.put(version, libEntry);
10914        return true;
10915    }
10916
10917    private boolean removeSharedLibraryLPw(String name, int version) {
10918        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10919        if (versionedLib == null) {
10920            return false;
10921        }
10922        final int libIdx = versionedLib.indexOfKey(version);
10923        if (libIdx < 0) {
10924            return false;
10925        }
10926        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10927        versionedLib.remove(version);
10928        if (versionedLib.size() <= 0) {
10929            mSharedLibraries.remove(name);
10930            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10931                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10932                        .getPackageName());
10933            }
10934        }
10935        return true;
10936    }
10937
10938    /**
10939     * Adds a scanned package to the system. When this method is finished, the package will
10940     * be available for query, resolution, etc...
10941     */
10942    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10943            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10944        final String pkgName = pkg.packageName;
10945        if (mCustomResolverComponentName != null &&
10946                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10947            setUpCustomResolverActivity(pkg);
10948        }
10949
10950        if (pkg.packageName.equals("android")) {
10951            synchronized (mPackages) {
10952                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10953                    // Set up information for our fall-back user intent resolution activity.
10954                    mPlatformPackage = pkg;
10955                    pkg.mVersionCode = mSdkVersion;
10956                    mAndroidApplication = pkg.applicationInfo;
10957                    if (!mResolverReplaced) {
10958                        mResolveActivity.applicationInfo = mAndroidApplication;
10959                        mResolveActivity.name = ResolverActivity.class.getName();
10960                        mResolveActivity.packageName = mAndroidApplication.packageName;
10961                        mResolveActivity.processName = "system:ui";
10962                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10963                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10964                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10965                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10966                        mResolveActivity.exported = true;
10967                        mResolveActivity.enabled = true;
10968                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10969                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10970                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10971                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10972                                | ActivityInfo.CONFIG_ORIENTATION
10973                                | ActivityInfo.CONFIG_KEYBOARD
10974                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10975                        mResolveInfo.activityInfo = mResolveActivity;
10976                        mResolveInfo.priority = 0;
10977                        mResolveInfo.preferredOrder = 0;
10978                        mResolveInfo.match = 0;
10979                        mResolveComponentName = new ComponentName(
10980                                mAndroidApplication.packageName, mResolveActivity.name);
10981                    }
10982                }
10983            }
10984        }
10985
10986        ArrayList<PackageParser.Package> clientLibPkgs = null;
10987        // writer
10988        synchronized (mPackages) {
10989            boolean hasStaticSharedLibs = false;
10990
10991            // Any app can add new static shared libraries
10992            if (pkg.staticSharedLibName != null) {
10993                // Static shared libs don't allow renaming as they have synthetic package
10994                // names to allow install of multiple versions, so use name from manifest.
10995                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10996                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10997                        pkg.manifestPackageName, pkg.mVersionCode)) {
10998                    hasStaticSharedLibs = true;
10999                } else {
11000                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11001                                + pkg.staticSharedLibName + " already exists; skipping");
11002                }
11003                // Static shared libs cannot be updated once installed since they
11004                // use synthetic package name which includes the version code, so
11005                // not need to update other packages's shared lib dependencies.
11006            }
11007
11008            if (!hasStaticSharedLibs
11009                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11010                // Only system apps can add new dynamic shared libraries.
11011                if (pkg.libraryNames != null) {
11012                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11013                        String name = pkg.libraryNames.get(i);
11014                        boolean allowed = false;
11015                        if (pkg.isUpdatedSystemApp()) {
11016                            // New library entries can only be added through the
11017                            // system image.  This is important to get rid of a lot
11018                            // of nasty edge cases: for example if we allowed a non-
11019                            // system update of the app to add a library, then uninstalling
11020                            // the update would make the library go away, and assumptions
11021                            // we made such as through app install filtering would now
11022                            // have allowed apps on the device which aren't compatible
11023                            // with it.  Better to just have the restriction here, be
11024                            // conservative, and create many fewer cases that can negatively
11025                            // impact the user experience.
11026                            final PackageSetting sysPs = mSettings
11027                                    .getDisabledSystemPkgLPr(pkg.packageName);
11028                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11029                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11030                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11031                                        allowed = true;
11032                                        break;
11033                                    }
11034                                }
11035                            }
11036                        } else {
11037                            allowed = true;
11038                        }
11039                        if (allowed) {
11040                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11041                                    SharedLibraryInfo.VERSION_UNDEFINED,
11042                                    SharedLibraryInfo.TYPE_DYNAMIC,
11043                                    pkg.packageName, pkg.mVersionCode)) {
11044                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11045                                        + name + " already exists; skipping");
11046                            }
11047                        } else {
11048                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11049                                    + name + " that is not declared on system image; skipping");
11050                        }
11051                    }
11052
11053                    if ((scanFlags & SCAN_BOOTING) == 0) {
11054                        // If we are not booting, we need to update any applications
11055                        // that are clients of our shared library.  If we are booting,
11056                        // this will all be done once the scan is complete.
11057                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11058                    }
11059                }
11060            }
11061        }
11062
11063        if ((scanFlags & SCAN_BOOTING) != 0) {
11064            // No apps can run during boot scan, so they don't need to be frozen
11065        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11066            // Caller asked to not kill app, so it's probably not frozen
11067        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11068            // Caller asked us to ignore frozen check for some reason; they
11069            // probably didn't know the package name
11070        } else {
11071            // We're doing major surgery on this package, so it better be frozen
11072            // right now to keep it from launching
11073            checkPackageFrozen(pkgName);
11074        }
11075
11076        // Also need to kill any apps that are dependent on the library.
11077        if (clientLibPkgs != null) {
11078            for (int i=0; i<clientLibPkgs.size(); i++) {
11079                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11080                killApplication(clientPkg.applicationInfo.packageName,
11081                        clientPkg.applicationInfo.uid, "update lib");
11082            }
11083        }
11084
11085        // writer
11086        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11087
11088        synchronized (mPackages) {
11089            // We don't expect installation to fail beyond this point
11090
11091            // Add the new setting to mSettings
11092            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11093            // Add the new setting to mPackages
11094            mPackages.put(pkg.applicationInfo.packageName, pkg);
11095            // Make sure we don't accidentally delete its data.
11096            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11097            while (iter.hasNext()) {
11098                PackageCleanItem item = iter.next();
11099                if (pkgName.equals(item.packageName)) {
11100                    iter.remove();
11101                }
11102            }
11103
11104            // Add the package's KeySets to the global KeySetManagerService
11105            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11106            ksms.addScannedPackageLPw(pkg);
11107
11108            int N = pkg.providers.size();
11109            StringBuilder r = null;
11110            int i;
11111            for (i=0; i<N; i++) {
11112                PackageParser.Provider p = pkg.providers.get(i);
11113                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11114                        p.info.processName);
11115                mProviders.addProvider(p);
11116                p.syncable = p.info.isSyncable;
11117                if (p.info.authority != null) {
11118                    String names[] = p.info.authority.split(";");
11119                    p.info.authority = null;
11120                    for (int j = 0; j < names.length; j++) {
11121                        if (j == 1 && p.syncable) {
11122                            // We only want the first authority for a provider to possibly be
11123                            // syncable, so if we already added this provider using a different
11124                            // authority clear the syncable flag. We copy the provider before
11125                            // changing it because the mProviders object contains a reference
11126                            // to a provider that we don't want to change.
11127                            // Only do this for the second authority since the resulting provider
11128                            // object can be the same for all future authorities for this provider.
11129                            p = new PackageParser.Provider(p);
11130                            p.syncable = false;
11131                        }
11132                        if (!mProvidersByAuthority.containsKey(names[j])) {
11133                            mProvidersByAuthority.put(names[j], p);
11134                            if (p.info.authority == null) {
11135                                p.info.authority = names[j];
11136                            } else {
11137                                p.info.authority = p.info.authority + ";" + names[j];
11138                            }
11139                            if (DEBUG_PACKAGE_SCANNING) {
11140                                if (chatty)
11141                                    Log.d(TAG, "Registered content provider: " + names[j]
11142                                            + ", className = " + p.info.name + ", isSyncable = "
11143                                            + p.info.isSyncable);
11144                            }
11145                        } else {
11146                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11147                            Slog.w(TAG, "Skipping provider name " + names[j] +
11148                                    " (in package " + pkg.applicationInfo.packageName +
11149                                    "): name already used by "
11150                                    + ((other != null && other.getComponentName() != null)
11151                                            ? other.getComponentName().getPackageName() : "?"));
11152                        }
11153                    }
11154                }
11155                if (chatty) {
11156                    if (r == null) {
11157                        r = new StringBuilder(256);
11158                    } else {
11159                        r.append(' ');
11160                    }
11161                    r.append(p.info.name);
11162                }
11163            }
11164            if (r != null) {
11165                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11166            }
11167
11168            N = pkg.services.size();
11169            r = null;
11170            for (i=0; i<N; i++) {
11171                PackageParser.Service s = pkg.services.get(i);
11172                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11173                        s.info.processName);
11174                mServices.addService(s);
11175                if (chatty) {
11176                    if (r == null) {
11177                        r = new StringBuilder(256);
11178                    } else {
11179                        r.append(' ');
11180                    }
11181                    r.append(s.info.name);
11182                }
11183            }
11184            if (r != null) {
11185                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11186            }
11187
11188            N = pkg.receivers.size();
11189            r = null;
11190            for (i=0; i<N; i++) {
11191                PackageParser.Activity a = pkg.receivers.get(i);
11192                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11193                        a.info.processName);
11194                mReceivers.addActivity(a, "receiver");
11195                if (chatty) {
11196                    if (r == null) {
11197                        r = new StringBuilder(256);
11198                    } else {
11199                        r.append(' ');
11200                    }
11201                    r.append(a.info.name);
11202                }
11203            }
11204            if (r != null) {
11205                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11206            }
11207
11208            N = pkg.activities.size();
11209            r = null;
11210            for (i=0; i<N; i++) {
11211                PackageParser.Activity a = pkg.activities.get(i);
11212                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11213                        a.info.processName);
11214                mActivities.addActivity(a, "activity");
11215                if (chatty) {
11216                    if (r == null) {
11217                        r = new StringBuilder(256);
11218                    } else {
11219                        r.append(' ');
11220                    }
11221                    r.append(a.info.name);
11222                }
11223            }
11224            if (r != null) {
11225                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11226            }
11227
11228            N = pkg.permissionGroups.size();
11229            r = null;
11230            for (i=0; i<N; i++) {
11231                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11232                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11233                final String curPackageName = cur == null ? null : cur.info.packageName;
11234                // Dont allow ephemeral apps to define new permission groups.
11235                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11236                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11237                            + pg.info.packageName
11238                            + " ignored: instant apps cannot define new permission groups.");
11239                    continue;
11240                }
11241                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11242                if (cur == null || isPackageUpdate) {
11243                    mPermissionGroups.put(pg.info.name, pg);
11244                    if (chatty) {
11245                        if (r == null) {
11246                            r = new StringBuilder(256);
11247                        } else {
11248                            r.append(' ');
11249                        }
11250                        if (isPackageUpdate) {
11251                            r.append("UPD:");
11252                        }
11253                        r.append(pg.info.name);
11254                    }
11255                } else {
11256                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11257                            + pg.info.packageName + " ignored: original from "
11258                            + cur.info.packageName);
11259                    if (chatty) {
11260                        if (r == null) {
11261                            r = new StringBuilder(256);
11262                        } else {
11263                            r.append(' ');
11264                        }
11265                        r.append("DUP:");
11266                        r.append(pg.info.name);
11267                    }
11268                }
11269            }
11270            if (r != null) {
11271                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11272            }
11273
11274            N = pkg.permissions.size();
11275            r = null;
11276            for (i=0; i<N; i++) {
11277                PackageParser.Permission p = pkg.permissions.get(i);
11278
11279                // Dont allow ephemeral apps to define new permissions.
11280                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11281                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11282                            + p.info.packageName
11283                            + " ignored: instant apps cannot define new permissions.");
11284                    continue;
11285                }
11286
11287                // Assume by default that we did not install this permission into the system.
11288                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11289
11290                // Now that permission groups have a special meaning, we ignore permission
11291                // groups for legacy apps to prevent unexpected behavior. In particular,
11292                // permissions for one app being granted to someone just because they happen
11293                // to be in a group defined by another app (before this had no implications).
11294                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11295                    p.group = mPermissionGroups.get(p.info.group);
11296                    // Warn for a permission in an unknown group.
11297                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11298                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11299                                + p.info.packageName + " in an unknown group " + p.info.group);
11300                    }
11301                }
11302
11303                ArrayMap<String, BasePermission> permissionMap =
11304                        p.tree ? mSettings.mPermissionTrees
11305                                : mSettings.mPermissions;
11306                BasePermission bp = permissionMap.get(p.info.name);
11307
11308                // Allow system apps to redefine non-system permissions
11309                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11310                    final boolean currentOwnerIsSystem = (bp.perm != null
11311                            && isSystemApp(bp.perm.owner));
11312                    if (isSystemApp(p.owner)) {
11313                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11314                            // It's a built-in permission and no owner, take ownership now
11315                            bp.packageSetting = pkgSetting;
11316                            bp.perm = p;
11317                            bp.uid = pkg.applicationInfo.uid;
11318                            bp.sourcePackage = p.info.packageName;
11319                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11320                        } else if (!currentOwnerIsSystem) {
11321                            String msg = "New decl " + p.owner + " of permission  "
11322                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11323                            reportSettingsProblem(Log.WARN, msg);
11324                            bp = null;
11325                        }
11326                    }
11327                }
11328
11329                if (bp == null) {
11330                    bp = new BasePermission(p.info.name, p.info.packageName,
11331                            BasePermission.TYPE_NORMAL);
11332                    permissionMap.put(p.info.name, bp);
11333                }
11334
11335                if (bp.perm == null) {
11336                    if (bp.sourcePackage == null
11337                            || bp.sourcePackage.equals(p.info.packageName)) {
11338                        BasePermission tree = findPermissionTreeLP(p.info.name);
11339                        if (tree == null
11340                                || tree.sourcePackage.equals(p.info.packageName)) {
11341                            bp.packageSetting = pkgSetting;
11342                            bp.perm = p;
11343                            bp.uid = pkg.applicationInfo.uid;
11344                            bp.sourcePackage = p.info.packageName;
11345                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11346                            if (chatty) {
11347                                if (r == null) {
11348                                    r = new StringBuilder(256);
11349                                } else {
11350                                    r.append(' ');
11351                                }
11352                                r.append(p.info.name);
11353                            }
11354                        } else {
11355                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11356                                    + p.info.packageName + " ignored: base tree "
11357                                    + tree.name + " is from package "
11358                                    + tree.sourcePackage);
11359                        }
11360                    } else {
11361                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11362                                + p.info.packageName + " ignored: original from "
11363                                + bp.sourcePackage);
11364                    }
11365                } else if (chatty) {
11366                    if (r == null) {
11367                        r = new StringBuilder(256);
11368                    } else {
11369                        r.append(' ');
11370                    }
11371                    r.append("DUP:");
11372                    r.append(p.info.name);
11373                }
11374                if (bp.perm == p) {
11375                    bp.protectionLevel = p.info.protectionLevel;
11376                }
11377            }
11378
11379            if (r != null) {
11380                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11381            }
11382
11383            N = pkg.instrumentation.size();
11384            r = null;
11385            for (i=0; i<N; i++) {
11386                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11387                a.info.packageName = pkg.applicationInfo.packageName;
11388                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11389                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11390                a.info.splitNames = pkg.splitNames;
11391                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11392                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11393                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11394                a.info.dataDir = pkg.applicationInfo.dataDir;
11395                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11396                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11397                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11398                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11399                mInstrumentation.put(a.getComponentName(), a);
11400                if (chatty) {
11401                    if (r == null) {
11402                        r = new StringBuilder(256);
11403                    } else {
11404                        r.append(' ');
11405                    }
11406                    r.append(a.info.name);
11407                }
11408            }
11409            if (r != null) {
11410                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11411            }
11412
11413            if (pkg.protectedBroadcasts != null) {
11414                N = pkg.protectedBroadcasts.size();
11415                for (i=0; i<N; i++) {
11416                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11417                }
11418            }
11419        }
11420
11421        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11422    }
11423
11424    /**
11425     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11426     * is derived purely on the basis of the contents of {@code scanFile} and
11427     * {@code cpuAbiOverride}.
11428     *
11429     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11430     */
11431    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11432                                 String cpuAbiOverride, boolean extractLibs,
11433                                 File appLib32InstallDir)
11434            throws PackageManagerException {
11435        // Give ourselves some initial paths; we'll come back for another
11436        // pass once we've determined ABI below.
11437        setNativeLibraryPaths(pkg, appLib32InstallDir);
11438
11439        // We would never need to extract libs for forward-locked and external packages,
11440        // since the container service will do it for us. We shouldn't attempt to
11441        // extract libs from system app when it was not updated.
11442        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11443                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11444            extractLibs = false;
11445        }
11446
11447        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11448        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11449
11450        NativeLibraryHelper.Handle handle = null;
11451        try {
11452            handle = NativeLibraryHelper.Handle.create(pkg);
11453            // TODO(multiArch): This can be null for apps that didn't go through the
11454            // usual installation process. We can calculate it again, like we
11455            // do during install time.
11456            //
11457            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11458            // unnecessary.
11459            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11460
11461            // Null out the abis so that they can be recalculated.
11462            pkg.applicationInfo.primaryCpuAbi = null;
11463            pkg.applicationInfo.secondaryCpuAbi = null;
11464            if (isMultiArch(pkg.applicationInfo)) {
11465                // Warn if we've set an abiOverride for multi-lib packages..
11466                // By definition, we need to copy both 32 and 64 bit libraries for
11467                // such packages.
11468                if (pkg.cpuAbiOverride != null
11469                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11470                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11471                }
11472
11473                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11474                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11475                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11476                    if (extractLibs) {
11477                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11478                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11479                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11480                                useIsaSpecificSubdirs);
11481                    } else {
11482                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11483                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11484                    }
11485                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11486                }
11487
11488                // Shared library native code should be in the APK zip aligned
11489                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11490                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11491                            "Shared library native lib extraction not supported");
11492                }
11493
11494                maybeThrowExceptionForMultiArchCopy(
11495                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11496
11497                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11498                    if (extractLibs) {
11499                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11500                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11501                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11502                                useIsaSpecificSubdirs);
11503                    } else {
11504                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11505                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11506                    }
11507                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11508                }
11509
11510                maybeThrowExceptionForMultiArchCopy(
11511                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11512
11513                if (abi64 >= 0) {
11514                    // Shared library native libs should be in the APK zip aligned
11515                    if (extractLibs && pkg.isLibrary()) {
11516                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11517                                "Shared library native lib extraction not supported");
11518                    }
11519                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11520                }
11521
11522                if (abi32 >= 0) {
11523                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11524                    if (abi64 >= 0) {
11525                        if (pkg.use32bitAbi) {
11526                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11527                            pkg.applicationInfo.primaryCpuAbi = abi;
11528                        } else {
11529                            pkg.applicationInfo.secondaryCpuAbi = abi;
11530                        }
11531                    } else {
11532                        pkg.applicationInfo.primaryCpuAbi = abi;
11533                    }
11534                }
11535            } else {
11536                String[] abiList = (cpuAbiOverride != null) ?
11537                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11538
11539                // Enable gross and lame hacks for apps that are built with old
11540                // SDK tools. We must scan their APKs for renderscript bitcode and
11541                // not launch them if it's present. Don't bother checking on devices
11542                // that don't have 64 bit support.
11543                boolean needsRenderScriptOverride = false;
11544                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11545                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11546                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11547                    needsRenderScriptOverride = true;
11548                }
11549
11550                final int copyRet;
11551                if (extractLibs) {
11552                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11553                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11554                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11555                } else {
11556                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11557                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11558                }
11559                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11560
11561                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11562                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11563                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11564                }
11565
11566                if (copyRet >= 0) {
11567                    // Shared libraries that have native libs must be multi-architecture
11568                    if (pkg.isLibrary()) {
11569                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11570                                "Shared library with native libs must be multiarch");
11571                    }
11572                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11573                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11574                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11575                } else if (needsRenderScriptOverride) {
11576                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11577                }
11578            }
11579        } catch (IOException ioe) {
11580            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11581        } finally {
11582            IoUtils.closeQuietly(handle);
11583        }
11584
11585        // Now that we've calculated the ABIs and determined if it's an internal app,
11586        // we will go ahead and populate the nativeLibraryPath.
11587        setNativeLibraryPaths(pkg, appLib32InstallDir);
11588    }
11589
11590    /**
11591     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11592     * i.e, so that all packages can be run inside a single process if required.
11593     *
11594     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11595     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11596     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11597     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11598     * updating a package that belongs to a shared user.
11599     *
11600     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11601     * adds unnecessary complexity.
11602     */
11603    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11604            PackageParser.Package scannedPackage) {
11605        String requiredInstructionSet = null;
11606        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11607            requiredInstructionSet = VMRuntime.getInstructionSet(
11608                     scannedPackage.applicationInfo.primaryCpuAbi);
11609        }
11610
11611        PackageSetting requirer = null;
11612        for (PackageSetting ps : packagesForUser) {
11613            // If packagesForUser contains scannedPackage, we skip it. This will happen
11614            // when scannedPackage is an update of an existing package. Without this check,
11615            // we will never be able to change the ABI of any package belonging to a shared
11616            // user, even if it's compatible with other packages.
11617            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11618                if (ps.primaryCpuAbiString == null) {
11619                    continue;
11620                }
11621
11622                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11623                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11624                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11625                    // this but there's not much we can do.
11626                    String errorMessage = "Instruction set mismatch, "
11627                            + ((requirer == null) ? "[caller]" : requirer)
11628                            + " requires " + requiredInstructionSet + " whereas " + ps
11629                            + " requires " + instructionSet;
11630                    Slog.w(TAG, errorMessage);
11631                }
11632
11633                if (requiredInstructionSet == null) {
11634                    requiredInstructionSet = instructionSet;
11635                    requirer = ps;
11636                }
11637            }
11638        }
11639
11640        if (requiredInstructionSet != null) {
11641            String adjustedAbi;
11642            if (requirer != null) {
11643                // requirer != null implies that either scannedPackage was null or that scannedPackage
11644                // did not require an ABI, in which case we have to adjust scannedPackage to match
11645                // the ABI of the set (which is the same as requirer's ABI)
11646                adjustedAbi = requirer.primaryCpuAbiString;
11647                if (scannedPackage != null) {
11648                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11649                }
11650            } else {
11651                // requirer == null implies that we're updating all ABIs in the set to
11652                // match scannedPackage.
11653                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11654            }
11655
11656            for (PackageSetting ps : packagesForUser) {
11657                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11658                    if (ps.primaryCpuAbiString != null) {
11659                        continue;
11660                    }
11661
11662                    ps.primaryCpuAbiString = adjustedAbi;
11663                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11664                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11665                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11666                        if (DEBUG_ABI_SELECTION) {
11667                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11668                                    + " (requirer="
11669                                    + (requirer != null ? requirer.pkg : "null")
11670                                    + ", scannedPackage="
11671                                    + (scannedPackage != null ? scannedPackage : "null")
11672                                    + ")");
11673                        }
11674                        try {
11675                            mInstaller.rmdex(ps.codePathString,
11676                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11677                        } catch (InstallerException ignored) {
11678                        }
11679                    }
11680                }
11681            }
11682        }
11683    }
11684
11685    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11686        synchronized (mPackages) {
11687            mResolverReplaced = true;
11688            // Set up information for custom user intent resolution activity.
11689            mResolveActivity.applicationInfo = pkg.applicationInfo;
11690            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11691            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11692            mResolveActivity.processName = pkg.applicationInfo.packageName;
11693            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11694            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11695                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11696            mResolveActivity.theme = 0;
11697            mResolveActivity.exported = true;
11698            mResolveActivity.enabled = true;
11699            mResolveInfo.activityInfo = mResolveActivity;
11700            mResolveInfo.priority = 0;
11701            mResolveInfo.preferredOrder = 0;
11702            mResolveInfo.match = 0;
11703            mResolveComponentName = mCustomResolverComponentName;
11704            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11705                    mResolveComponentName);
11706        }
11707    }
11708
11709    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11710        if (installerActivity == null) {
11711            if (DEBUG_EPHEMERAL) {
11712                Slog.d(TAG, "Clear ephemeral installer activity");
11713            }
11714            mInstantAppInstallerActivity = null;
11715            return;
11716        }
11717
11718        if (DEBUG_EPHEMERAL) {
11719            Slog.d(TAG, "Set ephemeral installer activity: "
11720                    + installerActivity.getComponentName());
11721        }
11722        // Set up information for ephemeral installer activity
11723        mInstantAppInstallerActivity = installerActivity;
11724        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11725                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11726        mInstantAppInstallerActivity.exported = true;
11727        mInstantAppInstallerActivity.enabled = true;
11728        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11729        mInstantAppInstallerInfo.priority = 0;
11730        mInstantAppInstallerInfo.preferredOrder = 1;
11731        mInstantAppInstallerInfo.isDefault = true;
11732        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11733                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11734    }
11735
11736    private static String calculateBundledApkRoot(final String codePathString) {
11737        final File codePath = new File(codePathString);
11738        final File codeRoot;
11739        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11740            codeRoot = Environment.getRootDirectory();
11741        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11742            codeRoot = Environment.getOemDirectory();
11743        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11744            codeRoot = Environment.getVendorDirectory();
11745        } else {
11746            // Unrecognized code path; take its top real segment as the apk root:
11747            // e.g. /something/app/blah.apk => /something
11748            try {
11749                File f = codePath.getCanonicalFile();
11750                File parent = f.getParentFile();    // non-null because codePath is a file
11751                File tmp;
11752                while ((tmp = parent.getParentFile()) != null) {
11753                    f = parent;
11754                    parent = tmp;
11755                }
11756                codeRoot = f;
11757                Slog.w(TAG, "Unrecognized code path "
11758                        + codePath + " - using " + codeRoot);
11759            } catch (IOException e) {
11760                // Can't canonicalize the code path -- shenanigans?
11761                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11762                return Environment.getRootDirectory().getPath();
11763            }
11764        }
11765        return codeRoot.getPath();
11766    }
11767
11768    /**
11769     * Derive and set the location of native libraries for the given package,
11770     * which varies depending on where and how the package was installed.
11771     */
11772    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11773        final ApplicationInfo info = pkg.applicationInfo;
11774        final String codePath = pkg.codePath;
11775        final File codeFile = new File(codePath);
11776        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11777        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11778
11779        info.nativeLibraryRootDir = null;
11780        info.nativeLibraryRootRequiresIsa = false;
11781        info.nativeLibraryDir = null;
11782        info.secondaryNativeLibraryDir = null;
11783
11784        if (isApkFile(codeFile)) {
11785            // Monolithic install
11786            if (bundledApp) {
11787                // If "/system/lib64/apkname" exists, assume that is the per-package
11788                // native library directory to use; otherwise use "/system/lib/apkname".
11789                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11790                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11791                        getPrimaryInstructionSet(info));
11792
11793                // This is a bundled system app so choose the path based on the ABI.
11794                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11795                // is just the default path.
11796                final String apkName = deriveCodePathName(codePath);
11797                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11798                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11799                        apkName).getAbsolutePath();
11800
11801                if (info.secondaryCpuAbi != null) {
11802                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11803                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11804                            secondaryLibDir, apkName).getAbsolutePath();
11805                }
11806            } else if (asecApp) {
11807                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11808                        .getAbsolutePath();
11809            } else {
11810                final String apkName = deriveCodePathName(codePath);
11811                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11812                        .getAbsolutePath();
11813            }
11814
11815            info.nativeLibraryRootRequiresIsa = false;
11816            info.nativeLibraryDir = info.nativeLibraryRootDir;
11817        } else {
11818            // Cluster install
11819            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11820            info.nativeLibraryRootRequiresIsa = true;
11821
11822            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11823                    getPrimaryInstructionSet(info)).getAbsolutePath();
11824
11825            if (info.secondaryCpuAbi != null) {
11826                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11827                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11828            }
11829        }
11830    }
11831
11832    /**
11833     * Calculate the abis and roots for a bundled app. These can uniquely
11834     * be determined from the contents of the system partition, i.e whether
11835     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11836     * of this information, and instead assume that the system was built
11837     * sensibly.
11838     */
11839    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11840                                           PackageSetting pkgSetting) {
11841        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11842
11843        // If "/system/lib64/apkname" exists, assume that is the per-package
11844        // native library directory to use; otherwise use "/system/lib/apkname".
11845        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11846        setBundledAppAbi(pkg, apkRoot, apkName);
11847        // pkgSetting might be null during rescan following uninstall of updates
11848        // to a bundled app, so accommodate that possibility.  The settings in
11849        // that case will be established later from the parsed package.
11850        //
11851        // If the settings aren't null, sync them up with what we've just derived.
11852        // note that apkRoot isn't stored in the package settings.
11853        if (pkgSetting != null) {
11854            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11855            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11856        }
11857    }
11858
11859    /**
11860     * Deduces the ABI of a bundled app and sets the relevant fields on the
11861     * parsed pkg object.
11862     *
11863     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11864     *        under which system libraries are installed.
11865     * @param apkName the name of the installed package.
11866     */
11867    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11868        final File codeFile = new File(pkg.codePath);
11869
11870        final boolean has64BitLibs;
11871        final boolean has32BitLibs;
11872        if (isApkFile(codeFile)) {
11873            // Monolithic install
11874            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11875            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11876        } else {
11877            // Cluster install
11878            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11879            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11880                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11881                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11882                has64BitLibs = (new File(rootDir, isa)).exists();
11883            } else {
11884                has64BitLibs = false;
11885            }
11886            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11887                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11888                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11889                has32BitLibs = (new File(rootDir, isa)).exists();
11890            } else {
11891                has32BitLibs = false;
11892            }
11893        }
11894
11895        if (has64BitLibs && !has32BitLibs) {
11896            // The package has 64 bit libs, but not 32 bit libs. Its primary
11897            // ABI should be 64 bit. We can safely assume here that the bundled
11898            // native libraries correspond to the most preferred ABI in the list.
11899
11900            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11901            pkg.applicationInfo.secondaryCpuAbi = null;
11902        } else if (has32BitLibs && !has64BitLibs) {
11903            // The package has 32 bit libs but not 64 bit libs. Its primary
11904            // ABI should be 32 bit.
11905
11906            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11907            pkg.applicationInfo.secondaryCpuAbi = null;
11908        } else if (has32BitLibs && has64BitLibs) {
11909            // The application has both 64 and 32 bit bundled libraries. We check
11910            // here that the app declares multiArch support, and warn if it doesn't.
11911            //
11912            // We will be lenient here and record both ABIs. The primary will be the
11913            // ABI that's higher on the list, i.e, a device that's configured to prefer
11914            // 64 bit apps will see a 64 bit primary ABI,
11915
11916            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11917                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11918            }
11919
11920            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11921                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11922                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11923            } else {
11924                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11925                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11926            }
11927        } else {
11928            pkg.applicationInfo.primaryCpuAbi = null;
11929            pkg.applicationInfo.secondaryCpuAbi = null;
11930        }
11931    }
11932
11933    private void killApplication(String pkgName, int appId, String reason) {
11934        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11935    }
11936
11937    private void killApplication(String pkgName, int appId, int userId, String reason) {
11938        // Request the ActivityManager to kill the process(only for existing packages)
11939        // so that we do not end up in a confused state while the user is still using the older
11940        // version of the application while the new one gets installed.
11941        final long token = Binder.clearCallingIdentity();
11942        try {
11943            IActivityManager am = ActivityManager.getService();
11944            if (am != null) {
11945                try {
11946                    am.killApplication(pkgName, appId, userId, reason);
11947                } catch (RemoteException e) {
11948                }
11949            }
11950        } finally {
11951            Binder.restoreCallingIdentity(token);
11952        }
11953    }
11954
11955    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11956        // Remove the parent package setting
11957        PackageSetting ps = (PackageSetting) pkg.mExtras;
11958        if (ps != null) {
11959            removePackageLI(ps, chatty);
11960        }
11961        // Remove the child package setting
11962        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11963        for (int i = 0; i < childCount; i++) {
11964            PackageParser.Package childPkg = pkg.childPackages.get(i);
11965            ps = (PackageSetting) childPkg.mExtras;
11966            if (ps != null) {
11967                removePackageLI(ps, chatty);
11968            }
11969        }
11970    }
11971
11972    void removePackageLI(PackageSetting ps, boolean chatty) {
11973        if (DEBUG_INSTALL) {
11974            if (chatty)
11975                Log.d(TAG, "Removing package " + ps.name);
11976        }
11977
11978        // writer
11979        synchronized (mPackages) {
11980            mPackages.remove(ps.name);
11981            final PackageParser.Package pkg = ps.pkg;
11982            if (pkg != null) {
11983                cleanPackageDataStructuresLILPw(pkg, chatty);
11984            }
11985        }
11986    }
11987
11988    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11989        if (DEBUG_INSTALL) {
11990            if (chatty)
11991                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11992        }
11993
11994        // writer
11995        synchronized (mPackages) {
11996            // Remove the parent package
11997            mPackages.remove(pkg.applicationInfo.packageName);
11998            cleanPackageDataStructuresLILPw(pkg, chatty);
11999
12000            // Remove the child packages
12001            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12002            for (int i = 0; i < childCount; i++) {
12003                PackageParser.Package childPkg = pkg.childPackages.get(i);
12004                mPackages.remove(childPkg.applicationInfo.packageName);
12005                cleanPackageDataStructuresLILPw(childPkg, chatty);
12006            }
12007        }
12008    }
12009
12010    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12011        int N = pkg.providers.size();
12012        StringBuilder r = null;
12013        int i;
12014        for (i=0; i<N; i++) {
12015            PackageParser.Provider p = pkg.providers.get(i);
12016            mProviders.removeProvider(p);
12017            if (p.info.authority == null) {
12018
12019                /* There was another ContentProvider with this authority when
12020                 * this app was installed so this authority is null,
12021                 * Ignore it as we don't have to unregister the provider.
12022                 */
12023                continue;
12024            }
12025            String names[] = p.info.authority.split(";");
12026            for (int j = 0; j < names.length; j++) {
12027                if (mProvidersByAuthority.get(names[j]) == p) {
12028                    mProvidersByAuthority.remove(names[j]);
12029                    if (DEBUG_REMOVE) {
12030                        if (chatty)
12031                            Log.d(TAG, "Unregistered content provider: " + names[j]
12032                                    + ", className = " + p.info.name + ", isSyncable = "
12033                                    + p.info.isSyncable);
12034                    }
12035                }
12036            }
12037            if (DEBUG_REMOVE && chatty) {
12038                if (r == null) {
12039                    r = new StringBuilder(256);
12040                } else {
12041                    r.append(' ');
12042                }
12043                r.append(p.info.name);
12044            }
12045        }
12046        if (r != null) {
12047            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12048        }
12049
12050        N = pkg.services.size();
12051        r = null;
12052        for (i=0; i<N; i++) {
12053            PackageParser.Service s = pkg.services.get(i);
12054            mServices.removeService(s);
12055            if (chatty) {
12056                if (r == null) {
12057                    r = new StringBuilder(256);
12058                } else {
12059                    r.append(' ');
12060                }
12061                r.append(s.info.name);
12062            }
12063        }
12064        if (r != null) {
12065            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12066        }
12067
12068        N = pkg.receivers.size();
12069        r = null;
12070        for (i=0; i<N; i++) {
12071            PackageParser.Activity a = pkg.receivers.get(i);
12072            mReceivers.removeActivity(a, "receiver");
12073            if (DEBUG_REMOVE && chatty) {
12074                if (r == null) {
12075                    r = new StringBuilder(256);
12076                } else {
12077                    r.append(' ');
12078                }
12079                r.append(a.info.name);
12080            }
12081        }
12082        if (r != null) {
12083            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12084        }
12085
12086        N = pkg.activities.size();
12087        r = null;
12088        for (i=0; i<N; i++) {
12089            PackageParser.Activity a = pkg.activities.get(i);
12090            mActivities.removeActivity(a, "activity");
12091            if (DEBUG_REMOVE && chatty) {
12092                if (r == null) {
12093                    r = new StringBuilder(256);
12094                } else {
12095                    r.append(' ');
12096                }
12097                r.append(a.info.name);
12098            }
12099        }
12100        if (r != null) {
12101            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12102        }
12103
12104        N = pkg.permissions.size();
12105        r = null;
12106        for (i=0; i<N; i++) {
12107            PackageParser.Permission p = pkg.permissions.get(i);
12108            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12109            if (bp == null) {
12110                bp = mSettings.mPermissionTrees.get(p.info.name);
12111            }
12112            if (bp != null && bp.perm == p) {
12113                bp.perm = null;
12114                if (DEBUG_REMOVE && chatty) {
12115                    if (r == null) {
12116                        r = new StringBuilder(256);
12117                    } else {
12118                        r.append(' ');
12119                    }
12120                    r.append(p.info.name);
12121                }
12122            }
12123            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12124                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12125                if (appOpPkgs != null) {
12126                    appOpPkgs.remove(pkg.packageName);
12127                }
12128            }
12129        }
12130        if (r != null) {
12131            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12132        }
12133
12134        N = pkg.requestedPermissions.size();
12135        r = null;
12136        for (i=0; i<N; i++) {
12137            String perm = pkg.requestedPermissions.get(i);
12138            BasePermission bp = mSettings.mPermissions.get(perm);
12139            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12140                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12141                if (appOpPkgs != null) {
12142                    appOpPkgs.remove(pkg.packageName);
12143                    if (appOpPkgs.isEmpty()) {
12144                        mAppOpPermissionPackages.remove(perm);
12145                    }
12146                }
12147            }
12148        }
12149        if (r != null) {
12150            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12151        }
12152
12153        N = pkg.instrumentation.size();
12154        r = null;
12155        for (i=0; i<N; i++) {
12156            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12157            mInstrumentation.remove(a.getComponentName());
12158            if (DEBUG_REMOVE && chatty) {
12159                if (r == null) {
12160                    r = new StringBuilder(256);
12161                } else {
12162                    r.append(' ');
12163                }
12164                r.append(a.info.name);
12165            }
12166        }
12167        if (r != null) {
12168            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12169        }
12170
12171        r = null;
12172        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12173            // Only system apps can hold shared libraries.
12174            if (pkg.libraryNames != null) {
12175                for (i = 0; i < pkg.libraryNames.size(); i++) {
12176                    String name = pkg.libraryNames.get(i);
12177                    if (removeSharedLibraryLPw(name, 0)) {
12178                        if (DEBUG_REMOVE && chatty) {
12179                            if (r == null) {
12180                                r = new StringBuilder(256);
12181                            } else {
12182                                r.append(' ');
12183                            }
12184                            r.append(name);
12185                        }
12186                    }
12187                }
12188            }
12189        }
12190
12191        r = null;
12192
12193        // Any package can hold static shared libraries.
12194        if (pkg.staticSharedLibName != null) {
12195            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12196                if (DEBUG_REMOVE && chatty) {
12197                    if (r == null) {
12198                        r = new StringBuilder(256);
12199                    } else {
12200                        r.append(' ');
12201                    }
12202                    r.append(pkg.staticSharedLibName);
12203                }
12204            }
12205        }
12206
12207        if (r != null) {
12208            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12209        }
12210    }
12211
12212    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12213        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12214            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12215                return true;
12216            }
12217        }
12218        return false;
12219    }
12220
12221    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12222    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12223    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12224
12225    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12226        // Update the parent permissions
12227        updatePermissionsLPw(pkg.packageName, pkg, flags);
12228        // Update the child permissions
12229        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12230        for (int i = 0; i < childCount; i++) {
12231            PackageParser.Package childPkg = pkg.childPackages.get(i);
12232            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12233        }
12234    }
12235
12236    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12237            int flags) {
12238        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12239        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12240    }
12241
12242    private void updatePermissionsLPw(String changingPkg,
12243            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12244        // Make sure there are no dangling permission trees.
12245        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12246        while (it.hasNext()) {
12247            final BasePermission bp = it.next();
12248            if (bp.packageSetting == null) {
12249                // We may not yet have parsed the package, so just see if
12250                // we still know about its settings.
12251                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12252            }
12253            if (bp.packageSetting == null) {
12254                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12255                        + " from package " + bp.sourcePackage);
12256                it.remove();
12257            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12258                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12259                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12260                            + " from package " + bp.sourcePackage);
12261                    flags |= UPDATE_PERMISSIONS_ALL;
12262                    it.remove();
12263                }
12264            }
12265        }
12266
12267        // Make sure all dynamic permissions have been assigned to a package,
12268        // and make sure there are no dangling permissions.
12269        it = mSettings.mPermissions.values().iterator();
12270        while (it.hasNext()) {
12271            final BasePermission bp = it.next();
12272            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12273                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12274                        + bp.name + " pkg=" + bp.sourcePackage
12275                        + " info=" + bp.pendingInfo);
12276                if (bp.packageSetting == null && bp.pendingInfo != null) {
12277                    final BasePermission tree = findPermissionTreeLP(bp.name);
12278                    if (tree != null && tree.perm != null) {
12279                        bp.packageSetting = tree.packageSetting;
12280                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12281                                new PermissionInfo(bp.pendingInfo));
12282                        bp.perm.info.packageName = tree.perm.info.packageName;
12283                        bp.perm.info.name = bp.name;
12284                        bp.uid = tree.uid;
12285                    }
12286                }
12287            }
12288            if (bp.packageSetting == null) {
12289                // We may not yet have parsed the package, so just see if
12290                // we still know about its settings.
12291                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12292            }
12293            if (bp.packageSetting == null) {
12294                Slog.w(TAG, "Removing dangling permission: " + bp.name
12295                        + " from package " + bp.sourcePackage);
12296                it.remove();
12297            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12298                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12299                    Slog.i(TAG, "Removing old permission: " + bp.name
12300                            + " from package " + bp.sourcePackage);
12301                    flags |= UPDATE_PERMISSIONS_ALL;
12302                    it.remove();
12303                }
12304            }
12305        }
12306
12307        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12308        // Now update the permissions for all packages, in particular
12309        // replace the granted permissions of the system packages.
12310        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12311            for (PackageParser.Package pkg : mPackages.values()) {
12312                if (pkg != pkgInfo) {
12313                    // Only replace for packages on requested volume
12314                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12315                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12316                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12317                    grantPermissionsLPw(pkg, replace, changingPkg);
12318                }
12319            }
12320        }
12321
12322        if (pkgInfo != null) {
12323            // Only replace for packages on requested volume
12324            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12325            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12326                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12327            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12328        }
12329        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12330    }
12331
12332    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12333            String packageOfInterest) {
12334        // IMPORTANT: There are two types of permissions: install and runtime.
12335        // Install time permissions are granted when the app is installed to
12336        // all device users and users added in the future. Runtime permissions
12337        // are granted at runtime explicitly to specific users. Normal and signature
12338        // protected permissions are install time permissions. Dangerous permissions
12339        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12340        // otherwise they are runtime permissions. This function does not manage
12341        // runtime permissions except for the case an app targeting Lollipop MR1
12342        // being upgraded to target a newer SDK, in which case dangerous permissions
12343        // are transformed from install time to runtime ones.
12344
12345        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12346        if (ps == null) {
12347            return;
12348        }
12349
12350        PermissionsState permissionsState = ps.getPermissionsState();
12351        PermissionsState origPermissions = permissionsState;
12352
12353        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12354
12355        boolean runtimePermissionsRevoked = false;
12356        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12357
12358        boolean changedInstallPermission = false;
12359
12360        if (replace) {
12361            ps.installPermissionsFixed = false;
12362            if (!ps.isSharedUser()) {
12363                origPermissions = new PermissionsState(permissionsState);
12364                permissionsState.reset();
12365            } else {
12366                // We need to know only about runtime permission changes since the
12367                // calling code always writes the install permissions state but
12368                // the runtime ones are written only if changed. The only cases of
12369                // changed runtime permissions here are promotion of an install to
12370                // runtime and revocation of a runtime from a shared user.
12371                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12372                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12373                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12374                    runtimePermissionsRevoked = true;
12375                }
12376            }
12377        }
12378
12379        permissionsState.setGlobalGids(mGlobalGids);
12380
12381        final int N = pkg.requestedPermissions.size();
12382        for (int i=0; i<N; i++) {
12383            final String name = pkg.requestedPermissions.get(i);
12384            final BasePermission bp = mSettings.mPermissions.get(name);
12385            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12386                    >= Build.VERSION_CODES.M;
12387
12388            if (DEBUG_INSTALL) {
12389                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12390            }
12391
12392            if (bp == null || bp.packageSetting == null) {
12393                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12394                    if (DEBUG_PERMISSIONS) {
12395                        Slog.i(TAG, "Unknown permission " + name
12396                                + " in package " + pkg.packageName);
12397                    }
12398                }
12399                continue;
12400            }
12401
12402
12403            // Limit ephemeral apps to ephemeral allowed permissions.
12404            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12405                if (DEBUG_PERMISSIONS) {
12406                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12407                            + pkg.packageName);
12408                }
12409                continue;
12410            }
12411
12412            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12413                if (DEBUG_PERMISSIONS) {
12414                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12415                            + pkg.packageName);
12416                }
12417                continue;
12418            }
12419
12420            final String perm = bp.name;
12421            boolean allowedSig = false;
12422            int grant = GRANT_DENIED;
12423
12424            // Keep track of app op permissions.
12425            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12426                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12427                if (pkgs == null) {
12428                    pkgs = new ArraySet<>();
12429                    mAppOpPermissionPackages.put(bp.name, pkgs);
12430                }
12431                pkgs.add(pkg.packageName);
12432            }
12433
12434            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12435            switch (level) {
12436                case PermissionInfo.PROTECTION_NORMAL: {
12437                    // For all apps normal permissions are install time ones.
12438                    grant = GRANT_INSTALL;
12439                } break;
12440
12441                case PermissionInfo.PROTECTION_DANGEROUS: {
12442                    // If a permission review is required for legacy apps we represent
12443                    // their permissions as always granted runtime ones since we need
12444                    // to keep the review required permission flag per user while an
12445                    // install permission's state is shared across all users.
12446                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12447                        // For legacy apps dangerous permissions are install time ones.
12448                        grant = GRANT_INSTALL;
12449                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12450                        // For legacy apps that became modern, install becomes runtime.
12451                        grant = GRANT_UPGRADE;
12452                    } else if (mPromoteSystemApps
12453                            && isSystemApp(ps)
12454                            && mExistingSystemPackages.contains(ps.name)) {
12455                        // For legacy system apps, install becomes runtime.
12456                        // We cannot check hasInstallPermission() for system apps since those
12457                        // permissions were granted implicitly and not persisted pre-M.
12458                        grant = GRANT_UPGRADE;
12459                    } else {
12460                        // For modern apps keep runtime permissions unchanged.
12461                        grant = GRANT_RUNTIME;
12462                    }
12463                } break;
12464
12465                case PermissionInfo.PROTECTION_SIGNATURE: {
12466                    // For all apps signature permissions are install time ones.
12467                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12468                    if (allowedSig) {
12469                        grant = GRANT_INSTALL;
12470                    }
12471                } break;
12472            }
12473
12474            if (DEBUG_PERMISSIONS) {
12475                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12476            }
12477
12478            if (grant != GRANT_DENIED) {
12479                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12480                    // If this is an existing, non-system package, then
12481                    // we can't add any new permissions to it.
12482                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12483                        // Except...  if this is a permission that was added
12484                        // to the platform (note: need to only do this when
12485                        // updating the platform).
12486                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12487                            grant = GRANT_DENIED;
12488                        }
12489                    }
12490                }
12491
12492                switch (grant) {
12493                    case GRANT_INSTALL: {
12494                        // Revoke this as runtime permission to handle the case of
12495                        // a runtime permission being downgraded to an install one.
12496                        // Also in permission review mode we keep dangerous permissions
12497                        // for legacy apps
12498                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12499                            if (origPermissions.getRuntimePermissionState(
12500                                    bp.name, userId) != null) {
12501                                // Revoke the runtime permission and clear the flags.
12502                                origPermissions.revokeRuntimePermission(bp, userId);
12503                                origPermissions.updatePermissionFlags(bp, userId,
12504                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12505                                // If we revoked a permission permission, we have to write.
12506                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12507                                        changedRuntimePermissionUserIds, userId);
12508                            }
12509                        }
12510                        // Grant an install permission.
12511                        if (permissionsState.grantInstallPermission(bp) !=
12512                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12513                            changedInstallPermission = true;
12514                        }
12515                    } break;
12516
12517                    case GRANT_RUNTIME: {
12518                        // Grant previously granted runtime permissions.
12519                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12520                            PermissionState permissionState = origPermissions
12521                                    .getRuntimePermissionState(bp.name, userId);
12522                            int flags = permissionState != null
12523                                    ? permissionState.getFlags() : 0;
12524                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12525                                // Don't propagate the permission in a permission review mode if
12526                                // the former was revoked, i.e. marked to not propagate on upgrade.
12527                                // Note that in a permission review mode install permissions are
12528                                // represented as constantly granted runtime ones since we need to
12529                                // keep a per user state associated with the permission. Also the
12530                                // revoke on upgrade flag is no longer applicable and is reset.
12531                                final boolean revokeOnUpgrade = (flags & PackageManager
12532                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12533                                if (revokeOnUpgrade) {
12534                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12535                                    // Since we changed the flags, we have to write.
12536                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12537                                            changedRuntimePermissionUserIds, userId);
12538                                }
12539                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12540                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12541                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12542                                        // If we cannot put the permission as it was,
12543                                        // we have to write.
12544                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12545                                                changedRuntimePermissionUserIds, userId);
12546                                    }
12547                                }
12548
12549                                // If the app supports runtime permissions no need for a review.
12550                                if (mPermissionReviewRequired
12551                                        && appSupportsRuntimePermissions
12552                                        && (flags & PackageManager
12553                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12554                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12555                                    // Since we changed the flags, we have to write.
12556                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12557                                            changedRuntimePermissionUserIds, userId);
12558                                }
12559                            } else if (mPermissionReviewRequired
12560                                    && !appSupportsRuntimePermissions) {
12561                                // For legacy apps that need a permission review, every new
12562                                // runtime permission is granted but it is pending a review.
12563                                // We also need to review only platform defined runtime
12564                                // permissions as these are the only ones the platform knows
12565                                // how to disable the API to simulate revocation as legacy
12566                                // apps don't expect to run with revoked permissions.
12567                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12568                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12569                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12570                                        // We changed the flags, hence have to write.
12571                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12572                                                changedRuntimePermissionUserIds, userId);
12573                                    }
12574                                }
12575                                if (permissionsState.grantRuntimePermission(bp, userId)
12576                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12577                                    // We changed the permission, hence have to write.
12578                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12579                                            changedRuntimePermissionUserIds, userId);
12580                                }
12581                            }
12582                            // Propagate the permission flags.
12583                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12584                        }
12585                    } break;
12586
12587                    case GRANT_UPGRADE: {
12588                        // Grant runtime permissions for a previously held install permission.
12589                        PermissionState permissionState = origPermissions
12590                                .getInstallPermissionState(bp.name);
12591                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12592
12593                        if (origPermissions.revokeInstallPermission(bp)
12594                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12595                            // We will be transferring the permission flags, so clear them.
12596                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12597                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12598                            changedInstallPermission = true;
12599                        }
12600
12601                        // If the permission is not to be promoted to runtime we ignore it and
12602                        // also its other flags as they are not applicable to install permissions.
12603                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12604                            for (int userId : currentUserIds) {
12605                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12606                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12607                                    // Transfer the permission flags.
12608                                    permissionsState.updatePermissionFlags(bp, userId,
12609                                            flags, flags);
12610                                    // If we granted the permission, we have to write.
12611                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12612                                            changedRuntimePermissionUserIds, userId);
12613                                }
12614                            }
12615                        }
12616                    } break;
12617
12618                    default: {
12619                        if (packageOfInterest == null
12620                                || packageOfInterest.equals(pkg.packageName)) {
12621                            if (DEBUG_PERMISSIONS) {
12622                                Slog.i(TAG, "Not granting permission " + perm
12623                                        + " to package " + pkg.packageName
12624                                        + " because it was previously installed without");
12625                            }
12626                        }
12627                    } break;
12628                }
12629            } else {
12630                if (permissionsState.revokeInstallPermission(bp) !=
12631                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12632                    // Also drop the permission flags.
12633                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12634                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12635                    changedInstallPermission = true;
12636                    Slog.i(TAG, "Un-granting permission " + perm
12637                            + " from package " + pkg.packageName
12638                            + " (protectionLevel=" + bp.protectionLevel
12639                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12640                            + ")");
12641                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12642                    // Don't print warning for app op permissions, since it is fine for them
12643                    // not to be granted, there is a UI for the user to decide.
12644                    if (DEBUG_PERMISSIONS
12645                            && (packageOfInterest == null
12646                                    || packageOfInterest.equals(pkg.packageName))) {
12647                        Slog.i(TAG, "Not granting permission " + perm
12648                                + " to package " + pkg.packageName
12649                                + " (protectionLevel=" + bp.protectionLevel
12650                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12651                                + ")");
12652                    }
12653                }
12654            }
12655        }
12656
12657        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12658                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12659            // This is the first that we have heard about this package, so the
12660            // permissions we have now selected are fixed until explicitly
12661            // changed.
12662            ps.installPermissionsFixed = true;
12663        }
12664
12665        // Persist the runtime permissions state for users with changes. If permissions
12666        // were revoked because no app in the shared user declares them we have to
12667        // write synchronously to avoid losing runtime permissions state.
12668        for (int userId : changedRuntimePermissionUserIds) {
12669            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12670        }
12671    }
12672
12673    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12674        boolean allowed = false;
12675        final int NP = PackageParser.NEW_PERMISSIONS.length;
12676        for (int ip=0; ip<NP; ip++) {
12677            final PackageParser.NewPermissionInfo npi
12678                    = PackageParser.NEW_PERMISSIONS[ip];
12679            if (npi.name.equals(perm)
12680                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12681                allowed = true;
12682                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12683                        + pkg.packageName);
12684                break;
12685            }
12686        }
12687        return allowed;
12688    }
12689
12690    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12691            BasePermission bp, PermissionsState origPermissions) {
12692        boolean privilegedPermission = (bp.protectionLevel
12693                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12694        boolean privappPermissionsDisable =
12695                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12696        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12697        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12698        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12699                && !platformPackage && platformPermission) {
12700            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12701                    .getPrivAppPermissions(pkg.packageName);
12702            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12703            if (!whitelisted) {
12704                Slog.w(TAG, "Privileged permission " + perm + " for package "
12705                        + pkg.packageName + " - not in privapp-permissions whitelist");
12706                // Only report violations for apps on system image
12707                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12708                    if (mPrivappPermissionsViolations == null) {
12709                        mPrivappPermissionsViolations = new ArraySet<>();
12710                    }
12711                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12712                }
12713                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12714                    return false;
12715                }
12716            }
12717        }
12718        boolean allowed = (compareSignatures(
12719                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12720                        == PackageManager.SIGNATURE_MATCH)
12721                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12722                        == PackageManager.SIGNATURE_MATCH);
12723        if (!allowed && privilegedPermission) {
12724            if (isSystemApp(pkg)) {
12725                // For updated system applications, a system permission
12726                // is granted only if it had been defined by the original application.
12727                if (pkg.isUpdatedSystemApp()) {
12728                    final PackageSetting sysPs = mSettings
12729                            .getDisabledSystemPkgLPr(pkg.packageName);
12730                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12731                        // If the original was granted this permission, we take
12732                        // that grant decision as read and propagate it to the
12733                        // update.
12734                        if (sysPs.isPrivileged()) {
12735                            allowed = true;
12736                        }
12737                    } else {
12738                        // The system apk may have been updated with an older
12739                        // version of the one on the data partition, but which
12740                        // granted a new system permission that it didn't have
12741                        // before.  In this case we do want to allow the app to
12742                        // now get the new permission if the ancestral apk is
12743                        // privileged to get it.
12744                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12745                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12746                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12747                                    allowed = true;
12748                                    break;
12749                                }
12750                            }
12751                        }
12752                        // Also if a privileged parent package on the system image or any of
12753                        // its children requested a privileged permission, the updated child
12754                        // packages can also get the permission.
12755                        if (pkg.parentPackage != null) {
12756                            final PackageSetting disabledSysParentPs = mSettings
12757                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12758                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12759                                    && disabledSysParentPs.isPrivileged()) {
12760                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12761                                    allowed = true;
12762                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12763                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12764                                    for (int i = 0; i < count; i++) {
12765                                        PackageParser.Package disabledSysChildPkg =
12766                                                disabledSysParentPs.pkg.childPackages.get(i);
12767                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12768                                                perm)) {
12769                                            allowed = true;
12770                                            break;
12771                                        }
12772                                    }
12773                                }
12774                            }
12775                        }
12776                    }
12777                } else {
12778                    allowed = isPrivilegedApp(pkg);
12779                }
12780            }
12781        }
12782        if (!allowed) {
12783            if (!allowed && (bp.protectionLevel
12784                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12785                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12786                // If this was a previously normal/dangerous permission that got moved
12787                // to a system permission as part of the runtime permission redesign, then
12788                // we still want to blindly grant it to old apps.
12789                allowed = true;
12790            }
12791            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12792                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12793                // If this permission is to be granted to the system installer and
12794                // this app is an installer, then it gets the permission.
12795                allowed = true;
12796            }
12797            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12798                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12799                // If this permission is to be granted to the system verifier and
12800                // this app is a verifier, then it gets the permission.
12801                allowed = true;
12802            }
12803            if (!allowed && (bp.protectionLevel
12804                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12805                    && isSystemApp(pkg)) {
12806                // Any pre-installed system app is allowed to get this permission.
12807                allowed = true;
12808            }
12809            if (!allowed && (bp.protectionLevel
12810                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12811                // For development permissions, a development permission
12812                // is granted only if it was already granted.
12813                allowed = origPermissions.hasInstallPermission(perm);
12814            }
12815            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12816                    && pkg.packageName.equals(mSetupWizardPackage)) {
12817                // If this permission is to be granted to the system setup wizard and
12818                // this app is a setup wizard, then it gets the permission.
12819                allowed = true;
12820            }
12821        }
12822        return allowed;
12823    }
12824
12825    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12826        final int permCount = pkg.requestedPermissions.size();
12827        for (int j = 0; j < permCount; j++) {
12828            String requestedPermission = pkg.requestedPermissions.get(j);
12829            if (permission.equals(requestedPermission)) {
12830                return true;
12831            }
12832        }
12833        return false;
12834    }
12835
12836    final class ActivityIntentResolver
12837            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12838        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12839                boolean defaultOnly, int userId) {
12840            if (!sUserManager.exists(userId)) return null;
12841            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12842            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12843        }
12844
12845        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12846                int userId) {
12847            if (!sUserManager.exists(userId)) return null;
12848            mFlags = flags;
12849            return super.queryIntent(intent, resolvedType,
12850                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12851                    userId);
12852        }
12853
12854        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12855                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12856            if (!sUserManager.exists(userId)) return null;
12857            if (packageActivities == null) {
12858                return null;
12859            }
12860            mFlags = flags;
12861            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12862            final int N = packageActivities.size();
12863            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12864                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12865
12866            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12867            for (int i = 0; i < N; ++i) {
12868                intentFilters = packageActivities.get(i).intents;
12869                if (intentFilters != null && intentFilters.size() > 0) {
12870                    PackageParser.ActivityIntentInfo[] array =
12871                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12872                    intentFilters.toArray(array);
12873                    listCut.add(array);
12874                }
12875            }
12876            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12877        }
12878
12879        /**
12880         * Finds a privileged activity that matches the specified activity names.
12881         */
12882        private PackageParser.Activity findMatchingActivity(
12883                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12884            for (PackageParser.Activity sysActivity : activityList) {
12885                if (sysActivity.info.name.equals(activityInfo.name)) {
12886                    return sysActivity;
12887                }
12888                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12889                    return sysActivity;
12890                }
12891                if (sysActivity.info.targetActivity != null) {
12892                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12893                        return sysActivity;
12894                    }
12895                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12896                        return sysActivity;
12897                    }
12898                }
12899            }
12900            return null;
12901        }
12902
12903        public class IterGenerator<E> {
12904            public Iterator<E> generate(ActivityIntentInfo info) {
12905                return null;
12906            }
12907        }
12908
12909        public class ActionIterGenerator extends IterGenerator<String> {
12910            @Override
12911            public Iterator<String> generate(ActivityIntentInfo info) {
12912                return info.actionsIterator();
12913            }
12914        }
12915
12916        public class CategoriesIterGenerator extends IterGenerator<String> {
12917            @Override
12918            public Iterator<String> generate(ActivityIntentInfo info) {
12919                return info.categoriesIterator();
12920            }
12921        }
12922
12923        public class SchemesIterGenerator extends IterGenerator<String> {
12924            @Override
12925            public Iterator<String> generate(ActivityIntentInfo info) {
12926                return info.schemesIterator();
12927            }
12928        }
12929
12930        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12931            @Override
12932            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12933                return info.authoritiesIterator();
12934            }
12935        }
12936
12937        /**
12938         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12939         * MODIFIED. Do not pass in a list that should not be changed.
12940         */
12941        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12942                IterGenerator<T> generator, Iterator<T> searchIterator) {
12943            // loop through the set of actions; every one must be found in the intent filter
12944            while (searchIterator.hasNext()) {
12945                // we must have at least one filter in the list to consider a match
12946                if (intentList.size() == 0) {
12947                    break;
12948                }
12949
12950                final T searchAction = searchIterator.next();
12951
12952                // loop through the set of intent filters
12953                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12954                while (intentIter.hasNext()) {
12955                    final ActivityIntentInfo intentInfo = intentIter.next();
12956                    boolean selectionFound = false;
12957
12958                    // loop through the intent filter's selection criteria; at least one
12959                    // of them must match the searched criteria
12960                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12961                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12962                        final T intentSelection = intentSelectionIter.next();
12963                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12964                            selectionFound = true;
12965                            break;
12966                        }
12967                    }
12968
12969                    // the selection criteria wasn't found in this filter's set; this filter
12970                    // is not a potential match
12971                    if (!selectionFound) {
12972                        intentIter.remove();
12973                    }
12974                }
12975            }
12976        }
12977
12978        private boolean isProtectedAction(ActivityIntentInfo filter) {
12979            final Iterator<String> actionsIter = filter.actionsIterator();
12980            while (actionsIter != null && actionsIter.hasNext()) {
12981                final String filterAction = actionsIter.next();
12982                if (PROTECTED_ACTIONS.contains(filterAction)) {
12983                    return true;
12984                }
12985            }
12986            return false;
12987        }
12988
12989        /**
12990         * Adjusts the priority of the given intent filter according to policy.
12991         * <p>
12992         * <ul>
12993         * <li>The priority for non privileged applications is capped to '0'</li>
12994         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12995         * <li>The priority for unbundled updates to privileged applications is capped to the
12996         *      priority defined on the system partition</li>
12997         * </ul>
12998         * <p>
12999         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13000         * allowed to obtain any priority on any action.
13001         */
13002        private void adjustPriority(
13003                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13004            // nothing to do; priority is fine as-is
13005            if (intent.getPriority() <= 0) {
13006                return;
13007            }
13008
13009            final ActivityInfo activityInfo = intent.activity.info;
13010            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13011
13012            final boolean privilegedApp =
13013                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13014            if (!privilegedApp) {
13015                // non-privileged applications can never define a priority >0
13016                if (DEBUG_FILTERS) {
13017                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13018                            + " package: " + applicationInfo.packageName
13019                            + " activity: " + intent.activity.className
13020                            + " origPrio: " + intent.getPriority());
13021                }
13022                intent.setPriority(0);
13023                return;
13024            }
13025
13026            if (systemActivities == null) {
13027                // the system package is not disabled; we're parsing the system partition
13028                if (isProtectedAction(intent)) {
13029                    if (mDeferProtectedFilters) {
13030                        // We can't deal with these just yet. No component should ever obtain a
13031                        // >0 priority for a protected actions, with ONE exception -- the setup
13032                        // wizard. The setup wizard, however, cannot be known until we're able to
13033                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13034                        // until all intent filters have been processed. Chicken, meet egg.
13035                        // Let the filter temporarily have a high priority and rectify the
13036                        // priorities after all system packages have been scanned.
13037                        mProtectedFilters.add(intent);
13038                        if (DEBUG_FILTERS) {
13039                            Slog.i(TAG, "Protected action; save for later;"
13040                                    + " package: " + applicationInfo.packageName
13041                                    + " activity: " + intent.activity.className
13042                                    + " origPrio: " + intent.getPriority());
13043                        }
13044                        return;
13045                    } else {
13046                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13047                            Slog.i(TAG, "No setup wizard;"
13048                                + " All protected intents capped to priority 0");
13049                        }
13050                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13051                            if (DEBUG_FILTERS) {
13052                                Slog.i(TAG, "Found setup wizard;"
13053                                    + " allow priority " + intent.getPriority() + ";"
13054                                    + " package: " + intent.activity.info.packageName
13055                                    + " activity: " + intent.activity.className
13056                                    + " priority: " + intent.getPriority());
13057                            }
13058                            // setup wizard gets whatever it wants
13059                            return;
13060                        }
13061                        if (DEBUG_FILTERS) {
13062                            Slog.i(TAG, "Protected action; cap priority to 0;"
13063                                    + " package: " + intent.activity.info.packageName
13064                                    + " activity: " + intent.activity.className
13065                                    + " origPrio: " + intent.getPriority());
13066                        }
13067                        intent.setPriority(0);
13068                        return;
13069                    }
13070                }
13071                // privileged apps on the system image get whatever priority they request
13072                return;
13073            }
13074
13075            // privileged app unbundled update ... try to find the same activity
13076            final PackageParser.Activity foundActivity =
13077                    findMatchingActivity(systemActivities, activityInfo);
13078            if (foundActivity == null) {
13079                // this is a new activity; it cannot obtain >0 priority
13080                if (DEBUG_FILTERS) {
13081                    Slog.i(TAG, "New activity; cap priority to 0;"
13082                            + " package: " + applicationInfo.packageName
13083                            + " activity: " + intent.activity.className
13084                            + " origPrio: " + intent.getPriority());
13085                }
13086                intent.setPriority(0);
13087                return;
13088            }
13089
13090            // found activity, now check for filter equivalence
13091
13092            // a shallow copy is enough; we modify the list, not its contents
13093            final List<ActivityIntentInfo> intentListCopy =
13094                    new ArrayList<>(foundActivity.intents);
13095            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13096
13097            // find matching action subsets
13098            final Iterator<String> actionsIterator = intent.actionsIterator();
13099            if (actionsIterator != null) {
13100                getIntentListSubset(
13101                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13102                if (intentListCopy.size() == 0) {
13103                    // no more intents to match; we're not equivalent
13104                    if (DEBUG_FILTERS) {
13105                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13106                                + " package: " + applicationInfo.packageName
13107                                + " activity: " + intent.activity.className
13108                                + " origPrio: " + intent.getPriority());
13109                    }
13110                    intent.setPriority(0);
13111                    return;
13112                }
13113            }
13114
13115            // find matching category subsets
13116            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13117            if (categoriesIterator != null) {
13118                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13119                        categoriesIterator);
13120                if (intentListCopy.size() == 0) {
13121                    // no more intents to match; we're not equivalent
13122                    if (DEBUG_FILTERS) {
13123                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13124                                + " package: " + applicationInfo.packageName
13125                                + " activity: " + intent.activity.className
13126                                + " origPrio: " + intent.getPriority());
13127                    }
13128                    intent.setPriority(0);
13129                    return;
13130                }
13131            }
13132
13133            // find matching schemes subsets
13134            final Iterator<String> schemesIterator = intent.schemesIterator();
13135            if (schemesIterator != null) {
13136                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13137                        schemesIterator);
13138                if (intentListCopy.size() == 0) {
13139                    // no more intents to match; we're not equivalent
13140                    if (DEBUG_FILTERS) {
13141                        Slog.i(TAG, "Mismatched scheme; 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
13151            // find matching authorities subsets
13152            final Iterator<IntentFilter.AuthorityEntry>
13153                    authoritiesIterator = intent.authoritiesIterator();
13154            if (authoritiesIterator != null) {
13155                getIntentListSubset(intentListCopy,
13156                        new AuthoritiesIterGenerator(),
13157                        authoritiesIterator);
13158                if (intentListCopy.size() == 0) {
13159                    // no more intents to match; we're not equivalent
13160                    if (DEBUG_FILTERS) {
13161                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13162                                + " package: " + applicationInfo.packageName
13163                                + " activity: " + intent.activity.className
13164                                + " origPrio: " + intent.getPriority());
13165                    }
13166                    intent.setPriority(0);
13167                    return;
13168                }
13169            }
13170
13171            // we found matching filter(s); app gets the max priority of all intents
13172            int cappedPriority = 0;
13173            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13174                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13175            }
13176            if (intent.getPriority() > cappedPriority) {
13177                if (DEBUG_FILTERS) {
13178                    Slog.i(TAG, "Found matching filter(s);"
13179                            + " cap priority to " + cappedPriority + ";"
13180                            + " package: " + applicationInfo.packageName
13181                            + " activity: " + intent.activity.className
13182                            + " origPrio: " + intent.getPriority());
13183                }
13184                intent.setPriority(cappedPriority);
13185                return;
13186            }
13187            // all this for nothing; the requested priority was <= what was on the system
13188        }
13189
13190        public final void addActivity(PackageParser.Activity a, String type) {
13191            mActivities.put(a.getComponentName(), a);
13192            if (DEBUG_SHOW_INFO)
13193                Log.v(
13194                TAG, "  " + type + " " +
13195                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13196            if (DEBUG_SHOW_INFO)
13197                Log.v(TAG, "    Class=" + a.info.name);
13198            final int NI = a.intents.size();
13199            for (int j=0; j<NI; j++) {
13200                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13201                if ("activity".equals(type)) {
13202                    final PackageSetting ps =
13203                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13204                    final List<PackageParser.Activity> systemActivities =
13205                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13206                    adjustPriority(systemActivities, intent);
13207                }
13208                if (DEBUG_SHOW_INFO) {
13209                    Log.v(TAG, "    IntentFilter:");
13210                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13211                }
13212                if (!intent.debugCheck()) {
13213                    Log.w(TAG, "==> For Activity " + a.info.name);
13214                }
13215                addFilter(intent);
13216            }
13217        }
13218
13219        public final void removeActivity(PackageParser.Activity a, String type) {
13220            mActivities.remove(a.getComponentName());
13221            if (DEBUG_SHOW_INFO) {
13222                Log.v(TAG, "  " + type + " "
13223                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13224                                : a.info.name) + ":");
13225                Log.v(TAG, "    Class=" + a.info.name);
13226            }
13227            final int NI = a.intents.size();
13228            for (int j=0; j<NI; j++) {
13229                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13230                if (DEBUG_SHOW_INFO) {
13231                    Log.v(TAG, "    IntentFilter:");
13232                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13233                }
13234                removeFilter(intent);
13235            }
13236        }
13237
13238        @Override
13239        protected boolean allowFilterResult(
13240                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13241            ActivityInfo filterAi = filter.activity.info;
13242            for (int i=dest.size()-1; i>=0; i--) {
13243                ActivityInfo destAi = dest.get(i).activityInfo;
13244                if (destAi.name == filterAi.name
13245                        && destAi.packageName == filterAi.packageName) {
13246                    return false;
13247                }
13248            }
13249            return true;
13250        }
13251
13252        @Override
13253        protected ActivityIntentInfo[] newArray(int size) {
13254            return new ActivityIntentInfo[size];
13255        }
13256
13257        @Override
13258        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13259            if (!sUserManager.exists(userId)) return true;
13260            PackageParser.Package p = filter.activity.owner;
13261            if (p != null) {
13262                PackageSetting ps = (PackageSetting)p.mExtras;
13263                if (ps != null) {
13264                    // System apps are never considered stopped for purposes of
13265                    // filtering, because there may be no way for the user to
13266                    // actually re-launch them.
13267                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13268                            && ps.getStopped(userId);
13269                }
13270            }
13271            return false;
13272        }
13273
13274        @Override
13275        protected boolean isPackageForFilter(String packageName,
13276                PackageParser.ActivityIntentInfo info) {
13277            return packageName.equals(info.activity.owner.packageName);
13278        }
13279
13280        @Override
13281        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13282                int match, int userId) {
13283            if (!sUserManager.exists(userId)) return null;
13284            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13285                return null;
13286            }
13287            final PackageParser.Activity activity = info.activity;
13288            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13289            if (ps == null) {
13290                return null;
13291            }
13292            final PackageUserState userState = ps.readUserState(userId);
13293            ActivityInfo ai =
13294                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13295            if (ai == null) {
13296                return null;
13297            }
13298            final boolean matchExplicitlyVisibleOnly =
13299                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13300            final boolean matchVisibleToInstantApp =
13301                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13302            final boolean componentVisible =
13303                    matchVisibleToInstantApp
13304                    && info.isVisibleToInstantApp()
13305                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13306            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13307            // throw out filters that aren't visible to ephemeral apps
13308            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13309                return null;
13310            }
13311            // throw out instant app filters if we're not explicitly requesting them
13312            if (!matchInstantApp && userState.instantApp) {
13313                return null;
13314            }
13315            // throw out instant app filters if updates are available; will trigger
13316            // instant app resolution
13317            if (userState.instantApp && ps.isUpdateAvailable()) {
13318                return null;
13319            }
13320            final ResolveInfo res = new ResolveInfo();
13321            res.activityInfo = ai;
13322            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13323                res.filter = info;
13324            }
13325            if (info != null) {
13326                res.handleAllWebDataURI = info.handleAllWebDataURI();
13327            }
13328            res.priority = info.getPriority();
13329            res.preferredOrder = activity.owner.mPreferredOrder;
13330            //System.out.println("Result: " + res.activityInfo.className +
13331            //                   " = " + res.priority);
13332            res.match = match;
13333            res.isDefault = info.hasDefault;
13334            res.labelRes = info.labelRes;
13335            res.nonLocalizedLabel = info.nonLocalizedLabel;
13336            if (userNeedsBadging(userId)) {
13337                res.noResourceId = true;
13338            } else {
13339                res.icon = info.icon;
13340            }
13341            res.iconResourceId = info.icon;
13342            res.system = res.activityInfo.applicationInfo.isSystemApp();
13343            res.isInstantAppAvailable = userState.instantApp;
13344            return res;
13345        }
13346
13347        @Override
13348        protected void sortResults(List<ResolveInfo> results) {
13349            Collections.sort(results, mResolvePrioritySorter);
13350        }
13351
13352        @Override
13353        protected void dumpFilter(PrintWriter out, String prefix,
13354                PackageParser.ActivityIntentInfo filter) {
13355            out.print(prefix); out.print(
13356                    Integer.toHexString(System.identityHashCode(filter.activity)));
13357                    out.print(' ');
13358                    filter.activity.printComponentShortName(out);
13359                    out.print(" filter ");
13360                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13361        }
13362
13363        @Override
13364        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13365            return filter.activity;
13366        }
13367
13368        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13369            PackageParser.Activity activity = (PackageParser.Activity)label;
13370            out.print(prefix); out.print(
13371                    Integer.toHexString(System.identityHashCode(activity)));
13372                    out.print(' ');
13373                    activity.printComponentShortName(out);
13374            if (count > 1) {
13375                out.print(" ("); out.print(count); out.print(" filters)");
13376            }
13377            out.println();
13378        }
13379
13380        // Keys are String (activity class name), values are Activity.
13381        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13382                = new ArrayMap<ComponentName, PackageParser.Activity>();
13383        private int mFlags;
13384    }
13385
13386    private final class ServiceIntentResolver
13387            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13388        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13389                boolean defaultOnly, int userId) {
13390            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13391            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13392        }
13393
13394        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13395                int userId) {
13396            if (!sUserManager.exists(userId)) return null;
13397            mFlags = flags;
13398            return super.queryIntent(intent, resolvedType,
13399                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13400                    userId);
13401        }
13402
13403        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13404                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13405            if (!sUserManager.exists(userId)) return null;
13406            if (packageServices == null) {
13407                return null;
13408            }
13409            mFlags = flags;
13410            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13411            final int N = packageServices.size();
13412            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13413                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13414
13415            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13416            for (int i = 0; i < N; ++i) {
13417                intentFilters = packageServices.get(i).intents;
13418                if (intentFilters != null && intentFilters.size() > 0) {
13419                    PackageParser.ServiceIntentInfo[] array =
13420                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13421                    intentFilters.toArray(array);
13422                    listCut.add(array);
13423                }
13424            }
13425            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13426        }
13427
13428        public final void addService(PackageParser.Service s) {
13429            mServices.put(s.getComponentName(), s);
13430            if (DEBUG_SHOW_INFO) {
13431                Log.v(TAG, "  "
13432                        + (s.info.nonLocalizedLabel != null
13433                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13434                Log.v(TAG, "    Class=" + s.info.name);
13435            }
13436            final int NI = s.intents.size();
13437            int j;
13438            for (j=0; j<NI; j++) {
13439                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13440                if (DEBUG_SHOW_INFO) {
13441                    Log.v(TAG, "    IntentFilter:");
13442                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13443                }
13444                if (!intent.debugCheck()) {
13445                    Log.w(TAG, "==> For Service " + s.info.name);
13446                }
13447                addFilter(intent);
13448            }
13449        }
13450
13451        public final void removeService(PackageParser.Service s) {
13452            mServices.remove(s.getComponentName());
13453            if (DEBUG_SHOW_INFO) {
13454                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13455                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13456                Log.v(TAG, "    Class=" + s.info.name);
13457            }
13458            final int NI = s.intents.size();
13459            int j;
13460            for (j=0; j<NI; j++) {
13461                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13462                if (DEBUG_SHOW_INFO) {
13463                    Log.v(TAG, "    IntentFilter:");
13464                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13465                }
13466                removeFilter(intent);
13467            }
13468        }
13469
13470        @Override
13471        protected boolean allowFilterResult(
13472                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13473            ServiceInfo filterSi = filter.service.info;
13474            for (int i=dest.size()-1; i>=0; i--) {
13475                ServiceInfo destAi = dest.get(i).serviceInfo;
13476                if (destAi.name == filterSi.name
13477                        && destAi.packageName == filterSi.packageName) {
13478                    return false;
13479                }
13480            }
13481            return true;
13482        }
13483
13484        @Override
13485        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13486            return new PackageParser.ServiceIntentInfo[size];
13487        }
13488
13489        @Override
13490        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13491            if (!sUserManager.exists(userId)) return true;
13492            PackageParser.Package p = filter.service.owner;
13493            if (p != null) {
13494                PackageSetting ps = (PackageSetting)p.mExtras;
13495                if (ps != null) {
13496                    // System apps are never considered stopped for purposes of
13497                    // filtering, because there may be no way for the user to
13498                    // actually re-launch them.
13499                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13500                            && ps.getStopped(userId);
13501                }
13502            }
13503            return false;
13504        }
13505
13506        @Override
13507        protected boolean isPackageForFilter(String packageName,
13508                PackageParser.ServiceIntentInfo info) {
13509            return packageName.equals(info.service.owner.packageName);
13510        }
13511
13512        @Override
13513        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13514                int match, int userId) {
13515            if (!sUserManager.exists(userId)) return null;
13516            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13517            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13518                return null;
13519            }
13520            final PackageParser.Service service = info.service;
13521            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13522            if (ps == null) {
13523                return null;
13524            }
13525            final PackageUserState userState = ps.readUserState(userId);
13526            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13527                    userState, userId);
13528            if (si == null) {
13529                return null;
13530            }
13531            final boolean matchVisibleToInstantApp =
13532                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13533            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13534            // throw out filters that aren't visible to ephemeral apps
13535            if (matchVisibleToInstantApp
13536                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13537                return null;
13538            }
13539            // throw out ephemeral filters if we're not explicitly requesting them
13540            if (!isInstantApp && userState.instantApp) {
13541                return null;
13542            }
13543            // throw out instant app filters if updates are available; will trigger
13544            // instant app resolution
13545            if (userState.instantApp && ps.isUpdateAvailable()) {
13546                return null;
13547            }
13548            final ResolveInfo res = new ResolveInfo();
13549            res.serviceInfo = si;
13550            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13551                res.filter = filter;
13552            }
13553            res.priority = info.getPriority();
13554            res.preferredOrder = service.owner.mPreferredOrder;
13555            res.match = match;
13556            res.isDefault = info.hasDefault;
13557            res.labelRes = info.labelRes;
13558            res.nonLocalizedLabel = info.nonLocalizedLabel;
13559            res.icon = info.icon;
13560            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13561            return res;
13562        }
13563
13564        @Override
13565        protected void sortResults(List<ResolveInfo> results) {
13566            Collections.sort(results, mResolvePrioritySorter);
13567        }
13568
13569        @Override
13570        protected void dumpFilter(PrintWriter out, String prefix,
13571                PackageParser.ServiceIntentInfo filter) {
13572            out.print(prefix); out.print(
13573                    Integer.toHexString(System.identityHashCode(filter.service)));
13574                    out.print(' ');
13575                    filter.service.printComponentShortName(out);
13576                    out.print(" filter ");
13577                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13578        }
13579
13580        @Override
13581        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13582            return filter.service;
13583        }
13584
13585        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13586            PackageParser.Service service = (PackageParser.Service)label;
13587            out.print(prefix); out.print(
13588                    Integer.toHexString(System.identityHashCode(service)));
13589                    out.print(' ');
13590                    service.printComponentShortName(out);
13591            if (count > 1) {
13592                out.print(" ("); out.print(count); out.print(" filters)");
13593            }
13594            out.println();
13595        }
13596
13597//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13598//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13599//            final List<ResolveInfo> retList = Lists.newArrayList();
13600//            while (i.hasNext()) {
13601//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13602//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13603//                    retList.add(resolveInfo);
13604//                }
13605//            }
13606//            return retList;
13607//        }
13608
13609        // Keys are String (activity class name), values are Activity.
13610        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13611                = new ArrayMap<ComponentName, PackageParser.Service>();
13612        private int mFlags;
13613    }
13614
13615    private final class ProviderIntentResolver
13616            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13617        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13618                boolean defaultOnly, int userId) {
13619            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13620            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13621        }
13622
13623        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13624                int userId) {
13625            if (!sUserManager.exists(userId))
13626                return null;
13627            mFlags = flags;
13628            return super.queryIntent(intent, resolvedType,
13629                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13630                    userId);
13631        }
13632
13633        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13634                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13635            if (!sUserManager.exists(userId))
13636                return null;
13637            if (packageProviders == null) {
13638                return null;
13639            }
13640            mFlags = flags;
13641            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13642            final int N = packageProviders.size();
13643            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13644                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13645
13646            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13647            for (int i = 0; i < N; ++i) {
13648                intentFilters = packageProviders.get(i).intents;
13649                if (intentFilters != null && intentFilters.size() > 0) {
13650                    PackageParser.ProviderIntentInfo[] array =
13651                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13652                    intentFilters.toArray(array);
13653                    listCut.add(array);
13654                }
13655            }
13656            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13657        }
13658
13659        public final void addProvider(PackageParser.Provider p) {
13660            if (mProviders.containsKey(p.getComponentName())) {
13661                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13662                return;
13663            }
13664
13665            mProviders.put(p.getComponentName(), p);
13666            if (DEBUG_SHOW_INFO) {
13667                Log.v(TAG, "  "
13668                        + (p.info.nonLocalizedLabel != null
13669                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13670                Log.v(TAG, "    Class=" + p.info.name);
13671            }
13672            final int NI = p.intents.size();
13673            int j;
13674            for (j = 0; j < NI; j++) {
13675                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13676                if (DEBUG_SHOW_INFO) {
13677                    Log.v(TAG, "    IntentFilter:");
13678                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13679                }
13680                if (!intent.debugCheck()) {
13681                    Log.w(TAG, "==> For Provider " + p.info.name);
13682                }
13683                addFilter(intent);
13684            }
13685        }
13686
13687        public final void removeProvider(PackageParser.Provider p) {
13688            mProviders.remove(p.getComponentName());
13689            if (DEBUG_SHOW_INFO) {
13690                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13691                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13692                Log.v(TAG, "    Class=" + p.info.name);
13693            }
13694            final int NI = p.intents.size();
13695            int j;
13696            for (j = 0; j < NI; j++) {
13697                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13698                if (DEBUG_SHOW_INFO) {
13699                    Log.v(TAG, "    IntentFilter:");
13700                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13701                }
13702                removeFilter(intent);
13703            }
13704        }
13705
13706        @Override
13707        protected boolean allowFilterResult(
13708                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13709            ProviderInfo filterPi = filter.provider.info;
13710            for (int i = dest.size() - 1; i >= 0; i--) {
13711                ProviderInfo destPi = dest.get(i).providerInfo;
13712                if (destPi.name == filterPi.name
13713                        && destPi.packageName == filterPi.packageName) {
13714                    return false;
13715                }
13716            }
13717            return true;
13718        }
13719
13720        @Override
13721        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13722            return new PackageParser.ProviderIntentInfo[size];
13723        }
13724
13725        @Override
13726        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13727            if (!sUserManager.exists(userId))
13728                return true;
13729            PackageParser.Package p = filter.provider.owner;
13730            if (p != null) {
13731                PackageSetting ps = (PackageSetting) p.mExtras;
13732                if (ps != null) {
13733                    // System apps are never considered stopped for purposes of
13734                    // filtering, because there may be no way for the user to
13735                    // actually re-launch them.
13736                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13737                            && ps.getStopped(userId);
13738                }
13739            }
13740            return false;
13741        }
13742
13743        @Override
13744        protected boolean isPackageForFilter(String packageName,
13745                PackageParser.ProviderIntentInfo info) {
13746            return packageName.equals(info.provider.owner.packageName);
13747        }
13748
13749        @Override
13750        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13751                int match, int userId) {
13752            if (!sUserManager.exists(userId))
13753                return null;
13754            final PackageParser.ProviderIntentInfo info = filter;
13755            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13756                return null;
13757            }
13758            final PackageParser.Provider provider = info.provider;
13759            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13760            if (ps == null) {
13761                return null;
13762            }
13763            final PackageUserState userState = ps.readUserState(userId);
13764            final boolean matchVisibleToInstantApp =
13765                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13766            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13767            // throw out filters that aren't visible to instant applications
13768            if (matchVisibleToInstantApp
13769                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13770                return null;
13771            }
13772            // throw out instant application filters if we're not explicitly requesting them
13773            if (!isInstantApp && userState.instantApp) {
13774                return null;
13775            }
13776            // throw out instant application filters if updates are available; will trigger
13777            // instant application resolution
13778            if (userState.instantApp && ps.isUpdateAvailable()) {
13779                return null;
13780            }
13781            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13782                    userState, userId);
13783            if (pi == null) {
13784                return null;
13785            }
13786            final ResolveInfo res = new ResolveInfo();
13787            res.providerInfo = pi;
13788            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13789                res.filter = filter;
13790            }
13791            res.priority = info.getPriority();
13792            res.preferredOrder = provider.owner.mPreferredOrder;
13793            res.match = match;
13794            res.isDefault = info.hasDefault;
13795            res.labelRes = info.labelRes;
13796            res.nonLocalizedLabel = info.nonLocalizedLabel;
13797            res.icon = info.icon;
13798            res.system = res.providerInfo.applicationInfo.isSystemApp();
13799            return res;
13800        }
13801
13802        @Override
13803        protected void sortResults(List<ResolveInfo> results) {
13804            Collections.sort(results, mResolvePrioritySorter);
13805        }
13806
13807        @Override
13808        protected void dumpFilter(PrintWriter out, String prefix,
13809                PackageParser.ProviderIntentInfo filter) {
13810            out.print(prefix);
13811            out.print(
13812                    Integer.toHexString(System.identityHashCode(filter.provider)));
13813            out.print(' ');
13814            filter.provider.printComponentShortName(out);
13815            out.print(" filter ");
13816            out.println(Integer.toHexString(System.identityHashCode(filter)));
13817        }
13818
13819        @Override
13820        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13821            return filter.provider;
13822        }
13823
13824        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13825            PackageParser.Provider provider = (PackageParser.Provider)label;
13826            out.print(prefix); out.print(
13827                    Integer.toHexString(System.identityHashCode(provider)));
13828                    out.print(' ');
13829                    provider.printComponentShortName(out);
13830            if (count > 1) {
13831                out.print(" ("); out.print(count); out.print(" filters)");
13832            }
13833            out.println();
13834        }
13835
13836        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13837                = new ArrayMap<ComponentName, PackageParser.Provider>();
13838        private int mFlags;
13839    }
13840
13841    static final class EphemeralIntentResolver
13842            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13843        /**
13844         * The result that has the highest defined order. Ordering applies on a
13845         * per-package basis. Mapping is from package name to Pair of order and
13846         * EphemeralResolveInfo.
13847         * <p>
13848         * NOTE: This is implemented as a field variable for convenience and efficiency.
13849         * By having a field variable, we're able to track filter ordering as soon as
13850         * a non-zero order is defined. Otherwise, multiple loops across the result set
13851         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13852         * this needs to be contained entirely within {@link #filterResults}.
13853         */
13854        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13855
13856        @Override
13857        protected AuxiliaryResolveInfo[] newArray(int size) {
13858            return new AuxiliaryResolveInfo[size];
13859        }
13860
13861        @Override
13862        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13863            return true;
13864        }
13865
13866        @Override
13867        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13868                int userId) {
13869            if (!sUserManager.exists(userId)) {
13870                return null;
13871            }
13872            final String packageName = responseObj.resolveInfo.getPackageName();
13873            final Integer order = responseObj.getOrder();
13874            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13875                    mOrderResult.get(packageName);
13876            // ordering is enabled and this item's order isn't high enough
13877            if (lastOrderResult != null && lastOrderResult.first >= order) {
13878                return null;
13879            }
13880            final InstantAppResolveInfo res = responseObj.resolveInfo;
13881            if (order > 0) {
13882                // non-zero order, enable ordering
13883                mOrderResult.put(packageName, new Pair<>(order, res));
13884            }
13885            return responseObj;
13886        }
13887
13888        @Override
13889        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13890            // only do work if ordering is enabled [most of the time it won't be]
13891            if (mOrderResult.size() == 0) {
13892                return;
13893            }
13894            int resultSize = results.size();
13895            for (int i = 0; i < resultSize; i++) {
13896                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13897                final String packageName = info.getPackageName();
13898                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13899                if (savedInfo == null) {
13900                    // package doesn't having ordering
13901                    continue;
13902                }
13903                if (savedInfo.second == info) {
13904                    // circled back to the highest ordered item; remove from order list
13905                    mOrderResult.remove(savedInfo);
13906                    if (mOrderResult.size() == 0) {
13907                        // no more ordered items
13908                        break;
13909                    }
13910                    continue;
13911                }
13912                // item has a worse order, remove it from the result list
13913                results.remove(i);
13914                resultSize--;
13915                i--;
13916            }
13917        }
13918    }
13919
13920    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13921            new Comparator<ResolveInfo>() {
13922        public int compare(ResolveInfo r1, ResolveInfo r2) {
13923            int v1 = r1.priority;
13924            int v2 = r2.priority;
13925            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13926            if (v1 != v2) {
13927                return (v1 > v2) ? -1 : 1;
13928            }
13929            v1 = r1.preferredOrder;
13930            v2 = r2.preferredOrder;
13931            if (v1 != v2) {
13932                return (v1 > v2) ? -1 : 1;
13933            }
13934            if (r1.isDefault != r2.isDefault) {
13935                return r1.isDefault ? -1 : 1;
13936            }
13937            v1 = r1.match;
13938            v2 = r2.match;
13939            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13940            if (v1 != v2) {
13941                return (v1 > v2) ? -1 : 1;
13942            }
13943            if (r1.system != r2.system) {
13944                return r1.system ? -1 : 1;
13945            }
13946            if (r1.activityInfo != null) {
13947                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13948            }
13949            if (r1.serviceInfo != null) {
13950                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13951            }
13952            if (r1.providerInfo != null) {
13953                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13954            }
13955            return 0;
13956        }
13957    };
13958
13959    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13960            new Comparator<ProviderInfo>() {
13961        public int compare(ProviderInfo p1, ProviderInfo p2) {
13962            final int v1 = p1.initOrder;
13963            final int v2 = p2.initOrder;
13964            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13965        }
13966    };
13967
13968    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13969            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13970            final int[] userIds) {
13971        mHandler.post(new Runnable() {
13972            @Override
13973            public void run() {
13974                try {
13975                    final IActivityManager am = ActivityManager.getService();
13976                    if (am == null) return;
13977                    final int[] resolvedUserIds;
13978                    if (userIds == null) {
13979                        resolvedUserIds = am.getRunningUserIds();
13980                    } else {
13981                        resolvedUserIds = userIds;
13982                    }
13983                    for (int id : resolvedUserIds) {
13984                        final Intent intent = new Intent(action,
13985                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13986                        if (extras != null) {
13987                            intent.putExtras(extras);
13988                        }
13989                        if (targetPkg != null) {
13990                            intent.setPackage(targetPkg);
13991                        }
13992                        // Modify the UID when posting to other users
13993                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13994                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13995                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13996                            intent.putExtra(Intent.EXTRA_UID, uid);
13997                        }
13998                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13999                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14000                        if (DEBUG_BROADCASTS) {
14001                            RuntimeException here = new RuntimeException("here");
14002                            here.fillInStackTrace();
14003                            Slog.d(TAG, "Sending to user " + id + ": "
14004                                    + intent.toShortString(false, true, false, false)
14005                                    + " " + intent.getExtras(), here);
14006                        }
14007                        am.broadcastIntent(null, intent, null, finishedReceiver,
14008                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14009                                null, finishedReceiver != null, false, id);
14010                    }
14011                } catch (RemoteException ex) {
14012                }
14013            }
14014        });
14015    }
14016
14017    /**
14018     * Check if the external storage media is available. This is true if there
14019     * is a mounted external storage medium or if the external storage is
14020     * emulated.
14021     */
14022    private boolean isExternalMediaAvailable() {
14023        return mMediaMounted || Environment.isExternalStorageEmulated();
14024    }
14025
14026    @Override
14027    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14028        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14029            return null;
14030        }
14031        // writer
14032        synchronized (mPackages) {
14033            if (!isExternalMediaAvailable()) {
14034                // If the external storage is no longer mounted at this point,
14035                // the caller may not have been able to delete all of this
14036                // packages files and can not delete any more.  Bail.
14037                return null;
14038            }
14039            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14040            if (lastPackage != null) {
14041                pkgs.remove(lastPackage);
14042            }
14043            if (pkgs.size() > 0) {
14044                return pkgs.get(0);
14045            }
14046        }
14047        return null;
14048    }
14049
14050    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14051        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14052                userId, andCode ? 1 : 0, packageName);
14053        if (mSystemReady) {
14054            msg.sendToTarget();
14055        } else {
14056            if (mPostSystemReadyMessages == null) {
14057                mPostSystemReadyMessages = new ArrayList<>();
14058            }
14059            mPostSystemReadyMessages.add(msg);
14060        }
14061    }
14062
14063    void startCleaningPackages() {
14064        // reader
14065        if (!isExternalMediaAvailable()) {
14066            return;
14067        }
14068        synchronized (mPackages) {
14069            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14070                return;
14071            }
14072        }
14073        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14074        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14075        IActivityManager am = ActivityManager.getService();
14076        if (am != null) {
14077            int dcsUid = -1;
14078            synchronized (mPackages) {
14079                if (!mDefaultContainerWhitelisted) {
14080                    mDefaultContainerWhitelisted = true;
14081                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14082                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14083                }
14084            }
14085            try {
14086                if (dcsUid > 0) {
14087                    am.backgroundWhitelistUid(dcsUid);
14088                }
14089                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14090                        UserHandle.USER_SYSTEM);
14091            } catch (RemoteException e) {
14092            }
14093        }
14094    }
14095
14096    @Override
14097    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14098            int installFlags, String installerPackageName, int userId) {
14099        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14100
14101        final int callingUid = Binder.getCallingUid();
14102        enforceCrossUserPermission(callingUid, userId,
14103                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14104
14105        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14106            try {
14107                if (observer != null) {
14108                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14109                }
14110            } catch (RemoteException re) {
14111            }
14112            return;
14113        }
14114
14115        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14116            installFlags |= PackageManager.INSTALL_FROM_ADB;
14117
14118        } else {
14119            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14120            // about installerPackageName.
14121
14122            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14123            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14124        }
14125
14126        UserHandle user;
14127        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14128            user = UserHandle.ALL;
14129        } else {
14130            user = new UserHandle(userId);
14131        }
14132
14133        // Only system components can circumvent runtime permissions when installing.
14134        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14135                && mContext.checkCallingOrSelfPermission(Manifest.permission
14136                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14137            throw new SecurityException("You need the "
14138                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14139                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14140        }
14141
14142        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14143                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14144            throw new IllegalArgumentException(
14145                    "New installs into ASEC containers no longer supported");
14146        }
14147
14148        final File originFile = new File(originPath);
14149        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14150
14151        final Message msg = mHandler.obtainMessage(INIT_COPY);
14152        final VerificationInfo verificationInfo = new VerificationInfo(
14153                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14154        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14155                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14156                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14157                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14158        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14159        msg.obj = params;
14160
14161        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14162                System.identityHashCode(msg.obj));
14163        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14164                System.identityHashCode(msg.obj));
14165
14166        mHandler.sendMessage(msg);
14167    }
14168
14169
14170    /**
14171     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14172     * it is acting on behalf on an enterprise or the user).
14173     *
14174     * Note that the ordering of the conditionals in this method is important. The checks we perform
14175     * are as follows, in this order:
14176     *
14177     * 1) If the install is being performed by a system app, we can trust the app to have set the
14178     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14179     *    what it is.
14180     * 2) If the install is being performed by a device or profile owner app, the install reason
14181     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14182     *    set the install reason correctly. If the app targets an older SDK version where install
14183     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14184     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14185     * 3) In all other cases, the install is being performed by a regular app that is neither part
14186     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14187     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14188     *    set to enterprise policy and if so, change it to unknown instead.
14189     */
14190    private int fixUpInstallReason(String installerPackageName, int installerUid,
14191            int installReason) {
14192        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14193                == PERMISSION_GRANTED) {
14194            // If the install is being performed by a system app, we trust that app to have set the
14195            // install reason correctly.
14196            return installReason;
14197        }
14198
14199        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14200            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14201        if (dpm != null) {
14202            ComponentName owner = null;
14203            try {
14204                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14205                if (owner == null) {
14206                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14207                }
14208            } catch (RemoteException e) {
14209            }
14210            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14211                // If the install is being performed by a device or profile owner, the install
14212                // reason should be enterprise policy.
14213                return PackageManager.INSTALL_REASON_POLICY;
14214            }
14215        }
14216
14217        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14218            // If the install is being performed by a regular app (i.e. neither system app nor
14219            // device or profile owner), we have no reason to believe that the app is acting on
14220            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14221            // change it to unknown instead.
14222            return PackageManager.INSTALL_REASON_UNKNOWN;
14223        }
14224
14225        // If the install is being performed by a regular app and the install reason was set to any
14226        // value but enterprise policy, leave the install reason unchanged.
14227        return installReason;
14228    }
14229
14230    void installStage(String packageName, File stagedDir, String stagedCid,
14231            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14232            String installerPackageName, int installerUid, UserHandle user,
14233            Certificate[][] certificates) {
14234        if (DEBUG_EPHEMERAL) {
14235            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14236                Slog.d(TAG, "Ephemeral install of " + packageName);
14237            }
14238        }
14239        final VerificationInfo verificationInfo = new VerificationInfo(
14240                sessionParams.originatingUri, sessionParams.referrerUri,
14241                sessionParams.originatingUid, installerUid);
14242
14243        final OriginInfo origin;
14244        if (stagedDir != null) {
14245            origin = OriginInfo.fromStagedFile(stagedDir);
14246        } else {
14247            origin = OriginInfo.fromStagedContainer(stagedCid);
14248        }
14249
14250        final Message msg = mHandler.obtainMessage(INIT_COPY);
14251        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14252                sessionParams.installReason);
14253        final InstallParams params = new InstallParams(origin, null, observer,
14254                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14255                verificationInfo, user, sessionParams.abiOverride,
14256                sessionParams.grantedRuntimePermissions, certificates, installReason);
14257        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14258        msg.obj = params;
14259
14260        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14261                System.identityHashCode(msg.obj));
14262        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14263                System.identityHashCode(msg.obj));
14264
14265        mHandler.sendMessage(msg);
14266    }
14267
14268    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14269            int userId) {
14270        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14271        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14272
14273        // Send a session commit broadcast
14274        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14275        info.installReason = pkgSetting.getInstallReason(userId);
14276        info.appPackageName = packageName;
14277        sendSessionCommitBroadcast(info, userId);
14278    }
14279
14280    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14281        if (ArrayUtils.isEmpty(userIds)) {
14282            return;
14283        }
14284        Bundle extras = new Bundle(1);
14285        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14286        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14287
14288        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14289                packageName, extras, 0, null, null, userIds);
14290        if (isSystem) {
14291            mHandler.post(() -> {
14292                        for (int userId : userIds) {
14293                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14294                        }
14295                    }
14296            );
14297        }
14298    }
14299
14300    /**
14301     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14302     * automatically without needing an explicit launch.
14303     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14304     */
14305    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14306        // If user is not running, the app didn't miss any broadcast
14307        if (!mUserManagerInternal.isUserRunning(userId)) {
14308            return;
14309        }
14310        final IActivityManager am = ActivityManager.getService();
14311        try {
14312            // Deliver LOCKED_BOOT_COMPLETED first
14313            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14314                    .setPackage(packageName);
14315            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14316            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14317                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14318
14319            // Deliver BOOT_COMPLETED only if user is unlocked
14320            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14321                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14322                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14323                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14324            }
14325        } catch (RemoteException e) {
14326            throw e.rethrowFromSystemServer();
14327        }
14328    }
14329
14330    @Override
14331    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14332            int userId) {
14333        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14334        PackageSetting pkgSetting;
14335        final int callingUid = Binder.getCallingUid();
14336        enforceCrossUserPermission(callingUid, userId,
14337                true /* requireFullPermission */, true /* checkShell */,
14338                "setApplicationHiddenSetting for user " + userId);
14339
14340        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14341            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14342            return false;
14343        }
14344
14345        long callingId = Binder.clearCallingIdentity();
14346        try {
14347            boolean sendAdded = false;
14348            boolean sendRemoved = false;
14349            // writer
14350            synchronized (mPackages) {
14351                pkgSetting = mSettings.mPackages.get(packageName);
14352                if (pkgSetting == null) {
14353                    return false;
14354                }
14355                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14356                    return false;
14357                }
14358                // Do not allow "android" is being disabled
14359                if ("android".equals(packageName)) {
14360                    Slog.w(TAG, "Cannot hide package: android");
14361                    return false;
14362                }
14363                // Cannot hide static shared libs as they are considered
14364                // a part of the using app (emulating static linking). Also
14365                // static libs are installed always on internal storage.
14366                PackageParser.Package pkg = mPackages.get(packageName);
14367                if (pkg != null && pkg.staticSharedLibName != null) {
14368                    Slog.w(TAG, "Cannot hide package: " + packageName
14369                            + " providing static shared library: "
14370                            + pkg.staticSharedLibName);
14371                    return false;
14372                }
14373                // Only allow protected packages to hide themselves.
14374                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14375                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14376                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14377                    return false;
14378                }
14379
14380                if (pkgSetting.getHidden(userId) != hidden) {
14381                    pkgSetting.setHidden(hidden, userId);
14382                    mSettings.writePackageRestrictionsLPr(userId);
14383                    if (hidden) {
14384                        sendRemoved = true;
14385                    } else {
14386                        sendAdded = true;
14387                    }
14388                }
14389            }
14390            if (sendAdded) {
14391                sendPackageAddedForUser(packageName, pkgSetting, userId);
14392                return true;
14393            }
14394            if (sendRemoved) {
14395                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14396                        "hiding pkg");
14397                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14398                return true;
14399            }
14400        } finally {
14401            Binder.restoreCallingIdentity(callingId);
14402        }
14403        return false;
14404    }
14405
14406    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14407            int userId) {
14408        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14409        info.removedPackage = packageName;
14410        info.installerPackageName = pkgSetting.installerPackageName;
14411        info.removedUsers = new int[] {userId};
14412        info.broadcastUsers = new int[] {userId};
14413        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14414        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14415    }
14416
14417    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14418        if (pkgList.length > 0) {
14419            Bundle extras = new Bundle(1);
14420            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14421
14422            sendPackageBroadcast(
14423                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14424                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14425                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14426                    new int[] {userId});
14427        }
14428    }
14429
14430    /**
14431     * Returns true if application is not found or there was an error. Otherwise it returns
14432     * the hidden state of the package for the given user.
14433     */
14434    @Override
14435    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14436        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14437        final int callingUid = Binder.getCallingUid();
14438        enforceCrossUserPermission(callingUid, userId,
14439                true /* requireFullPermission */, false /* checkShell */,
14440                "getApplicationHidden for user " + userId);
14441        PackageSetting ps;
14442        long callingId = Binder.clearCallingIdentity();
14443        try {
14444            // writer
14445            synchronized (mPackages) {
14446                ps = mSettings.mPackages.get(packageName);
14447                if (ps == null) {
14448                    return true;
14449                }
14450                if (filterAppAccessLPr(ps, callingUid, userId)) {
14451                    return true;
14452                }
14453                return ps.getHidden(userId);
14454            }
14455        } finally {
14456            Binder.restoreCallingIdentity(callingId);
14457        }
14458    }
14459
14460    /**
14461     * @hide
14462     */
14463    @Override
14464    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14465            int installReason) {
14466        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14467                null);
14468        PackageSetting pkgSetting;
14469        final int callingUid = Binder.getCallingUid();
14470        enforceCrossUserPermission(callingUid, userId,
14471                true /* requireFullPermission */, true /* checkShell */,
14472                "installExistingPackage for user " + userId);
14473        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14474            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14475        }
14476
14477        long callingId = Binder.clearCallingIdentity();
14478        try {
14479            boolean installed = false;
14480            final boolean instantApp =
14481                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14482            final boolean fullApp =
14483                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14484
14485            // writer
14486            synchronized (mPackages) {
14487                pkgSetting = mSettings.mPackages.get(packageName);
14488                if (pkgSetting == null) {
14489                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14490                }
14491                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14492                    // only allow the existing package to be used if it's installed as a full
14493                    // application for at least one user
14494                    boolean installAllowed = false;
14495                    for (int checkUserId : sUserManager.getUserIds()) {
14496                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14497                        if (installAllowed) {
14498                            break;
14499                        }
14500                    }
14501                    if (!installAllowed) {
14502                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14503                    }
14504                }
14505                if (!pkgSetting.getInstalled(userId)) {
14506                    pkgSetting.setInstalled(true, userId);
14507                    pkgSetting.setHidden(false, userId);
14508                    pkgSetting.setInstallReason(installReason, userId);
14509                    mSettings.writePackageRestrictionsLPr(userId);
14510                    mSettings.writeKernelMappingLPr(pkgSetting);
14511                    installed = true;
14512                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14513                    // upgrade app from instant to full; we don't allow app downgrade
14514                    installed = true;
14515                }
14516                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14517            }
14518
14519            if (installed) {
14520                if (pkgSetting.pkg != null) {
14521                    synchronized (mInstallLock) {
14522                        // We don't need to freeze for a brand new install
14523                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14524                    }
14525                }
14526                sendPackageAddedForUser(packageName, pkgSetting, userId);
14527                synchronized (mPackages) {
14528                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14529                }
14530            }
14531        } finally {
14532            Binder.restoreCallingIdentity(callingId);
14533        }
14534
14535        return PackageManager.INSTALL_SUCCEEDED;
14536    }
14537
14538    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14539            boolean instantApp, boolean fullApp) {
14540        // no state specified; do nothing
14541        if (!instantApp && !fullApp) {
14542            return;
14543        }
14544        if (userId != UserHandle.USER_ALL) {
14545            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14546                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14547            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14548                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14549            }
14550        } else {
14551            for (int currentUserId : sUserManager.getUserIds()) {
14552                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14553                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14554                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14555                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14556                }
14557            }
14558        }
14559    }
14560
14561    boolean isUserRestricted(int userId, String restrictionKey) {
14562        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14563        if (restrictions.getBoolean(restrictionKey, false)) {
14564            Log.w(TAG, "User is restricted: " + restrictionKey);
14565            return true;
14566        }
14567        return false;
14568    }
14569
14570    @Override
14571    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14572            int userId) {
14573        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14574        final int callingUid = Binder.getCallingUid();
14575        enforceCrossUserPermission(callingUid, userId,
14576                true /* requireFullPermission */, true /* checkShell */,
14577                "setPackagesSuspended for user " + userId);
14578
14579        if (ArrayUtils.isEmpty(packageNames)) {
14580            return packageNames;
14581        }
14582
14583        // List of package names for whom the suspended state has changed.
14584        List<String> changedPackages = new ArrayList<>(packageNames.length);
14585        // List of package names for whom the suspended state is not set as requested in this
14586        // method.
14587        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14588        long callingId = Binder.clearCallingIdentity();
14589        try {
14590            for (int i = 0; i < packageNames.length; i++) {
14591                String packageName = packageNames[i];
14592                boolean changed = false;
14593                final int appId;
14594                synchronized (mPackages) {
14595                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14596                    if (pkgSetting == null
14597                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14598                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14599                                + "\". Skipping suspending/un-suspending.");
14600                        unactionedPackages.add(packageName);
14601                        continue;
14602                    }
14603                    appId = pkgSetting.appId;
14604                    if (pkgSetting.getSuspended(userId) != suspended) {
14605                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14606                            unactionedPackages.add(packageName);
14607                            continue;
14608                        }
14609                        pkgSetting.setSuspended(suspended, userId);
14610                        mSettings.writePackageRestrictionsLPr(userId);
14611                        changed = true;
14612                        changedPackages.add(packageName);
14613                    }
14614                }
14615
14616                if (changed && suspended) {
14617                    killApplication(packageName, UserHandle.getUid(userId, appId),
14618                            "suspending package");
14619                }
14620            }
14621        } finally {
14622            Binder.restoreCallingIdentity(callingId);
14623        }
14624
14625        if (!changedPackages.isEmpty()) {
14626            sendPackagesSuspendedForUser(changedPackages.toArray(
14627                    new String[changedPackages.size()]), userId, suspended);
14628        }
14629
14630        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14631    }
14632
14633    @Override
14634    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14635        final int callingUid = Binder.getCallingUid();
14636        enforceCrossUserPermission(callingUid, userId,
14637                true /* requireFullPermission */, false /* checkShell */,
14638                "isPackageSuspendedForUser for user " + userId);
14639        synchronized (mPackages) {
14640            final PackageSetting ps = mSettings.mPackages.get(packageName);
14641            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14642                throw new IllegalArgumentException("Unknown target package: " + packageName);
14643            }
14644            return ps.getSuspended(userId);
14645        }
14646    }
14647
14648    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14649        if (isPackageDeviceAdmin(packageName, userId)) {
14650            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14651                    + "\": has an active device admin");
14652            return false;
14653        }
14654
14655        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14656        if (packageName.equals(activeLauncherPackageName)) {
14657            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14658                    + "\": contains the active launcher");
14659            return false;
14660        }
14661
14662        if (packageName.equals(mRequiredInstallerPackage)) {
14663            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14664                    + "\": required for package installation");
14665            return false;
14666        }
14667
14668        if (packageName.equals(mRequiredUninstallerPackage)) {
14669            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14670                    + "\": required for package uninstallation");
14671            return false;
14672        }
14673
14674        if (packageName.equals(mRequiredVerifierPackage)) {
14675            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14676                    + "\": required for package verification");
14677            return false;
14678        }
14679
14680        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14681            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14682                    + "\": is the default dialer");
14683            return false;
14684        }
14685
14686        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14687            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14688                    + "\": protected package");
14689            return false;
14690        }
14691
14692        // Cannot suspend static shared libs as they are considered
14693        // a part of the using app (emulating static linking). Also
14694        // static libs are installed always on internal storage.
14695        PackageParser.Package pkg = mPackages.get(packageName);
14696        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14697            Slog.w(TAG, "Cannot suspend package: " + packageName
14698                    + " providing static shared library: "
14699                    + pkg.staticSharedLibName);
14700            return false;
14701        }
14702
14703        return true;
14704    }
14705
14706    private String getActiveLauncherPackageName(int userId) {
14707        Intent intent = new Intent(Intent.ACTION_MAIN);
14708        intent.addCategory(Intent.CATEGORY_HOME);
14709        ResolveInfo resolveInfo = resolveIntent(
14710                intent,
14711                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14712                PackageManager.MATCH_DEFAULT_ONLY,
14713                userId);
14714
14715        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14716    }
14717
14718    private String getDefaultDialerPackageName(int userId) {
14719        synchronized (mPackages) {
14720            return mSettings.getDefaultDialerPackageNameLPw(userId);
14721        }
14722    }
14723
14724    @Override
14725    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14726        mContext.enforceCallingOrSelfPermission(
14727                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14728                "Only package verification agents can verify applications");
14729
14730        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14731        final PackageVerificationResponse response = new PackageVerificationResponse(
14732                verificationCode, Binder.getCallingUid());
14733        msg.arg1 = id;
14734        msg.obj = response;
14735        mHandler.sendMessage(msg);
14736    }
14737
14738    @Override
14739    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14740            long millisecondsToDelay) {
14741        mContext.enforceCallingOrSelfPermission(
14742                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14743                "Only package verification agents can extend verification timeouts");
14744
14745        final PackageVerificationState state = mPendingVerification.get(id);
14746        final PackageVerificationResponse response = new PackageVerificationResponse(
14747                verificationCodeAtTimeout, Binder.getCallingUid());
14748
14749        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14750            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14751        }
14752        if (millisecondsToDelay < 0) {
14753            millisecondsToDelay = 0;
14754        }
14755        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14756                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14757            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14758        }
14759
14760        if ((state != null) && !state.timeoutExtended()) {
14761            state.extendTimeout();
14762
14763            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14764            msg.arg1 = id;
14765            msg.obj = response;
14766            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14767        }
14768    }
14769
14770    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14771            int verificationCode, UserHandle user) {
14772        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14773        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14774        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14775        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14776        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14777
14778        mContext.sendBroadcastAsUser(intent, user,
14779                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14780    }
14781
14782    private ComponentName matchComponentForVerifier(String packageName,
14783            List<ResolveInfo> receivers) {
14784        ActivityInfo targetReceiver = null;
14785
14786        final int NR = receivers.size();
14787        for (int i = 0; i < NR; i++) {
14788            final ResolveInfo info = receivers.get(i);
14789            if (info.activityInfo == null) {
14790                continue;
14791            }
14792
14793            if (packageName.equals(info.activityInfo.packageName)) {
14794                targetReceiver = info.activityInfo;
14795                break;
14796            }
14797        }
14798
14799        if (targetReceiver == null) {
14800            return null;
14801        }
14802
14803        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14804    }
14805
14806    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14807            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14808        if (pkgInfo.verifiers.length == 0) {
14809            return null;
14810        }
14811
14812        final int N = pkgInfo.verifiers.length;
14813        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14814        for (int i = 0; i < N; i++) {
14815            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14816
14817            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14818                    receivers);
14819            if (comp == null) {
14820                continue;
14821            }
14822
14823            final int verifierUid = getUidForVerifier(verifierInfo);
14824            if (verifierUid == -1) {
14825                continue;
14826            }
14827
14828            if (DEBUG_VERIFY) {
14829                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14830                        + " with the correct signature");
14831            }
14832            sufficientVerifiers.add(comp);
14833            verificationState.addSufficientVerifier(verifierUid);
14834        }
14835
14836        return sufficientVerifiers;
14837    }
14838
14839    private int getUidForVerifier(VerifierInfo verifierInfo) {
14840        synchronized (mPackages) {
14841            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14842            if (pkg == null) {
14843                return -1;
14844            } else if (pkg.mSignatures.length != 1) {
14845                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14846                        + " has more than one signature; ignoring");
14847                return -1;
14848            }
14849
14850            /*
14851             * If the public key of the package's signature does not match
14852             * our expected public key, then this is a different package and
14853             * we should skip.
14854             */
14855
14856            final byte[] expectedPublicKey;
14857            try {
14858                final Signature verifierSig = pkg.mSignatures[0];
14859                final PublicKey publicKey = verifierSig.getPublicKey();
14860                expectedPublicKey = publicKey.getEncoded();
14861            } catch (CertificateException e) {
14862                return -1;
14863            }
14864
14865            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14866
14867            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14868                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14869                        + " does not have the expected public key; ignoring");
14870                return -1;
14871            }
14872
14873            return pkg.applicationInfo.uid;
14874        }
14875    }
14876
14877    @Override
14878    public void finishPackageInstall(int token, boolean didLaunch) {
14879        enforceSystemOrRoot("Only the system is allowed to finish installs");
14880
14881        if (DEBUG_INSTALL) {
14882            Slog.v(TAG, "BM finishing package install for " + token);
14883        }
14884        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14885
14886        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14887        mHandler.sendMessage(msg);
14888    }
14889
14890    /**
14891     * Get the verification agent timeout.  Used for both the APK verifier and the
14892     * intent filter verifier.
14893     *
14894     * @return verification timeout in milliseconds
14895     */
14896    private long getVerificationTimeout() {
14897        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14898                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14899                DEFAULT_VERIFICATION_TIMEOUT);
14900    }
14901
14902    /**
14903     * Get the default verification agent response code.
14904     *
14905     * @return default verification response code
14906     */
14907    private int getDefaultVerificationResponse(UserHandle user) {
14908        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14909            return PackageManager.VERIFICATION_REJECT;
14910        }
14911        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14912                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14913                DEFAULT_VERIFICATION_RESPONSE);
14914    }
14915
14916    /**
14917     * Check whether or not package verification has been enabled.
14918     *
14919     * @return true if verification should be performed
14920     */
14921    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14922        if (!DEFAULT_VERIFY_ENABLE) {
14923            return false;
14924        }
14925
14926        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14927
14928        // Check if installing from ADB
14929        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14930            // Do not run verification in a test harness environment
14931            if (ActivityManager.isRunningInTestHarness()) {
14932                return false;
14933            }
14934            if (ensureVerifyAppsEnabled) {
14935                return true;
14936            }
14937            // Check if the developer does not want package verification for ADB installs
14938            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14939                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14940                return false;
14941            }
14942        } else {
14943            // only when not installed from ADB, skip verification for instant apps when
14944            // the installer and verifier are the same.
14945            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14946                if (mInstantAppInstallerActivity != null
14947                        && mInstantAppInstallerActivity.packageName.equals(
14948                                mRequiredVerifierPackage)) {
14949                    try {
14950                        mContext.getSystemService(AppOpsManager.class)
14951                                .checkPackage(installerUid, mRequiredVerifierPackage);
14952                        if (DEBUG_VERIFY) {
14953                            Slog.i(TAG, "disable verification for instant app");
14954                        }
14955                        return false;
14956                    } catch (SecurityException ignore) { }
14957                }
14958            }
14959        }
14960
14961        if (ensureVerifyAppsEnabled) {
14962            return true;
14963        }
14964
14965        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14966                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14967    }
14968
14969    @Override
14970    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14971            throws RemoteException {
14972        mContext.enforceCallingOrSelfPermission(
14973                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14974                "Only intentfilter verification agents can verify applications");
14975
14976        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14977        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14978                Binder.getCallingUid(), verificationCode, failedDomains);
14979        msg.arg1 = id;
14980        msg.obj = response;
14981        mHandler.sendMessage(msg);
14982    }
14983
14984    @Override
14985    public int getIntentVerificationStatus(String packageName, int userId) {
14986        final int callingUid = Binder.getCallingUid();
14987        if (getInstantAppPackageName(callingUid) != null) {
14988            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14989        }
14990        synchronized (mPackages) {
14991            final PackageSetting ps = mSettings.mPackages.get(packageName);
14992            if (ps == null
14993                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14994                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14995            }
14996            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14997        }
14998    }
14999
15000    @Override
15001    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15002        mContext.enforceCallingOrSelfPermission(
15003                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15004
15005        boolean result = false;
15006        synchronized (mPackages) {
15007            final PackageSetting ps = mSettings.mPackages.get(packageName);
15008            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15009                return false;
15010            }
15011            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15012        }
15013        if (result) {
15014            scheduleWritePackageRestrictionsLocked(userId);
15015        }
15016        return result;
15017    }
15018
15019    @Override
15020    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15021            String packageName) {
15022        final int callingUid = Binder.getCallingUid();
15023        if (getInstantAppPackageName(callingUid) != null) {
15024            return ParceledListSlice.emptyList();
15025        }
15026        synchronized (mPackages) {
15027            final PackageSetting ps = mSettings.mPackages.get(packageName);
15028            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15029                return ParceledListSlice.emptyList();
15030            }
15031            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15032        }
15033    }
15034
15035    @Override
15036    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15037        if (TextUtils.isEmpty(packageName)) {
15038            return ParceledListSlice.emptyList();
15039        }
15040        final int callingUid = Binder.getCallingUid();
15041        final int callingUserId = UserHandle.getUserId(callingUid);
15042        synchronized (mPackages) {
15043            PackageParser.Package pkg = mPackages.get(packageName);
15044            if (pkg == null || pkg.activities == null) {
15045                return ParceledListSlice.emptyList();
15046            }
15047            if (pkg.mExtras == null) {
15048                return ParceledListSlice.emptyList();
15049            }
15050            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15051            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15052                return ParceledListSlice.emptyList();
15053            }
15054            final int count = pkg.activities.size();
15055            ArrayList<IntentFilter> result = new ArrayList<>();
15056            for (int n=0; n<count; n++) {
15057                PackageParser.Activity activity = pkg.activities.get(n);
15058                if (activity.intents != null && activity.intents.size() > 0) {
15059                    result.addAll(activity.intents);
15060                }
15061            }
15062            return new ParceledListSlice<>(result);
15063        }
15064    }
15065
15066    @Override
15067    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15068        mContext.enforceCallingOrSelfPermission(
15069                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15070
15071        synchronized (mPackages) {
15072            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15073            if (packageName != null) {
15074                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15075                        packageName, userId);
15076            }
15077            return result;
15078        }
15079    }
15080
15081    @Override
15082    public String getDefaultBrowserPackageName(int userId) {
15083        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15084            return null;
15085        }
15086        synchronized (mPackages) {
15087            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15088        }
15089    }
15090
15091    /**
15092     * Get the "allow unknown sources" setting.
15093     *
15094     * @return the current "allow unknown sources" setting
15095     */
15096    private int getUnknownSourcesSettings() {
15097        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15098                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15099                -1);
15100    }
15101
15102    @Override
15103    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15104        final int callingUid = Binder.getCallingUid();
15105        if (getInstantAppPackageName(callingUid) != null) {
15106            return;
15107        }
15108        // writer
15109        synchronized (mPackages) {
15110            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15111            if (targetPackageSetting == null
15112                    || filterAppAccessLPr(
15113                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15114                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15115            }
15116
15117            PackageSetting installerPackageSetting;
15118            if (installerPackageName != null) {
15119                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15120                if (installerPackageSetting == null) {
15121                    throw new IllegalArgumentException("Unknown installer package: "
15122                            + installerPackageName);
15123                }
15124            } else {
15125                installerPackageSetting = null;
15126            }
15127
15128            Signature[] callerSignature;
15129            Object obj = mSettings.getUserIdLPr(callingUid);
15130            if (obj != null) {
15131                if (obj instanceof SharedUserSetting) {
15132                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15133                } else if (obj instanceof PackageSetting) {
15134                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15135                } else {
15136                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15137                }
15138            } else {
15139                throw new SecurityException("Unknown calling UID: " + callingUid);
15140            }
15141
15142            // Verify: can't set installerPackageName to a package that is
15143            // not signed with the same cert as the caller.
15144            if (installerPackageSetting != null) {
15145                if (compareSignatures(callerSignature,
15146                        installerPackageSetting.signatures.mSignatures)
15147                        != PackageManager.SIGNATURE_MATCH) {
15148                    throw new SecurityException(
15149                            "Caller does not have same cert as new installer package "
15150                            + installerPackageName);
15151                }
15152            }
15153
15154            // Verify: if target already has an installer package, it must
15155            // be signed with the same cert as the caller.
15156            if (targetPackageSetting.installerPackageName != null) {
15157                PackageSetting setting = mSettings.mPackages.get(
15158                        targetPackageSetting.installerPackageName);
15159                // If the currently set package isn't valid, then it's always
15160                // okay to change it.
15161                if (setting != null) {
15162                    if (compareSignatures(callerSignature,
15163                            setting.signatures.mSignatures)
15164                            != PackageManager.SIGNATURE_MATCH) {
15165                        throw new SecurityException(
15166                                "Caller does not have same cert as old installer package "
15167                                + targetPackageSetting.installerPackageName);
15168                    }
15169                }
15170            }
15171
15172            // Okay!
15173            targetPackageSetting.installerPackageName = installerPackageName;
15174            if (installerPackageName != null) {
15175                mSettings.mInstallerPackages.add(installerPackageName);
15176            }
15177            scheduleWriteSettingsLocked();
15178        }
15179    }
15180
15181    @Override
15182    public void setApplicationCategoryHint(String packageName, int categoryHint,
15183            String callerPackageName) {
15184        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15185            throw new SecurityException("Instant applications don't have access to this method");
15186        }
15187        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15188                callerPackageName);
15189        synchronized (mPackages) {
15190            PackageSetting ps = mSettings.mPackages.get(packageName);
15191            if (ps == null) {
15192                throw new IllegalArgumentException("Unknown target package " + packageName);
15193            }
15194            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15195                throw new IllegalArgumentException("Unknown target package " + packageName);
15196            }
15197            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15198                throw new IllegalArgumentException("Calling package " + callerPackageName
15199                        + " is not installer for " + packageName);
15200            }
15201
15202            if (ps.categoryHint != categoryHint) {
15203                ps.categoryHint = categoryHint;
15204                scheduleWriteSettingsLocked();
15205            }
15206        }
15207    }
15208
15209    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15210        // Queue up an async operation since the package installation may take a little while.
15211        mHandler.post(new Runnable() {
15212            public void run() {
15213                mHandler.removeCallbacks(this);
15214                 // Result object to be returned
15215                PackageInstalledInfo res = new PackageInstalledInfo();
15216                res.setReturnCode(currentStatus);
15217                res.uid = -1;
15218                res.pkg = null;
15219                res.removedInfo = null;
15220                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15221                    args.doPreInstall(res.returnCode);
15222                    synchronized (mInstallLock) {
15223                        installPackageTracedLI(args, res);
15224                    }
15225                    args.doPostInstall(res.returnCode, res.uid);
15226                }
15227
15228                // A restore should be performed at this point if (a) the install
15229                // succeeded, (b) the operation is not an update, and (c) the new
15230                // package has not opted out of backup participation.
15231                final boolean update = res.removedInfo != null
15232                        && res.removedInfo.removedPackage != null;
15233                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15234                boolean doRestore = !update
15235                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15236
15237                // Set up the post-install work request bookkeeping.  This will be used
15238                // and cleaned up by the post-install event handling regardless of whether
15239                // there's a restore pass performed.  Token values are >= 1.
15240                int token;
15241                if (mNextInstallToken < 0) mNextInstallToken = 1;
15242                token = mNextInstallToken++;
15243
15244                PostInstallData data = new PostInstallData(args, res);
15245                mRunningInstalls.put(token, data);
15246                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15247
15248                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15249                    // Pass responsibility to the Backup Manager.  It will perform a
15250                    // restore if appropriate, then pass responsibility back to the
15251                    // Package Manager to run the post-install observer callbacks
15252                    // and broadcasts.
15253                    IBackupManager bm = IBackupManager.Stub.asInterface(
15254                            ServiceManager.getService(Context.BACKUP_SERVICE));
15255                    if (bm != null) {
15256                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15257                                + " to BM for possible restore");
15258                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15259                        try {
15260                            // TODO: http://b/22388012
15261                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15262                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15263                            } else {
15264                                doRestore = false;
15265                            }
15266                        } catch (RemoteException e) {
15267                            // can't happen; the backup manager is local
15268                        } catch (Exception e) {
15269                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15270                            doRestore = false;
15271                        }
15272                    } else {
15273                        Slog.e(TAG, "Backup Manager not found!");
15274                        doRestore = false;
15275                    }
15276                }
15277
15278                if (!doRestore) {
15279                    // No restore possible, or the Backup Manager was mysteriously not
15280                    // available -- just fire the post-install work request directly.
15281                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15282
15283                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15284
15285                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15286                    mHandler.sendMessage(msg);
15287                }
15288            }
15289        });
15290    }
15291
15292    /**
15293     * Callback from PackageSettings whenever an app is first transitioned out of the
15294     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15295     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15296     * here whether the app is the target of an ongoing install, and only send the
15297     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15298     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15299     * handling.
15300     */
15301    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15302        // Serialize this with the rest of the install-process message chain.  In the
15303        // restore-at-install case, this Runnable will necessarily run before the
15304        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15305        // are coherent.  In the non-restore case, the app has already completed install
15306        // and been launched through some other means, so it is not in a problematic
15307        // state for observers to see the FIRST_LAUNCH signal.
15308        mHandler.post(new Runnable() {
15309            @Override
15310            public void run() {
15311                for (int i = 0; i < mRunningInstalls.size(); i++) {
15312                    final PostInstallData data = mRunningInstalls.valueAt(i);
15313                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15314                        continue;
15315                    }
15316                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15317                        // right package; but is it for the right user?
15318                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15319                            if (userId == data.res.newUsers[uIndex]) {
15320                                if (DEBUG_BACKUP) {
15321                                    Slog.i(TAG, "Package " + pkgName
15322                                            + " being restored so deferring FIRST_LAUNCH");
15323                                }
15324                                return;
15325                            }
15326                        }
15327                    }
15328                }
15329                // didn't find it, so not being restored
15330                if (DEBUG_BACKUP) {
15331                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15332                }
15333                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15334            }
15335        });
15336    }
15337
15338    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15339        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15340                installerPkg, null, userIds);
15341    }
15342
15343    private abstract class HandlerParams {
15344        private static final int MAX_RETRIES = 4;
15345
15346        /**
15347         * Number of times startCopy() has been attempted and had a non-fatal
15348         * error.
15349         */
15350        private int mRetries = 0;
15351
15352        /** User handle for the user requesting the information or installation. */
15353        private final UserHandle mUser;
15354        String traceMethod;
15355        int traceCookie;
15356
15357        HandlerParams(UserHandle user) {
15358            mUser = user;
15359        }
15360
15361        UserHandle getUser() {
15362            return mUser;
15363        }
15364
15365        HandlerParams setTraceMethod(String traceMethod) {
15366            this.traceMethod = traceMethod;
15367            return this;
15368        }
15369
15370        HandlerParams setTraceCookie(int traceCookie) {
15371            this.traceCookie = traceCookie;
15372            return this;
15373        }
15374
15375        final boolean startCopy() {
15376            boolean res;
15377            try {
15378                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15379
15380                if (++mRetries > MAX_RETRIES) {
15381                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15382                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15383                    handleServiceError();
15384                    return false;
15385                } else {
15386                    handleStartCopy();
15387                    res = true;
15388                }
15389            } catch (RemoteException e) {
15390                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15391                mHandler.sendEmptyMessage(MCS_RECONNECT);
15392                res = false;
15393            }
15394            handleReturnCode();
15395            return res;
15396        }
15397
15398        final void serviceError() {
15399            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15400            handleServiceError();
15401            handleReturnCode();
15402        }
15403
15404        abstract void handleStartCopy() throws RemoteException;
15405        abstract void handleServiceError();
15406        abstract void handleReturnCode();
15407    }
15408
15409    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15410        for (File path : paths) {
15411            try {
15412                mcs.clearDirectory(path.getAbsolutePath());
15413            } catch (RemoteException e) {
15414            }
15415        }
15416    }
15417
15418    static class OriginInfo {
15419        /**
15420         * Location where install is coming from, before it has been
15421         * copied/renamed into place. This could be a single monolithic APK
15422         * file, or a cluster directory. This location may be untrusted.
15423         */
15424        final File file;
15425        final String cid;
15426
15427        /**
15428         * Flag indicating that {@link #file} or {@link #cid} has already been
15429         * staged, meaning downstream users don't need to defensively copy the
15430         * contents.
15431         */
15432        final boolean staged;
15433
15434        /**
15435         * Flag indicating that {@link #file} or {@link #cid} is an already
15436         * installed app that is being moved.
15437         */
15438        final boolean existing;
15439
15440        final String resolvedPath;
15441        final File resolvedFile;
15442
15443        static OriginInfo fromNothing() {
15444            return new OriginInfo(null, null, false, false);
15445        }
15446
15447        static OriginInfo fromUntrustedFile(File file) {
15448            return new OriginInfo(file, null, false, false);
15449        }
15450
15451        static OriginInfo fromExistingFile(File file) {
15452            return new OriginInfo(file, null, false, true);
15453        }
15454
15455        static OriginInfo fromStagedFile(File file) {
15456            return new OriginInfo(file, null, true, false);
15457        }
15458
15459        static OriginInfo fromStagedContainer(String cid) {
15460            return new OriginInfo(null, cid, true, false);
15461        }
15462
15463        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15464            this.file = file;
15465            this.cid = cid;
15466            this.staged = staged;
15467            this.existing = existing;
15468
15469            if (cid != null) {
15470                resolvedPath = PackageHelper.getSdDir(cid);
15471                resolvedFile = new File(resolvedPath);
15472            } else if (file != null) {
15473                resolvedPath = file.getAbsolutePath();
15474                resolvedFile = file;
15475            } else {
15476                resolvedPath = null;
15477                resolvedFile = null;
15478            }
15479        }
15480    }
15481
15482    static class MoveInfo {
15483        final int moveId;
15484        final String fromUuid;
15485        final String toUuid;
15486        final String packageName;
15487        final String dataAppName;
15488        final int appId;
15489        final String seinfo;
15490        final int targetSdkVersion;
15491
15492        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15493                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15494            this.moveId = moveId;
15495            this.fromUuid = fromUuid;
15496            this.toUuid = toUuid;
15497            this.packageName = packageName;
15498            this.dataAppName = dataAppName;
15499            this.appId = appId;
15500            this.seinfo = seinfo;
15501            this.targetSdkVersion = targetSdkVersion;
15502        }
15503    }
15504
15505    static class VerificationInfo {
15506        /** A constant used to indicate that a uid value is not present. */
15507        public static final int NO_UID = -1;
15508
15509        /** URI referencing where the package was downloaded from. */
15510        final Uri originatingUri;
15511
15512        /** HTTP referrer URI associated with the originatingURI. */
15513        final Uri referrer;
15514
15515        /** UID of the application that the install request originated from. */
15516        final int originatingUid;
15517
15518        /** UID of application requesting the install */
15519        final int installerUid;
15520
15521        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15522            this.originatingUri = originatingUri;
15523            this.referrer = referrer;
15524            this.originatingUid = originatingUid;
15525            this.installerUid = installerUid;
15526        }
15527    }
15528
15529    class InstallParams extends HandlerParams {
15530        final OriginInfo origin;
15531        final MoveInfo move;
15532        final IPackageInstallObserver2 observer;
15533        int installFlags;
15534        final String installerPackageName;
15535        final String volumeUuid;
15536        private InstallArgs mArgs;
15537        private int mRet;
15538        final String packageAbiOverride;
15539        final String[] grantedRuntimePermissions;
15540        final VerificationInfo verificationInfo;
15541        final Certificate[][] certificates;
15542        final int installReason;
15543
15544        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15545                int installFlags, String installerPackageName, String volumeUuid,
15546                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15547                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15548            super(user);
15549            this.origin = origin;
15550            this.move = move;
15551            this.observer = observer;
15552            this.installFlags = installFlags;
15553            this.installerPackageName = installerPackageName;
15554            this.volumeUuid = volumeUuid;
15555            this.verificationInfo = verificationInfo;
15556            this.packageAbiOverride = packageAbiOverride;
15557            this.grantedRuntimePermissions = grantedPermissions;
15558            this.certificates = certificates;
15559            this.installReason = installReason;
15560        }
15561
15562        @Override
15563        public String toString() {
15564            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15565                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15566        }
15567
15568        private int installLocationPolicy(PackageInfoLite pkgLite) {
15569            String packageName = pkgLite.packageName;
15570            int installLocation = pkgLite.installLocation;
15571            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15572            // reader
15573            synchronized (mPackages) {
15574                // Currently installed package which the new package is attempting to replace or
15575                // null if no such package is installed.
15576                PackageParser.Package installedPkg = mPackages.get(packageName);
15577                // Package which currently owns the data which the new package will own if installed.
15578                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15579                // will be null whereas dataOwnerPkg will contain information about the package
15580                // which was uninstalled while keeping its data.
15581                PackageParser.Package dataOwnerPkg = installedPkg;
15582                if (dataOwnerPkg  == null) {
15583                    PackageSetting ps = mSettings.mPackages.get(packageName);
15584                    if (ps != null) {
15585                        dataOwnerPkg = ps.pkg;
15586                    }
15587                }
15588
15589                if (dataOwnerPkg != null) {
15590                    // If installed, the package will get access to data left on the device by its
15591                    // predecessor. As a security measure, this is permited only if this is not a
15592                    // version downgrade or if the predecessor package is marked as debuggable and
15593                    // a downgrade is explicitly requested.
15594                    //
15595                    // On debuggable platform builds, downgrades are permitted even for
15596                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15597                    // not offer security guarantees and thus it's OK to disable some security
15598                    // mechanisms to make debugging/testing easier on those builds. However, even on
15599                    // debuggable builds downgrades of packages are permitted only if requested via
15600                    // installFlags. This is because we aim to keep the behavior of debuggable
15601                    // platform builds as close as possible to the behavior of non-debuggable
15602                    // platform builds.
15603                    final boolean downgradeRequested =
15604                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15605                    final boolean packageDebuggable =
15606                                (dataOwnerPkg.applicationInfo.flags
15607                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15608                    final boolean downgradePermitted =
15609                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15610                    if (!downgradePermitted) {
15611                        try {
15612                            checkDowngrade(dataOwnerPkg, pkgLite);
15613                        } catch (PackageManagerException e) {
15614                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15615                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15616                        }
15617                    }
15618                }
15619
15620                if (installedPkg != null) {
15621                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15622                        // Check for updated system application.
15623                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15624                            if (onSd) {
15625                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15626                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15627                            }
15628                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15629                        } else {
15630                            if (onSd) {
15631                                // Install flag overrides everything.
15632                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15633                            }
15634                            // If current upgrade specifies particular preference
15635                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15636                                // Application explicitly specified internal.
15637                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15638                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15639                                // App explictly prefers external. Let policy decide
15640                            } else {
15641                                // Prefer previous location
15642                                if (isExternal(installedPkg)) {
15643                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15644                                }
15645                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15646                            }
15647                        }
15648                    } else {
15649                        // Invalid install. Return error code
15650                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15651                    }
15652                }
15653            }
15654            // All the special cases have been taken care of.
15655            // Return result based on recommended install location.
15656            if (onSd) {
15657                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15658            }
15659            return pkgLite.recommendedInstallLocation;
15660        }
15661
15662        /*
15663         * Invoke remote method to get package information and install
15664         * location values. Override install location based on default
15665         * policy if needed and then create install arguments based
15666         * on the install location.
15667         */
15668        public void handleStartCopy() throws RemoteException {
15669            int ret = PackageManager.INSTALL_SUCCEEDED;
15670
15671            // If we're already staged, we've firmly committed to an install location
15672            if (origin.staged) {
15673                if (origin.file != null) {
15674                    installFlags |= PackageManager.INSTALL_INTERNAL;
15675                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15676                } else if (origin.cid != null) {
15677                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15678                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15679                } else {
15680                    throw new IllegalStateException("Invalid stage location");
15681                }
15682            }
15683
15684            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15685            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15686            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15687            PackageInfoLite pkgLite = null;
15688
15689            if (onInt && onSd) {
15690                // Check if both bits are set.
15691                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15692                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15693            } else if (onSd && ephemeral) {
15694                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15695                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15696            } else {
15697                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15698                        packageAbiOverride);
15699
15700                if (DEBUG_EPHEMERAL && ephemeral) {
15701                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15702                }
15703
15704                /*
15705                 * If we have too little free space, try to free cache
15706                 * before giving up.
15707                 */
15708                if (!origin.staged && pkgLite.recommendedInstallLocation
15709                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15710                    // TODO: focus freeing disk space on the target device
15711                    final StorageManager storage = StorageManager.from(mContext);
15712                    final long lowThreshold = storage.getStorageLowBytes(
15713                            Environment.getDataDirectory());
15714
15715                    final long sizeBytes = mContainerService.calculateInstalledSize(
15716                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15717
15718                    try {
15719                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15720                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15721                                installFlags, packageAbiOverride);
15722                    } catch (InstallerException e) {
15723                        Slog.w(TAG, "Failed to free cache", e);
15724                    }
15725
15726                    /*
15727                     * The cache free must have deleted the file we
15728                     * downloaded to install.
15729                     *
15730                     * TODO: fix the "freeCache" call to not delete
15731                     *       the file we care about.
15732                     */
15733                    if (pkgLite.recommendedInstallLocation
15734                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15735                        pkgLite.recommendedInstallLocation
15736                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15737                    }
15738                }
15739            }
15740
15741            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15742                int loc = pkgLite.recommendedInstallLocation;
15743                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15744                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15745                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15746                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15747                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15748                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15749                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15750                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15751                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15752                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15753                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15754                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15755                } else {
15756                    // Override with defaults if needed.
15757                    loc = installLocationPolicy(pkgLite);
15758                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15759                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15760                    } else if (!onSd && !onInt) {
15761                        // Override install location with flags
15762                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15763                            // Set the flag to install on external media.
15764                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15765                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15766                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15767                            if (DEBUG_EPHEMERAL) {
15768                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15769                            }
15770                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15771                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15772                                    |PackageManager.INSTALL_INTERNAL);
15773                        } else {
15774                            // Make sure the flag for installing on external
15775                            // media is unset
15776                            installFlags |= PackageManager.INSTALL_INTERNAL;
15777                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15778                        }
15779                    }
15780                }
15781            }
15782
15783            final InstallArgs args = createInstallArgs(this);
15784            mArgs = args;
15785
15786            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15787                // TODO: http://b/22976637
15788                // Apps installed for "all" users use the device owner to verify the app
15789                UserHandle verifierUser = getUser();
15790                if (verifierUser == UserHandle.ALL) {
15791                    verifierUser = UserHandle.SYSTEM;
15792                }
15793
15794                /*
15795                 * Determine if we have any installed package verifiers. If we
15796                 * do, then we'll defer to them to verify the packages.
15797                 */
15798                final int requiredUid = mRequiredVerifierPackage == null ? -1
15799                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15800                                verifierUser.getIdentifier());
15801                final int installerUid =
15802                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15803                if (!origin.existing && requiredUid != -1
15804                        && isVerificationEnabled(
15805                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15806                    final Intent verification = new Intent(
15807                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15808                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15809                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15810                            PACKAGE_MIME_TYPE);
15811                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15812
15813                    // Query all live verifiers based on current user state
15814                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15815                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15816
15817                    if (DEBUG_VERIFY) {
15818                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15819                                + verification.toString() + " with " + pkgLite.verifiers.length
15820                                + " optional verifiers");
15821                    }
15822
15823                    final int verificationId = mPendingVerificationToken++;
15824
15825                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15826
15827                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15828                            installerPackageName);
15829
15830                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15831                            installFlags);
15832
15833                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15834                            pkgLite.packageName);
15835
15836                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15837                            pkgLite.versionCode);
15838
15839                    if (verificationInfo != null) {
15840                        if (verificationInfo.originatingUri != null) {
15841                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15842                                    verificationInfo.originatingUri);
15843                        }
15844                        if (verificationInfo.referrer != null) {
15845                            verification.putExtra(Intent.EXTRA_REFERRER,
15846                                    verificationInfo.referrer);
15847                        }
15848                        if (verificationInfo.originatingUid >= 0) {
15849                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15850                                    verificationInfo.originatingUid);
15851                        }
15852                        if (verificationInfo.installerUid >= 0) {
15853                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15854                                    verificationInfo.installerUid);
15855                        }
15856                    }
15857
15858                    final PackageVerificationState verificationState = new PackageVerificationState(
15859                            requiredUid, args);
15860
15861                    mPendingVerification.append(verificationId, verificationState);
15862
15863                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15864                            receivers, verificationState);
15865
15866                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15867                    final long idleDuration = getVerificationTimeout();
15868
15869                    /*
15870                     * If any sufficient verifiers were listed in the package
15871                     * manifest, attempt to ask them.
15872                     */
15873                    if (sufficientVerifiers != null) {
15874                        final int N = sufficientVerifiers.size();
15875                        if (N == 0) {
15876                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15877                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15878                        } else {
15879                            for (int i = 0; i < N; i++) {
15880                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15881                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15882                                        verifierComponent.getPackageName(), idleDuration,
15883                                        verifierUser.getIdentifier(), false, "package verifier");
15884
15885                                final Intent sufficientIntent = new Intent(verification);
15886                                sufficientIntent.setComponent(verifierComponent);
15887                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15888                            }
15889                        }
15890                    }
15891
15892                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15893                            mRequiredVerifierPackage, receivers);
15894                    if (ret == PackageManager.INSTALL_SUCCEEDED
15895                            && mRequiredVerifierPackage != null) {
15896                        Trace.asyncTraceBegin(
15897                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15898                        /*
15899                         * Send the intent to the required verification agent,
15900                         * but only start the verification timeout after the
15901                         * target BroadcastReceivers have run.
15902                         */
15903                        verification.setComponent(requiredVerifierComponent);
15904                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15905                                mRequiredVerifierPackage, idleDuration,
15906                                verifierUser.getIdentifier(), false, "package verifier");
15907                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15908                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15909                                new BroadcastReceiver() {
15910                                    @Override
15911                                    public void onReceive(Context context, Intent intent) {
15912                                        final Message msg = mHandler
15913                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15914                                        msg.arg1 = verificationId;
15915                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15916                                    }
15917                                }, null, 0, null, null);
15918
15919                        /*
15920                         * We don't want the copy to proceed until verification
15921                         * succeeds, so null out this field.
15922                         */
15923                        mArgs = null;
15924                    }
15925                } else {
15926                    /*
15927                     * No package verification is enabled, so immediately start
15928                     * the remote call to initiate copy using temporary file.
15929                     */
15930                    ret = args.copyApk(mContainerService, true);
15931                }
15932            }
15933
15934            mRet = ret;
15935        }
15936
15937        @Override
15938        void handleReturnCode() {
15939            // If mArgs is null, then MCS couldn't be reached. When it
15940            // reconnects, it will try again to install. At that point, this
15941            // will succeed.
15942            if (mArgs != null) {
15943                processPendingInstall(mArgs, mRet);
15944            }
15945        }
15946
15947        @Override
15948        void handleServiceError() {
15949            mArgs = createInstallArgs(this);
15950            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15951        }
15952
15953        public boolean isForwardLocked() {
15954            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15955        }
15956    }
15957
15958    /**
15959     * Used during creation of InstallArgs
15960     *
15961     * @param installFlags package installation flags
15962     * @return true if should be installed on external storage
15963     */
15964    private static boolean installOnExternalAsec(int installFlags) {
15965        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
15966            return false;
15967        }
15968        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
15969            return true;
15970        }
15971        return false;
15972    }
15973
15974    /**
15975     * Used during creation of InstallArgs
15976     *
15977     * @param installFlags package installation flags
15978     * @return true if should be installed as forward locked
15979     */
15980    private static boolean installForwardLocked(int installFlags) {
15981        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15982    }
15983
15984    private InstallArgs createInstallArgs(InstallParams params) {
15985        if (params.move != null) {
15986            return new MoveInstallArgs(params);
15987        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15988            return new AsecInstallArgs(params);
15989        } else {
15990            return new FileInstallArgs(params);
15991        }
15992    }
15993
15994    /**
15995     * Create args that describe an existing installed package. Typically used
15996     * when cleaning up old installs, or used as a move source.
15997     */
15998    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15999            String resourcePath, String[] instructionSets) {
16000        final boolean isInAsec;
16001        if (installOnExternalAsec(installFlags)) {
16002            /* Apps on SD card are always in ASEC containers. */
16003            isInAsec = true;
16004        } else if (installForwardLocked(installFlags)
16005                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16006            /*
16007             * Forward-locked apps are only in ASEC containers if they're the
16008             * new style
16009             */
16010            isInAsec = true;
16011        } else {
16012            isInAsec = false;
16013        }
16014
16015        if (isInAsec) {
16016            return new AsecInstallArgs(codePath, instructionSets,
16017                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16018        } else {
16019            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16020        }
16021    }
16022
16023    static abstract class InstallArgs {
16024        /** @see InstallParams#origin */
16025        final OriginInfo origin;
16026        /** @see InstallParams#move */
16027        final MoveInfo move;
16028
16029        final IPackageInstallObserver2 observer;
16030        // Always refers to PackageManager flags only
16031        final int installFlags;
16032        final String installerPackageName;
16033        final String volumeUuid;
16034        final UserHandle user;
16035        final String abiOverride;
16036        final String[] installGrantPermissions;
16037        /** If non-null, drop an async trace when the install completes */
16038        final String traceMethod;
16039        final int traceCookie;
16040        final Certificate[][] certificates;
16041        final int installReason;
16042
16043        // The list of instruction sets supported by this app. This is currently
16044        // only used during the rmdex() phase to clean up resources. We can get rid of this
16045        // if we move dex files under the common app path.
16046        /* nullable */ String[] instructionSets;
16047
16048        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16049                int installFlags, String installerPackageName, String volumeUuid,
16050                UserHandle user, String[] instructionSets,
16051                String abiOverride, String[] installGrantPermissions,
16052                String traceMethod, int traceCookie, Certificate[][] certificates,
16053                int installReason) {
16054            this.origin = origin;
16055            this.move = move;
16056            this.installFlags = installFlags;
16057            this.observer = observer;
16058            this.installerPackageName = installerPackageName;
16059            this.volumeUuid = volumeUuid;
16060            this.user = user;
16061            this.instructionSets = instructionSets;
16062            this.abiOverride = abiOverride;
16063            this.installGrantPermissions = installGrantPermissions;
16064            this.traceMethod = traceMethod;
16065            this.traceCookie = traceCookie;
16066            this.certificates = certificates;
16067            this.installReason = installReason;
16068        }
16069
16070        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16071        abstract int doPreInstall(int status);
16072
16073        /**
16074         * Rename package into final resting place. All paths on the given
16075         * scanned package should be updated to reflect the rename.
16076         */
16077        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16078        abstract int doPostInstall(int status, int uid);
16079
16080        /** @see PackageSettingBase#codePathString */
16081        abstract String getCodePath();
16082        /** @see PackageSettingBase#resourcePathString */
16083        abstract String getResourcePath();
16084
16085        // Need installer lock especially for dex file removal.
16086        abstract void cleanUpResourcesLI();
16087        abstract boolean doPostDeleteLI(boolean delete);
16088
16089        /**
16090         * Called before the source arguments are copied. This is used mostly
16091         * for MoveParams when it needs to read the source file to put it in the
16092         * destination.
16093         */
16094        int doPreCopy() {
16095            return PackageManager.INSTALL_SUCCEEDED;
16096        }
16097
16098        /**
16099         * Called after the source arguments are copied. This is used mostly for
16100         * MoveParams when it needs to read the source file to put it in the
16101         * destination.
16102         */
16103        int doPostCopy(int uid) {
16104            return PackageManager.INSTALL_SUCCEEDED;
16105        }
16106
16107        protected boolean isFwdLocked() {
16108            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16109        }
16110
16111        protected boolean isExternalAsec() {
16112            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16113        }
16114
16115        protected boolean isEphemeral() {
16116            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16117        }
16118
16119        UserHandle getUser() {
16120            return user;
16121        }
16122    }
16123
16124    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16125        if (!allCodePaths.isEmpty()) {
16126            if (instructionSets == null) {
16127                throw new IllegalStateException("instructionSet == null");
16128            }
16129            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16130            for (String codePath : allCodePaths) {
16131                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16132                    try {
16133                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16134                    } catch (InstallerException ignored) {
16135                    }
16136                }
16137            }
16138        }
16139    }
16140
16141    /**
16142     * Logic to handle installation of non-ASEC applications, including copying
16143     * and renaming logic.
16144     */
16145    class FileInstallArgs extends InstallArgs {
16146        private File codeFile;
16147        private File resourceFile;
16148
16149        // Example topology:
16150        // /data/app/com.example/base.apk
16151        // /data/app/com.example/split_foo.apk
16152        // /data/app/com.example/lib/arm/libfoo.so
16153        // /data/app/com.example/lib/arm64/libfoo.so
16154        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16155
16156        /** New install */
16157        FileInstallArgs(InstallParams params) {
16158            super(params.origin, params.move, params.observer, params.installFlags,
16159                    params.installerPackageName, params.volumeUuid,
16160                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16161                    params.grantedRuntimePermissions,
16162                    params.traceMethod, params.traceCookie, params.certificates,
16163                    params.installReason);
16164            if (isFwdLocked()) {
16165                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16166            }
16167        }
16168
16169        /** Existing install */
16170        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16171            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16172                    null, null, null, 0, null /*certificates*/,
16173                    PackageManager.INSTALL_REASON_UNKNOWN);
16174            this.codeFile = (codePath != null) ? new File(codePath) : null;
16175            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16176        }
16177
16178        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16179            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16180            try {
16181                return doCopyApk(imcs, temp);
16182            } finally {
16183                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16184            }
16185        }
16186
16187        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16188            if (origin.staged) {
16189                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16190                codeFile = origin.file;
16191                resourceFile = origin.file;
16192                return PackageManager.INSTALL_SUCCEEDED;
16193            }
16194
16195            try {
16196                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16197                final File tempDir =
16198                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16199                codeFile = tempDir;
16200                resourceFile = tempDir;
16201            } catch (IOException e) {
16202                Slog.w(TAG, "Failed to create copy file: " + e);
16203                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16204            }
16205
16206            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16207                @Override
16208                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16209                    if (!FileUtils.isValidExtFilename(name)) {
16210                        throw new IllegalArgumentException("Invalid filename: " + name);
16211                    }
16212                    try {
16213                        final File file = new File(codeFile, name);
16214                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16215                                O_RDWR | O_CREAT, 0644);
16216                        Os.chmod(file.getAbsolutePath(), 0644);
16217                        return new ParcelFileDescriptor(fd);
16218                    } catch (ErrnoException e) {
16219                        throw new RemoteException("Failed to open: " + e.getMessage());
16220                    }
16221                }
16222            };
16223
16224            int ret = PackageManager.INSTALL_SUCCEEDED;
16225            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16226            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16227                Slog.e(TAG, "Failed to copy package");
16228                return ret;
16229            }
16230
16231            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16232            NativeLibraryHelper.Handle handle = null;
16233            try {
16234                handle = NativeLibraryHelper.Handle.create(codeFile);
16235                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16236                        abiOverride);
16237            } catch (IOException e) {
16238                Slog.e(TAG, "Copying native libraries failed", e);
16239                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16240            } finally {
16241                IoUtils.closeQuietly(handle);
16242            }
16243
16244            return ret;
16245        }
16246
16247        int doPreInstall(int status) {
16248            if (status != PackageManager.INSTALL_SUCCEEDED) {
16249                cleanUp();
16250            }
16251            return status;
16252        }
16253
16254        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16255            if (status != PackageManager.INSTALL_SUCCEEDED) {
16256                cleanUp();
16257                return false;
16258            }
16259
16260            final File targetDir = codeFile.getParentFile();
16261            final File beforeCodeFile = codeFile;
16262            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16263
16264            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16265            try {
16266                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16267            } catch (ErrnoException e) {
16268                Slog.w(TAG, "Failed to rename", e);
16269                return false;
16270            }
16271
16272            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16273                Slog.w(TAG, "Failed to restorecon");
16274                return false;
16275            }
16276
16277            // Reflect the rename internally
16278            codeFile = afterCodeFile;
16279            resourceFile = afterCodeFile;
16280
16281            // Reflect the rename in scanned details
16282            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16283            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16284                    afterCodeFile, pkg.baseCodePath));
16285            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16286                    afterCodeFile, pkg.splitCodePaths));
16287
16288            // Reflect the rename in app info
16289            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16290            pkg.setApplicationInfoCodePath(pkg.codePath);
16291            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16292            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16293            pkg.setApplicationInfoResourcePath(pkg.codePath);
16294            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16295            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16296
16297            return true;
16298        }
16299
16300        int doPostInstall(int status, int uid) {
16301            if (status != PackageManager.INSTALL_SUCCEEDED) {
16302                cleanUp();
16303            }
16304            return status;
16305        }
16306
16307        @Override
16308        String getCodePath() {
16309            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16310        }
16311
16312        @Override
16313        String getResourcePath() {
16314            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16315        }
16316
16317        private boolean cleanUp() {
16318            if (codeFile == null || !codeFile.exists()) {
16319                return false;
16320            }
16321
16322            removeCodePathLI(codeFile);
16323
16324            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16325                resourceFile.delete();
16326            }
16327
16328            return true;
16329        }
16330
16331        void cleanUpResourcesLI() {
16332            // Try enumerating all code paths before deleting
16333            List<String> allCodePaths = Collections.EMPTY_LIST;
16334            if (codeFile != null && codeFile.exists()) {
16335                try {
16336                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16337                    allCodePaths = pkg.getAllCodePaths();
16338                } catch (PackageParserException e) {
16339                    // Ignored; we tried our best
16340                }
16341            }
16342
16343            cleanUp();
16344            removeDexFiles(allCodePaths, instructionSets);
16345        }
16346
16347        boolean doPostDeleteLI(boolean delete) {
16348            // XXX err, shouldn't we respect the delete flag?
16349            cleanUpResourcesLI();
16350            return true;
16351        }
16352    }
16353
16354    private boolean isAsecExternal(String cid) {
16355        final String asecPath = PackageHelper.getSdFilesystem(cid);
16356        return !asecPath.startsWith(mAsecInternalPath);
16357    }
16358
16359    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16360            PackageManagerException {
16361        if (copyRet < 0) {
16362            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16363                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16364                throw new PackageManagerException(copyRet, message);
16365            }
16366        }
16367    }
16368
16369    /**
16370     * Extract the StorageManagerService "container ID" from the full code path of an
16371     * .apk.
16372     */
16373    static String cidFromCodePath(String fullCodePath) {
16374        int eidx = fullCodePath.lastIndexOf("/");
16375        String subStr1 = fullCodePath.substring(0, eidx);
16376        int sidx = subStr1.lastIndexOf("/");
16377        return subStr1.substring(sidx+1, eidx);
16378    }
16379
16380    /**
16381     * Logic to handle installation of ASEC applications, including copying and
16382     * renaming logic.
16383     */
16384    class AsecInstallArgs extends InstallArgs {
16385        static final String RES_FILE_NAME = "pkg.apk";
16386        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16387
16388        String cid;
16389        String packagePath;
16390        String resourcePath;
16391
16392        /** New install */
16393        AsecInstallArgs(InstallParams params) {
16394            super(params.origin, params.move, params.observer, params.installFlags,
16395                    params.installerPackageName, params.volumeUuid,
16396                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16397                    params.grantedRuntimePermissions,
16398                    params.traceMethod, params.traceCookie, params.certificates,
16399                    params.installReason);
16400        }
16401
16402        /** Existing install */
16403        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16404                        boolean isExternal, boolean isForwardLocked) {
16405            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16406                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16407                    instructionSets, null, null, null, 0, null /*certificates*/,
16408                    PackageManager.INSTALL_REASON_UNKNOWN);
16409            // Hackily pretend we're still looking at a full code path
16410            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16411                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16412            }
16413
16414            // Extract cid from fullCodePath
16415            int eidx = fullCodePath.lastIndexOf("/");
16416            String subStr1 = fullCodePath.substring(0, eidx);
16417            int sidx = subStr1.lastIndexOf("/");
16418            cid = subStr1.substring(sidx+1, eidx);
16419            setMountPath(subStr1);
16420        }
16421
16422        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16423            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16424                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16425                    instructionSets, null, null, null, 0, null /*certificates*/,
16426                    PackageManager.INSTALL_REASON_UNKNOWN);
16427            this.cid = cid;
16428            setMountPath(PackageHelper.getSdDir(cid));
16429        }
16430
16431        void createCopyFile() {
16432            cid = mInstallerService.allocateExternalStageCidLegacy();
16433        }
16434
16435        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16436            if (origin.staged && origin.cid != null) {
16437                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16438                cid = origin.cid;
16439                setMountPath(PackageHelper.getSdDir(cid));
16440                return PackageManager.INSTALL_SUCCEEDED;
16441            }
16442
16443            if (temp) {
16444                createCopyFile();
16445            } else {
16446                /*
16447                 * Pre-emptively destroy the container since it's destroyed if
16448                 * copying fails due to it existing anyway.
16449                 */
16450                PackageHelper.destroySdDir(cid);
16451            }
16452
16453            final String newMountPath = imcs.copyPackageToContainer(
16454                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16455                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16456
16457            if (newMountPath != null) {
16458                setMountPath(newMountPath);
16459                return PackageManager.INSTALL_SUCCEEDED;
16460            } else {
16461                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16462            }
16463        }
16464
16465        @Override
16466        String getCodePath() {
16467            return packagePath;
16468        }
16469
16470        @Override
16471        String getResourcePath() {
16472            return resourcePath;
16473        }
16474
16475        int doPreInstall(int status) {
16476            if (status != PackageManager.INSTALL_SUCCEEDED) {
16477                // Destroy container
16478                PackageHelper.destroySdDir(cid);
16479            } else {
16480                boolean mounted = PackageHelper.isContainerMounted(cid);
16481                if (!mounted) {
16482                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16483                            Process.SYSTEM_UID);
16484                    if (newMountPath != null) {
16485                        setMountPath(newMountPath);
16486                    } else {
16487                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16488                    }
16489                }
16490            }
16491            return status;
16492        }
16493
16494        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16495            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16496            String newMountPath = null;
16497            if (PackageHelper.isContainerMounted(cid)) {
16498                // Unmount the container
16499                if (!PackageHelper.unMountSdDir(cid)) {
16500                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16501                    return false;
16502                }
16503            }
16504            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16505                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16506                        " which might be stale. Will try to clean up.");
16507                // Clean up the stale container and proceed to recreate.
16508                if (!PackageHelper.destroySdDir(newCacheId)) {
16509                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16510                    return false;
16511                }
16512                // Successfully cleaned up stale container. Try to rename again.
16513                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16514                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16515                            + " inspite of cleaning it up.");
16516                    return false;
16517                }
16518            }
16519            if (!PackageHelper.isContainerMounted(newCacheId)) {
16520                Slog.w(TAG, "Mounting container " + newCacheId);
16521                newMountPath = PackageHelper.mountSdDir(newCacheId,
16522                        getEncryptKey(), Process.SYSTEM_UID);
16523            } else {
16524                newMountPath = PackageHelper.getSdDir(newCacheId);
16525            }
16526            if (newMountPath == null) {
16527                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16528                return false;
16529            }
16530            Log.i(TAG, "Succesfully renamed " + cid +
16531                    " to " + newCacheId +
16532                    " at new path: " + newMountPath);
16533            cid = newCacheId;
16534
16535            final File beforeCodeFile = new File(packagePath);
16536            setMountPath(newMountPath);
16537            final File afterCodeFile = new File(packagePath);
16538
16539            // Reflect the rename in scanned details
16540            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16541            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16542                    afterCodeFile, pkg.baseCodePath));
16543            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16544                    afterCodeFile, pkg.splitCodePaths));
16545
16546            // Reflect the rename in app info
16547            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16548            pkg.setApplicationInfoCodePath(pkg.codePath);
16549            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16550            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16551            pkg.setApplicationInfoResourcePath(pkg.codePath);
16552            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16553            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16554
16555            return true;
16556        }
16557
16558        private void setMountPath(String mountPath) {
16559            final File mountFile = new File(mountPath);
16560
16561            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16562            if (monolithicFile.exists()) {
16563                packagePath = monolithicFile.getAbsolutePath();
16564                if (isFwdLocked()) {
16565                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16566                } else {
16567                    resourcePath = packagePath;
16568                }
16569            } else {
16570                packagePath = mountFile.getAbsolutePath();
16571                resourcePath = packagePath;
16572            }
16573        }
16574
16575        int doPostInstall(int status, int uid) {
16576            if (status != PackageManager.INSTALL_SUCCEEDED) {
16577                cleanUp();
16578            } else {
16579                final int groupOwner;
16580                final String protectedFile;
16581                if (isFwdLocked()) {
16582                    groupOwner = UserHandle.getSharedAppGid(uid);
16583                    protectedFile = RES_FILE_NAME;
16584                } else {
16585                    groupOwner = -1;
16586                    protectedFile = null;
16587                }
16588
16589                if (uid < Process.FIRST_APPLICATION_UID
16590                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16591                    Slog.e(TAG, "Failed to finalize " + cid);
16592                    PackageHelper.destroySdDir(cid);
16593                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16594                }
16595
16596                boolean mounted = PackageHelper.isContainerMounted(cid);
16597                if (!mounted) {
16598                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16599                }
16600            }
16601            return status;
16602        }
16603
16604        private void cleanUp() {
16605            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16606
16607            // Destroy secure container
16608            PackageHelper.destroySdDir(cid);
16609        }
16610
16611        private List<String> getAllCodePaths() {
16612            final File codeFile = new File(getCodePath());
16613            if (codeFile != null && codeFile.exists()) {
16614                try {
16615                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16616                    return pkg.getAllCodePaths();
16617                } catch (PackageParserException e) {
16618                    // Ignored; we tried our best
16619                }
16620            }
16621            return Collections.EMPTY_LIST;
16622        }
16623
16624        void cleanUpResourcesLI() {
16625            // Enumerate all code paths before deleting
16626            cleanUpResourcesLI(getAllCodePaths());
16627        }
16628
16629        private void cleanUpResourcesLI(List<String> allCodePaths) {
16630            cleanUp();
16631            removeDexFiles(allCodePaths, instructionSets);
16632        }
16633
16634        String getPackageName() {
16635            return getAsecPackageName(cid);
16636        }
16637
16638        boolean doPostDeleteLI(boolean delete) {
16639            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16640            final List<String> allCodePaths = getAllCodePaths();
16641            boolean mounted = PackageHelper.isContainerMounted(cid);
16642            if (mounted) {
16643                // Unmount first
16644                if (PackageHelper.unMountSdDir(cid)) {
16645                    mounted = false;
16646                }
16647            }
16648            if (!mounted && delete) {
16649                cleanUpResourcesLI(allCodePaths);
16650            }
16651            return !mounted;
16652        }
16653
16654        @Override
16655        int doPreCopy() {
16656            if (isFwdLocked()) {
16657                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16658                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16659                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16660                }
16661            }
16662
16663            return PackageManager.INSTALL_SUCCEEDED;
16664        }
16665
16666        @Override
16667        int doPostCopy(int uid) {
16668            if (isFwdLocked()) {
16669                if (uid < Process.FIRST_APPLICATION_UID
16670                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16671                                RES_FILE_NAME)) {
16672                    Slog.e(TAG, "Failed to finalize " + cid);
16673                    PackageHelper.destroySdDir(cid);
16674                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16675                }
16676            }
16677
16678            return PackageManager.INSTALL_SUCCEEDED;
16679        }
16680    }
16681
16682    /**
16683     * Logic to handle movement of existing installed applications.
16684     */
16685    class MoveInstallArgs extends InstallArgs {
16686        private File codeFile;
16687        private File resourceFile;
16688
16689        /** New install */
16690        MoveInstallArgs(InstallParams params) {
16691            super(params.origin, params.move, params.observer, params.installFlags,
16692                    params.installerPackageName, params.volumeUuid,
16693                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16694                    params.grantedRuntimePermissions,
16695                    params.traceMethod, params.traceCookie, params.certificates,
16696                    params.installReason);
16697        }
16698
16699        int copyApk(IMediaContainerService imcs, boolean temp) {
16700            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16701                    + move.fromUuid + " to " + move.toUuid);
16702            synchronized (mInstaller) {
16703                try {
16704                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16705                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16706                } catch (InstallerException e) {
16707                    Slog.w(TAG, "Failed to move app", e);
16708                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16709                }
16710            }
16711
16712            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16713            resourceFile = codeFile;
16714            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16715
16716            return PackageManager.INSTALL_SUCCEEDED;
16717        }
16718
16719        int doPreInstall(int status) {
16720            if (status != PackageManager.INSTALL_SUCCEEDED) {
16721                cleanUp(move.toUuid);
16722            }
16723            return status;
16724        }
16725
16726        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16727            if (status != PackageManager.INSTALL_SUCCEEDED) {
16728                cleanUp(move.toUuid);
16729                return false;
16730            }
16731
16732            // Reflect the move in app info
16733            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16734            pkg.setApplicationInfoCodePath(pkg.codePath);
16735            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16736            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16737            pkg.setApplicationInfoResourcePath(pkg.codePath);
16738            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16739            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16740
16741            return true;
16742        }
16743
16744        int doPostInstall(int status, int uid) {
16745            if (status == PackageManager.INSTALL_SUCCEEDED) {
16746                cleanUp(move.fromUuid);
16747            } else {
16748                cleanUp(move.toUuid);
16749            }
16750            return status;
16751        }
16752
16753        @Override
16754        String getCodePath() {
16755            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16756        }
16757
16758        @Override
16759        String getResourcePath() {
16760            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16761        }
16762
16763        private boolean cleanUp(String volumeUuid) {
16764            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16765                    move.dataAppName);
16766            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16767            final int[] userIds = sUserManager.getUserIds();
16768            synchronized (mInstallLock) {
16769                // Clean up both app data and code
16770                // All package moves are frozen until finished
16771                for (int userId : userIds) {
16772                    try {
16773                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16774                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16775                    } catch (InstallerException e) {
16776                        Slog.w(TAG, String.valueOf(e));
16777                    }
16778                }
16779                removeCodePathLI(codeFile);
16780            }
16781            return true;
16782        }
16783
16784        void cleanUpResourcesLI() {
16785            throw new UnsupportedOperationException();
16786        }
16787
16788        boolean doPostDeleteLI(boolean delete) {
16789            throw new UnsupportedOperationException();
16790        }
16791    }
16792
16793    static String getAsecPackageName(String packageCid) {
16794        int idx = packageCid.lastIndexOf("-");
16795        if (idx == -1) {
16796            return packageCid;
16797        }
16798        return packageCid.substring(0, idx);
16799    }
16800
16801    // Utility method used to create code paths based on package name and available index.
16802    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16803        String idxStr = "";
16804        int idx = 1;
16805        // Fall back to default value of idx=1 if prefix is not
16806        // part of oldCodePath
16807        if (oldCodePath != null) {
16808            String subStr = oldCodePath;
16809            // Drop the suffix right away
16810            if (suffix != null && subStr.endsWith(suffix)) {
16811                subStr = subStr.substring(0, subStr.length() - suffix.length());
16812            }
16813            // If oldCodePath already contains prefix find out the
16814            // ending index to either increment or decrement.
16815            int sidx = subStr.lastIndexOf(prefix);
16816            if (sidx != -1) {
16817                subStr = subStr.substring(sidx + prefix.length());
16818                if (subStr != null) {
16819                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16820                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16821                    }
16822                    try {
16823                        idx = Integer.parseInt(subStr);
16824                        if (idx <= 1) {
16825                            idx++;
16826                        } else {
16827                            idx--;
16828                        }
16829                    } catch(NumberFormatException e) {
16830                    }
16831                }
16832            }
16833        }
16834        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16835        return prefix + idxStr;
16836    }
16837
16838    private File getNextCodePath(File targetDir, String packageName) {
16839        File result;
16840        SecureRandom random = new SecureRandom();
16841        byte[] bytes = new byte[16];
16842        do {
16843            random.nextBytes(bytes);
16844            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16845            result = new File(targetDir, packageName + "-" + suffix);
16846        } while (result.exists());
16847        return result;
16848    }
16849
16850    // Utility method that returns the relative package path with respect
16851    // to the installation directory. Like say for /data/data/com.test-1.apk
16852    // string com.test-1 is returned.
16853    static String deriveCodePathName(String codePath) {
16854        if (codePath == null) {
16855            return null;
16856        }
16857        final File codeFile = new File(codePath);
16858        final String name = codeFile.getName();
16859        if (codeFile.isDirectory()) {
16860            return name;
16861        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16862            final int lastDot = name.lastIndexOf('.');
16863            return name.substring(0, lastDot);
16864        } else {
16865            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16866            return null;
16867        }
16868    }
16869
16870    static class PackageInstalledInfo {
16871        String name;
16872        int uid;
16873        // The set of users that originally had this package installed.
16874        int[] origUsers;
16875        // The set of users that now have this package installed.
16876        int[] newUsers;
16877        PackageParser.Package pkg;
16878        int returnCode;
16879        String returnMsg;
16880        PackageRemovedInfo removedInfo;
16881        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16882
16883        public void setError(int code, String msg) {
16884            setReturnCode(code);
16885            setReturnMessage(msg);
16886            Slog.w(TAG, msg);
16887        }
16888
16889        public void setError(String msg, PackageParserException e) {
16890            setReturnCode(e.error);
16891            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16892            Slog.w(TAG, msg, e);
16893        }
16894
16895        public void setError(String msg, PackageManagerException e) {
16896            returnCode = e.error;
16897            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16898            Slog.w(TAG, msg, e);
16899        }
16900
16901        public void setReturnCode(int returnCode) {
16902            this.returnCode = returnCode;
16903            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16904            for (int i = 0; i < childCount; i++) {
16905                addedChildPackages.valueAt(i).returnCode = returnCode;
16906            }
16907        }
16908
16909        private void setReturnMessage(String returnMsg) {
16910            this.returnMsg = returnMsg;
16911            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16912            for (int i = 0; i < childCount; i++) {
16913                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16914            }
16915        }
16916
16917        // In some error cases we want to convey more info back to the observer
16918        String origPackage;
16919        String origPermission;
16920    }
16921
16922    /*
16923     * Install a non-existing package.
16924     */
16925    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16926            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16927            PackageInstalledInfo res, int installReason) {
16928        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16929
16930        // Remember this for later, in case we need to rollback this install
16931        String pkgName = pkg.packageName;
16932
16933        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16934
16935        synchronized(mPackages) {
16936            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16937            if (renamedPackage != null) {
16938                // A package with the same name is already installed, though
16939                // it has been renamed to an older name.  The package we
16940                // are trying to install should be installed as an update to
16941                // the existing one, but that has not been requested, so bail.
16942                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16943                        + " without first uninstalling package running as "
16944                        + renamedPackage);
16945                return;
16946            }
16947            if (mPackages.containsKey(pkgName)) {
16948                // Don't allow installation over an existing package with the same name.
16949                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16950                        + " without first uninstalling.");
16951                return;
16952            }
16953        }
16954
16955        try {
16956            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16957                    System.currentTimeMillis(), user);
16958
16959            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16960
16961            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16962                prepareAppDataAfterInstallLIF(newPackage);
16963
16964            } else {
16965                // Remove package from internal structures, but keep around any
16966                // data that might have already existed
16967                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16968                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16969            }
16970        } catch (PackageManagerException e) {
16971            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16972        }
16973
16974        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16975    }
16976
16977    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16978        // Can't rotate keys during boot or if sharedUser.
16979        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16980                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16981            return false;
16982        }
16983        // app is using upgradeKeySets; make sure all are valid
16984        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16985        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16986        for (int i = 0; i < upgradeKeySets.length; i++) {
16987            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16988                Slog.wtf(TAG, "Package "
16989                         + (oldPs.name != null ? oldPs.name : "<null>")
16990                         + " contains upgrade-key-set reference to unknown key-set: "
16991                         + upgradeKeySets[i]
16992                         + " reverting to signatures check.");
16993                return false;
16994            }
16995        }
16996        return true;
16997    }
16998
16999    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17000        // Upgrade keysets are being used.  Determine if new package has a superset of the
17001        // required keys.
17002        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17003        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17004        for (int i = 0; i < upgradeKeySets.length; i++) {
17005            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17006            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17007                return true;
17008            }
17009        }
17010        return false;
17011    }
17012
17013    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17014        try (DigestInputStream digestStream =
17015                new DigestInputStream(new FileInputStream(file), digest)) {
17016            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17017        }
17018    }
17019
17020    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17021            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17022            int installReason) {
17023        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17024
17025        final PackageParser.Package oldPackage;
17026        final PackageSetting ps;
17027        final String pkgName = pkg.packageName;
17028        final int[] allUsers;
17029        final int[] installedUsers;
17030
17031        synchronized(mPackages) {
17032            oldPackage = mPackages.get(pkgName);
17033            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17034
17035            // don't allow upgrade to target a release SDK from a pre-release SDK
17036            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17037                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17038            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17039                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17040            if (oldTargetsPreRelease
17041                    && !newTargetsPreRelease
17042                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17043                Slog.w(TAG, "Can't install package targeting released sdk");
17044                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17045                return;
17046            }
17047
17048            ps = mSettings.mPackages.get(pkgName);
17049
17050            // verify signatures are valid
17051            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17052                if (!checkUpgradeKeySetLP(ps, pkg)) {
17053                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17054                            "New package not signed by keys specified by upgrade-keysets: "
17055                                    + pkgName);
17056                    return;
17057                }
17058            } else {
17059                // default to original signature matching
17060                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17061                        != PackageManager.SIGNATURE_MATCH) {
17062                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17063                            "New package has a different signature: " + pkgName);
17064                    return;
17065                }
17066            }
17067
17068            // don't allow a system upgrade unless the upgrade hash matches
17069            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17070                byte[] digestBytes = null;
17071                try {
17072                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17073                    updateDigest(digest, new File(pkg.baseCodePath));
17074                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17075                        for (String path : pkg.splitCodePaths) {
17076                            updateDigest(digest, new File(path));
17077                        }
17078                    }
17079                    digestBytes = digest.digest();
17080                } catch (NoSuchAlgorithmException | IOException e) {
17081                    res.setError(INSTALL_FAILED_INVALID_APK,
17082                            "Could not compute hash: " + pkgName);
17083                    return;
17084                }
17085                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17086                    res.setError(INSTALL_FAILED_INVALID_APK,
17087                            "New package fails restrict-update check: " + pkgName);
17088                    return;
17089                }
17090                // retain upgrade restriction
17091                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17092            }
17093
17094            // Check for shared user id changes
17095            String invalidPackageName =
17096                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17097            if (invalidPackageName != null) {
17098                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17099                        "Package " + invalidPackageName + " tried to change user "
17100                                + oldPackage.mSharedUserId);
17101                return;
17102            }
17103
17104            // In case of rollback, remember per-user/profile install state
17105            allUsers = sUserManager.getUserIds();
17106            installedUsers = ps.queryInstalledUsers(allUsers, true);
17107
17108            // don't allow an upgrade from full to ephemeral
17109            if (isInstantApp) {
17110                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17111                    for (int currentUser : allUsers) {
17112                        if (!ps.getInstantApp(currentUser)) {
17113                            // can't downgrade from full to instant
17114                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17115                                    + " for user: " + currentUser);
17116                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17117                            return;
17118                        }
17119                    }
17120                } else if (!ps.getInstantApp(user.getIdentifier())) {
17121                    // can't downgrade from full to instant
17122                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17123                            + " for user: " + user.getIdentifier());
17124                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17125                    return;
17126                }
17127            }
17128        }
17129
17130        // Update what is removed
17131        res.removedInfo = new PackageRemovedInfo(this);
17132        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17133        res.removedInfo.removedPackage = oldPackage.packageName;
17134        res.removedInfo.installerPackageName = ps.installerPackageName;
17135        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17136        res.removedInfo.isUpdate = true;
17137        res.removedInfo.origUsers = installedUsers;
17138        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17139        for (int i = 0; i < installedUsers.length; i++) {
17140            final int userId = installedUsers[i];
17141            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17142        }
17143
17144        final int childCount = (oldPackage.childPackages != null)
17145                ? oldPackage.childPackages.size() : 0;
17146        for (int i = 0; i < childCount; i++) {
17147            boolean childPackageUpdated = false;
17148            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17149            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17150            if (res.addedChildPackages != null) {
17151                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17152                if (childRes != null) {
17153                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17154                    childRes.removedInfo.removedPackage = childPkg.packageName;
17155                    if (childPs != null) {
17156                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17157                    }
17158                    childRes.removedInfo.isUpdate = true;
17159                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17160                    childPackageUpdated = true;
17161                }
17162            }
17163            if (!childPackageUpdated) {
17164                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17165                childRemovedRes.removedPackage = childPkg.packageName;
17166                if (childPs != null) {
17167                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17168                }
17169                childRemovedRes.isUpdate = false;
17170                childRemovedRes.dataRemoved = true;
17171                synchronized (mPackages) {
17172                    if (childPs != null) {
17173                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17174                    }
17175                }
17176                if (res.removedInfo.removedChildPackages == null) {
17177                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17178                }
17179                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17180            }
17181        }
17182
17183        boolean sysPkg = (isSystemApp(oldPackage));
17184        if (sysPkg) {
17185            // Set the system/privileged flags as needed
17186            final boolean privileged =
17187                    (oldPackage.applicationInfo.privateFlags
17188                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17189            final int systemPolicyFlags = policyFlags
17190                    | PackageParser.PARSE_IS_SYSTEM
17191                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17192
17193            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17194                    user, allUsers, installerPackageName, res, installReason);
17195        } else {
17196            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17197                    user, allUsers, installerPackageName, res, installReason);
17198        }
17199    }
17200
17201    @Override
17202    public List<String> getPreviousCodePaths(String packageName) {
17203        final int callingUid = Binder.getCallingUid();
17204        final List<String> result = new ArrayList<>();
17205        if (getInstantAppPackageName(callingUid) != null) {
17206            return result;
17207        }
17208        final PackageSetting ps = mSettings.mPackages.get(packageName);
17209        if (ps != null
17210                && ps.oldCodePaths != null
17211                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17212            result.addAll(ps.oldCodePaths);
17213        }
17214        return result;
17215    }
17216
17217    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17218            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17219            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17220            int installReason) {
17221        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17222                + deletedPackage);
17223
17224        String pkgName = deletedPackage.packageName;
17225        boolean deletedPkg = true;
17226        boolean addedPkg = false;
17227        boolean updatedSettings = false;
17228        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17229        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17230                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17231
17232        final long origUpdateTime = (pkg.mExtras != null)
17233                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17234
17235        // First delete the existing package while retaining the data directory
17236        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17237                res.removedInfo, true, pkg)) {
17238            // If the existing package wasn't successfully deleted
17239            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17240            deletedPkg = false;
17241        } else {
17242            // Successfully deleted the old package; proceed with replace.
17243
17244            // If deleted package lived in a container, give users a chance to
17245            // relinquish resources before killing.
17246            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17247                if (DEBUG_INSTALL) {
17248                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17249                }
17250                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17251                final ArrayList<String> pkgList = new ArrayList<String>(1);
17252                pkgList.add(deletedPackage.applicationInfo.packageName);
17253                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17254            }
17255
17256            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17257                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17258            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17259
17260            try {
17261                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17262                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17263                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17264                        installReason);
17265
17266                // Update the in-memory copy of the previous code paths.
17267                PackageSetting ps = mSettings.mPackages.get(pkgName);
17268                if (!killApp) {
17269                    if (ps.oldCodePaths == null) {
17270                        ps.oldCodePaths = new ArraySet<>();
17271                    }
17272                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17273                    if (deletedPackage.splitCodePaths != null) {
17274                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17275                    }
17276                } else {
17277                    ps.oldCodePaths = null;
17278                }
17279                if (ps.childPackageNames != null) {
17280                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17281                        final String childPkgName = ps.childPackageNames.get(i);
17282                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17283                        childPs.oldCodePaths = ps.oldCodePaths;
17284                    }
17285                }
17286                // set instant app status, but, only if it's explicitly specified
17287                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17288                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17289                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17290                prepareAppDataAfterInstallLIF(newPackage);
17291                addedPkg = true;
17292                mDexManager.notifyPackageUpdated(newPackage.packageName,
17293                        newPackage.baseCodePath, newPackage.splitCodePaths);
17294            } catch (PackageManagerException e) {
17295                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17296            }
17297        }
17298
17299        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17300            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17301
17302            // Revert all internal state mutations and added folders for the failed install
17303            if (addedPkg) {
17304                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17305                        res.removedInfo, true, null);
17306            }
17307
17308            // Restore the old package
17309            if (deletedPkg) {
17310                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17311                File restoreFile = new File(deletedPackage.codePath);
17312                // Parse old package
17313                boolean oldExternal = isExternal(deletedPackage);
17314                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17315                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17316                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17317                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17318                try {
17319                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17320                            null);
17321                } catch (PackageManagerException e) {
17322                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17323                            + e.getMessage());
17324                    return;
17325                }
17326
17327                synchronized (mPackages) {
17328                    // Ensure the installer package name up to date
17329                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17330
17331                    // Update permissions for restored package
17332                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17333
17334                    mSettings.writeLPr();
17335                }
17336
17337                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17338            }
17339        } else {
17340            synchronized (mPackages) {
17341                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17342                if (ps != null) {
17343                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17344                    if (res.removedInfo.removedChildPackages != null) {
17345                        final int childCount = res.removedInfo.removedChildPackages.size();
17346                        // Iterate in reverse as we may modify the collection
17347                        for (int i = childCount - 1; i >= 0; i--) {
17348                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17349                            if (res.addedChildPackages.containsKey(childPackageName)) {
17350                                res.removedInfo.removedChildPackages.removeAt(i);
17351                            } else {
17352                                PackageRemovedInfo childInfo = res.removedInfo
17353                                        .removedChildPackages.valueAt(i);
17354                                childInfo.removedForAllUsers = mPackages.get(
17355                                        childInfo.removedPackage) == null;
17356                            }
17357                        }
17358                    }
17359                }
17360            }
17361        }
17362    }
17363
17364    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17365            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17366            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17367            int installReason) {
17368        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17369                + ", old=" + deletedPackage);
17370
17371        final boolean disabledSystem;
17372
17373        // Remove existing system package
17374        removePackageLI(deletedPackage, true);
17375
17376        synchronized (mPackages) {
17377            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17378        }
17379        if (!disabledSystem) {
17380            // We didn't need to disable the .apk as a current system package,
17381            // which means we are replacing another update that is already
17382            // installed.  We need to make sure to delete the older one's .apk.
17383            res.removedInfo.args = createInstallArgsForExisting(0,
17384                    deletedPackage.applicationInfo.getCodePath(),
17385                    deletedPackage.applicationInfo.getResourcePath(),
17386                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17387        } else {
17388            res.removedInfo.args = null;
17389        }
17390
17391        // Successfully disabled the old package. Now proceed with re-installation
17392        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17393                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17394        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17395
17396        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17397        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17398                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17399
17400        PackageParser.Package newPackage = null;
17401        try {
17402            // Add the package to the internal data structures
17403            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17404
17405            // Set the update and install times
17406            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17407            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17408                    System.currentTimeMillis());
17409
17410            // Update the package dynamic state if succeeded
17411            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17412                // Now that the install succeeded make sure we remove data
17413                // directories for any child package the update removed.
17414                final int deletedChildCount = (deletedPackage.childPackages != null)
17415                        ? deletedPackage.childPackages.size() : 0;
17416                final int newChildCount = (newPackage.childPackages != null)
17417                        ? newPackage.childPackages.size() : 0;
17418                for (int i = 0; i < deletedChildCount; i++) {
17419                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17420                    boolean childPackageDeleted = true;
17421                    for (int j = 0; j < newChildCount; j++) {
17422                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17423                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17424                            childPackageDeleted = false;
17425                            break;
17426                        }
17427                    }
17428                    if (childPackageDeleted) {
17429                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17430                                deletedChildPkg.packageName);
17431                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17432                            PackageRemovedInfo removedChildRes = res.removedInfo
17433                                    .removedChildPackages.get(deletedChildPkg.packageName);
17434                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17435                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17436                        }
17437                    }
17438                }
17439
17440                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17441                        installReason);
17442                prepareAppDataAfterInstallLIF(newPackage);
17443
17444                mDexManager.notifyPackageUpdated(newPackage.packageName,
17445                            newPackage.baseCodePath, newPackage.splitCodePaths);
17446            }
17447        } catch (PackageManagerException e) {
17448            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17449            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17450        }
17451
17452        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17453            // Re installation failed. Restore old information
17454            // Remove new pkg information
17455            if (newPackage != null) {
17456                removeInstalledPackageLI(newPackage, true);
17457            }
17458            // Add back the old system package
17459            try {
17460                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17461            } catch (PackageManagerException e) {
17462                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17463            }
17464
17465            synchronized (mPackages) {
17466                if (disabledSystem) {
17467                    enableSystemPackageLPw(deletedPackage);
17468                }
17469
17470                // Ensure the installer package name up to date
17471                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17472
17473                // Update permissions for restored package
17474                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17475
17476                mSettings.writeLPr();
17477            }
17478
17479            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17480                    + " after failed upgrade");
17481        }
17482    }
17483
17484    /**
17485     * Checks whether the parent or any of the child packages have a change shared
17486     * user. For a package to be a valid update the shred users of the parent and
17487     * the children should match. We may later support changing child shared users.
17488     * @param oldPkg The updated package.
17489     * @param newPkg The update package.
17490     * @return The shared user that change between the versions.
17491     */
17492    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17493            PackageParser.Package newPkg) {
17494        // Check parent shared user
17495        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17496            return newPkg.packageName;
17497        }
17498        // Check child shared users
17499        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17500        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17501        for (int i = 0; i < newChildCount; i++) {
17502            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17503            // If this child was present, did it have the same shared user?
17504            for (int j = 0; j < oldChildCount; j++) {
17505                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17506                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17507                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17508                    return newChildPkg.packageName;
17509                }
17510            }
17511        }
17512        return null;
17513    }
17514
17515    private void removeNativeBinariesLI(PackageSetting ps) {
17516        // Remove the lib path for the parent package
17517        if (ps != null) {
17518            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17519            // Remove the lib path for the child packages
17520            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17521            for (int i = 0; i < childCount; i++) {
17522                PackageSetting childPs = null;
17523                synchronized (mPackages) {
17524                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17525                }
17526                if (childPs != null) {
17527                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17528                            .legacyNativeLibraryPathString);
17529                }
17530            }
17531        }
17532    }
17533
17534    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17535        // Enable the parent package
17536        mSettings.enableSystemPackageLPw(pkg.packageName);
17537        // Enable the child packages
17538        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17539        for (int i = 0; i < childCount; i++) {
17540            PackageParser.Package childPkg = pkg.childPackages.get(i);
17541            mSettings.enableSystemPackageLPw(childPkg.packageName);
17542        }
17543    }
17544
17545    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17546            PackageParser.Package newPkg) {
17547        // Disable the parent package (parent always replaced)
17548        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17549        // Disable the child packages
17550        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17551        for (int i = 0; i < childCount; i++) {
17552            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17553            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17554            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17555        }
17556        return disabled;
17557    }
17558
17559    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17560            String installerPackageName) {
17561        // Enable the parent package
17562        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17563        // Enable the child packages
17564        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17565        for (int i = 0; i < childCount; i++) {
17566            PackageParser.Package childPkg = pkg.childPackages.get(i);
17567            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17568        }
17569    }
17570
17571    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17572        // Collect all used permissions in the UID
17573        ArraySet<String> usedPermissions = new ArraySet<>();
17574        final int packageCount = su.packages.size();
17575        for (int i = 0; i < packageCount; i++) {
17576            PackageSetting ps = su.packages.valueAt(i);
17577            if (ps.pkg == null) {
17578                continue;
17579            }
17580            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17581            for (int j = 0; j < requestedPermCount; j++) {
17582                String permission = ps.pkg.requestedPermissions.get(j);
17583                BasePermission bp = mSettings.mPermissions.get(permission);
17584                if (bp != null) {
17585                    usedPermissions.add(permission);
17586                }
17587            }
17588        }
17589
17590        PermissionsState permissionsState = su.getPermissionsState();
17591        // Prune install permissions
17592        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17593        final int installPermCount = installPermStates.size();
17594        for (int i = installPermCount - 1; i >= 0;  i--) {
17595            PermissionState permissionState = installPermStates.get(i);
17596            if (!usedPermissions.contains(permissionState.getName())) {
17597                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17598                if (bp != null) {
17599                    permissionsState.revokeInstallPermission(bp);
17600                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17601                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17602                }
17603            }
17604        }
17605
17606        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17607
17608        // Prune runtime permissions
17609        for (int userId : allUserIds) {
17610            List<PermissionState> runtimePermStates = permissionsState
17611                    .getRuntimePermissionStates(userId);
17612            final int runtimePermCount = runtimePermStates.size();
17613            for (int i = runtimePermCount - 1; i >= 0; i--) {
17614                PermissionState permissionState = runtimePermStates.get(i);
17615                if (!usedPermissions.contains(permissionState.getName())) {
17616                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17617                    if (bp != null) {
17618                        permissionsState.revokeRuntimePermission(bp, userId);
17619                        permissionsState.updatePermissionFlags(bp, userId,
17620                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17621                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17622                                runtimePermissionChangedUserIds, userId);
17623                    }
17624                }
17625            }
17626        }
17627
17628        return runtimePermissionChangedUserIds;
17629    }
17630
17631    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17632            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17633        // Update the parent package setting
17634        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17635                res, user, installReason);
17636        // Update the child packages setting
17637        final int childCount = (newPackage.childPackages != null)
17638                ? newPackage.childPackages.size() : 0;
17639        for (int i = 0; i < childCount; i++) {
17640            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17641            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17642            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17643                    childRes.origUsers, childRes, user, installReason);
17644        }
17645    }
17646
17647    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17648            String installerPackageName, int[] allUsers, int[] installedForUsers,
17649            PackageInstalledInfo res, UserHandle user, int installReason) {
17650        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17651
17652        String pkgName = newPackage.packageName;
17653        synchronized (mPackages) {
17654            //write settings. the installStatus will be incomplete at this stage.
17655            //note that the new package setting would have already been
17656            //added to mPackages. It hasn't been persisted yet.
17657            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17658            // TODO: Remove this write? It's also written at the end of this method
17659            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17660            mSettings.writeLPr();
17661            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17662        }
17663
17664        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17665        synchronized (mPackages) {
17666            updatePermissionsLPw(newPackage.packageName, newPackage,
17667                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17668                            ? UPDATE_PERMISSIONS_ALL : 0));
17669            // For system-bundled packages, we assume that installing an upgraded version
17670            // of the package implies that the user actually wants to run that new code,
17671            // so we enable the package.
17672            PackageSetting ps = mSettings.mPackages.get(pkgName);
17673            final int userId = user.getIdentifier();
17674            if (ps != null) {
17675                if (isSystemApp(newPackage)) {
17676                    if (DEBUG_INSTALL) {
17677                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17678                    }
17679                    // Enable system package for requested users
17680                    if (res.origUsers != null) {
17681                        for (int origUserId : res.origUsers) {
17682                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17683                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17684                                        origUserId, installerPackageName);
17685                            }
17686                        }
17687                    }
17688                    // Also convey the prior install/uninstall state
17689                    if (allUsers != null && installedForUsers != null) {
17690                        for (int currentUserId : allUsers) {
17691                            final boolean installed = ArrayUtils.contains(
17692                                    installedForUsers, currentUserId);
17693                            if (DEBUG_INSTALL) {
17694                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17695                            }
17696                            ps.setInstalled(installed, currentUserId);
17697                        }
17698                        // these install state changes will be persisted in the
17699                        // upcoming call to mSettings.writeLPr().
17700                    }
17701                }
17702                // It's implied that when a user requests installation, they want the app to be
17703                // installed and enabled.
17704                if (userId != UserHandle.USER_ALL) {
17705                    ps.setInstalled(true, userId);
17706                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17707                }
17708
17709                // When replacing an existing package, preserve the original install reason for all
17710                // users that had the package installed before.
17711                final Set<Integer> previousUserIds = new ArraySet<>();
17712                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17713                    final int installReasonCount = res.removedInfo.installReasons.size();
17714                    for (int i = 0; i < installReasonCount; i++) {
17715                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17716                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17717                        ps.setInstallReason(previousInstallReason, previousUserId);
17718                        previousUserIds.add(previousUserId);
17719                    }
17720                }
17721
17722                // Set install reason for users that are having the package newly installed.
17723                if (userId == UserHandle.USER_ALL) {
17724                    for (int currentUserId : sUserManager.getUserIds()) {
17725                        if (!previousUserIds.contains(currentUserId)) {
17726                            ps.setInstallReason(installReason, currentUserId);
17727                        }
17728                    }
17729                } else if (!previousUserIds.contains(userId)) {
17730                    ps.setInstallReason(installReason, userId);
17731                }
17732                mSettings.writeKernelMappingLPr(ps);
17733            }
17734            res.name = pkgName;
17735            res.uid = newPackage.applicationInfo.uid;
17736            res.pkg = newPackage;
17737            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17738            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17739            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17740            //to update install status
17741            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17742            mSettings.writeLPr();
17743            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17744        }
17745
17746        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17747    }
17748
17749    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17750        try {
17751            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17752            installPackageLI(args, res);
17753        } finally {
17754            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17755        }
17756    }
17757
17758    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17759        final int installFlags = args.installFlags;
17760        final String installerPackageName = args.installerPackageName;
17761        final String volumeUuid = args.volumeUuid;
17762        final File tmpPackageFile = new File(args.getCodePath());
17763        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17764        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17765                || (args.volumeUuid != null));
17766        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17767        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17768        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17769        boolean replace = false;
17770        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17771        if (args.move != null) {
17772            // moving a complete application; perform an initial scan on the new install location
17773            scanFlags |= SCAN_INITIAL;
17774        }
17775        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17776            scanFlags |= SCAN_DONT_KILL_APP;
17777        }
17778        if (instantApp) {
17779            scanFlags |= SCAN_AS_INSTANT_APP;
17780        }
17781        if (fullApp) {
17782            scanFlags |= SCAN_AS_FULL_APP;
17783        }
17784
17785        // Result object to be returned
17786        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17787
17788        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17789
17790        // Sanity check
17791        if (instantApp && (forwardLocked || onExternal)) {
17792            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17793                    + " external=" + onExternal);
17794            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17795            return;
17796        }
17797
17798        // Retrieve PackageSettings and parse package
17799        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17800                | PackageParser.PARSE_ENFORCE_CODE
17801                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17802                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17803                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17804                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17805        PackageParser pp = new PackageParser();
17806        pp.setSeparateProcesses(mSeparateProcesses);
17807        pp.setDisplayMetrics(mMetrics);
17808        pp.setCallback(mPackageParserCallback);
17809
17810        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17811        final PackageParser.Package pkg;
17812        try {
17813            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17814        } catch (PackageParserException e) {
17815            res.setError("Failed parse during installPackageLI", e);
17816            return;
17817        } finally {
17818            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17819        }
17820
17821        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17822        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17823            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17824            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17825                    "Instant app package must target O");
17826            return;
17827        }
17828        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17829            Slog.w(TAG, "Instant app package " + pkg.packageName
17830                    + " does not target targetSandboxVersion 2");
17831            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17832                    "Instant app package must use targetSanboxVersion 2");
17833            return;
17834        }
17835
17836        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17837            // Static shared libraries have synthetic package names
17838            renameStaticSharedLibraryPackage(pkg);
17839
17840            // No static shared libs on external storage
17841            if (onExternal) {
17842                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17843                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17844                        "Packages declaring static-shared libs cannot be updated");
17845                return;
17846            }
17847        }
17848
17849        // If we are installing a clustered package add results for the children
17850        if (pkg.childPackages != null) {
17851            synchronized (mPackages) {
17852                final int childCount = pkg.childPackages.size();
17853                for (int i = 0; i < childCount; i++) {
17854                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17855                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17856                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17857                    childRes.pkg = childPkg;
17858                    childRes.name = childPkg.packageName;
17859                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17860                    if (childPs != null) {
17861                        childRes.origUsers = childPs.queryInstalledUsers(
17862                                sUserManager.getUserIds(), true);
17863                    }
17864                    if ((mPackages.containsKey(childPkg.packageName))) {
17865                        childRes.removedInfo = new PackageRemovedInfo(this);
17866                        childRes.removedInfo.removedPackage = childPkg.packageName;
17867                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17868                    }
17869                    if (res.addedChildPackages == null) {
17870                        res.addedChildPackages = new ArrayMap<>();
17871                    }
17872                    res.addedChildPackages.put(childPkg.packageName, childRes);
17873                }
17874            }
17875        }
17876
17877        // If package doesn't declare API override, mark that we have an install
17878        // time CPU ABI override.
17879        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17880            pkg.cpuAbiOverride = args.abiOverride;
17881        }
17882
17883        String pkgName = res.name = pkg.packageName;
17884        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17885            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17886                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17887                return;
17888            }
17889        }
17890
17891        try {
17892            // either use what we've been given or parse directly from the APK
17893            if (args.certificates != null) {
17894                try {
17895                    PackageParser.populateCertificates(pkg, args.certificates);
17896                } catch (PackageParserException e) {
17897                    // there was something wrong with the certificates we were given;
17898                    // try to pull them from the APK
17899                    PackageParser.collectCertificates(pkg, parseFlags);
17900                }
17901            } else {
17902                PackageParser.collectCertificates(pkg, parseFlags);
17903            }
17904        } catch (PackageParserException e) {
17905            res.setError("Failed collect during installPackageLI", e);
17906            return;
17907        }
17908
17909        // Get rid of all references to package scan path via parser.
17910        pp = null;
17911        String oldCodePath = null;
17912        boolean systemApp = false;
17913        synchronized (mPackages) {
17914            // Check if installing already existing package
17915            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17916                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17917                if (pkg.mOriginalPackages != null
17918                        && pkg.mOriginalPackages.contains(oldName)
17919                        && mPackages.containsKey(oldName)) {
17920                    // This package is derived from an original package,
17921                    // and this device has been updating from that original
17922                    // name.  We must continue using the original name, so
17923                    // rename the new package here.
17924                    pkg.setPackageName(oldName);
17925                    pkgName = pkg.packageName;
17926                    replace = true;
17927                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17928                            + oldName + " pkgName=" + pkgName);
17929                } else if (mPackages.containsKey(pkgName)) {
17930                    // This package, under its official name, already exists
17931                    // on the device; we should replace it.
17932                    replace = true;
17933                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17934                }
17935
17936                // Child packages are installed through the parent package
17937                if (pkg.parentPackage != null) {
17938                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17939                            "Package " + pkg.packageName + " is child of package "
17940                                    + pkg.parentPackage.parentPackage + ". Child packages "
17941                                    + "can be updated only through the parent package.");
17942                    return;
17943                }
17944
17945                if (replace) {
17946                    // Prevent apps opting out from runtime permissions
17947                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17948                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17949                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17950                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17951                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17952                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17953                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17954                                        + " doesn't support runtime permissions but the old"
17955                                        + " target SDK " + oldTargetSdk + " does.");
17956                        return;
17957                    }
17958                    // Prevent apps from downgrading their targetSandbox.
17959                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17960                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17961                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17962                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17963                                "Package " + pkg.packageName + " new target sandbox "
17964                                + newTargetSandbox + " is incompatible with the previous value of"
17965                                + oldTargetSandbox + ".");
17966                        return;
17967                    }
17968
17969                    // Prevent installing of child packages
17970                    if (oldPackage.parentPackage != null) {
17971                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17972                                "Package " + pkg.packageName + " is child of package "
17973                                        + oldPackage.parentPackage + ". Child packages "
17974                                        + "can be updated only through the parent package.");
17975                        return;
17976                    }
17977                }
17978            }
17979
17980            PackageSetting ps = mSettings.mPackages.get(pkgName);
17981            if (ps != null) {
17982                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17983
17984                // Static shared libs have same package with different versions where
17985                // we internally use a synthetic package name to allow multiple versions
17986                // of the same package, therefore we need to compare signatures against
17987                // the package setting for the latest library version.
17988                PackageSetting signatureCheckPs = ps;
17989                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17990                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17991                    if (libraryEntry != null) {
17992                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17993                    }
17994                }
17995
17996                // Quick sanity check that we're signed correctly if updating;
17997                // we'll check this again later when scanning, but we want to
17998                // bail early here before tripping over redefined permissions.
17999                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18000                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18001                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18002                                + pkg.packageName + " upgrade keys do not match the "
18003                                + "previously installed version");
18004                        return;
18005                    }
18006                } else {
18007                    try {
18008                        verifySignaturesLP(signatureCheckPs, pkg);
18009                    } catch (PackageManagerException e) {
18010                        res.setError(e.error, e.getMessage());
18011                        return;
18012                    }
18013                }
18014
18015                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18016                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18017                    systemApp = (ps.pkg.applicationInfo.flags &
18018                            ApplicationInfo.FLAG_SYSTEM) != 0;
18019                }
18020                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18021            }
18022
18023            int N = pkg.permissions.size();
18024            for (int i = N-1; i >= 0; i--) {
18025                PackageParser.Permission perm = pkg.permissions.get(i);
18026                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18027
18028                // Don't allow anyone but the system to define ephemeral permissions.
18029                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18030                        && !systemApp) {
18031                    Slog.w(TAG, "Non-System package " + pkg.packageName
18032                            + " attempting to delcare ephemeral permission "
18033                            + perm.info.name + "; Removing ephemeral.");
18034                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18035                }
18036                // Check whether the newly-scanned package wants to define an already-defined perm
18037                if (bp != null) {
18038                    // If the defining package is signed with our cert, it's okay.  This
18039                    // also includes the "updating the same package" case, of course.
18040                    // "updating same package" could also involve key-rotation.
18041                    final boolean sigsOk;
18042                    if (bp.sourcePackage.equals(pkg.packageName)
18043                            && (bp.packageSetting instanceof PackageSetting)
18044                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18045                                    scanFlags))) {
18046                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18047                    } else {
18048                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18049                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18050                    }
18051                    if (!sigsOk) {
18052                        // If the owning package is the system itself, we log but allow
18053                        // install to proceed; we fail the install on all other permission
18054                        // redefinitions.
18055                        if (!bp.sourcePackage.equals("android")) {
18056                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18057                                    + pkg.packageName + " attempting to redeclare permission "
18058                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18059                            res.origPermission = perm.info.name;
18060                            res.origPackage = bp.sourcePackage;
18061                            return;
18062                        } else {
18063                            Slog.w(TAG, "Package " + pkg.packageName
18064                                    + " attempting to redeclare system permission "
18065                                    + perm.info.name + "; ignoring new declaration");
18066                            pkg.permissions.remove(i);
18067                        }
18068                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18069                        // Prevent apps to change protection level to dangerous from any other
18070                        // type as this would allow a privilege escalation where an app adds a
18071                        // normal/signature permission in other app's group and later redefines
18072                        // it as dangerous leading to the group auto-grant.
18073                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18074                                == PermissionInfo.PROTECTION_DANGEROUS) {
18075                            if (bp != null && !bp.isRuntime()) {
18076                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18077                                        + "non-runtime permission " + perm.info.name
18078                                        + " to runtime; keeping old protection level");
18079                                perm.info.protectionLevel = bp.protectionLevel;
18080                            }
18081                        }
18082                    }
18083                }
18084            }
18085        }
18086
18087        if (systemApp) {
18088            if (onExternal) {
18089                // Abort update; system app can't be replaced with app on sdcard
18090                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18091                        "Cannot install updates to system apps on sdcard");
18092                return;
18093            } else if (instantApp) {
18094                // Abort update; system app can't be replaced with an instant app
18095                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18096                        "Cannot update a system app with an instant app");
18097                return;
18098            }
18099        }
18100
18101        if (args.move != null) {
18102            // We did an in-place move, so dex is ready to roll
18103            scanFlags |= SCAN_NO_DEX;
18104            scanFlags |= SCAN_MOVE;
18105
18106            synchronized (mPackages) {
18107                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18108                if (ps == null) {
18109                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18110                            "Missing settings for moved package " + pkgName);
18111                }
18112
18113                // We moved the entire application as-is, so bring over the
18114                // previously derived ABI information.
18115                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18116                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18117            }
18118
18119        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18120            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18121            scanFlags |= SCAN_NO_DEX;
18122
18123            try {
18124                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18125                    args.abiOverride : pkg.cpuAbiOverride);
18126                final boolean extractNativeLibs = !pkg.isLibrary();
18127                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18128                        extractNativeLibs, mAppLib32InstallDir);
18129            } catch (PackageManagerException pme) {
18130                Slog.e(TAG, "Error deriving application ABI", pme);
18131                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18132                return;
18133            }
18134
18135            // Shared libraries for the package need to be updated.
18136            synchronized (mPackages) {
18137                try {
18138                    updateSharedLibrariesLPr(pkg, null);
18139                } catch (PackageManagerException e) {
18140                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18141                }
18142            }
18143
18144            // dexopt can take some time to complete, so, for instant apps, we skip this
18145            // step during installation. Instead, we'll take extra time the first time the
18146            // instant app starts. It's preferred to do it this way to provide continuous
18147            // progress to the user instead of mysteriously blocking somewhere in the
18148            // middle of running an instant app. The default behaviour can be overridden
18149            // via gservices.
18150            if (!instantApp || Global.getInt(
18151                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18152                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18153                // Do not run PackageDexOptimizer through the local performDexOpt
18154                // method because `pkg` may not be in `mPackages` yet.
18155                //
18156                // Also, don't fail application installs if the dexopt step fails.
18157                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18158                        null /* instructionSets */, false /* checkProfiles */,
18159                        getCompilerFilterForReason(REASON_INSTALL),
18160                        getOrCreateCompilerPackageStats(pkg),
18161                        mDexManager.isUsedByOtherApps(pkg.packageName),
18162                        true /* bootComplete */);
18163                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18164            }
18165
18166            // Notify BackgroundDexOptService that the package has been changed.
18167            // If this is an update of a package which used to fail to compile,
18168            // BDOS will remove it from its blacklist.
18169            // TODO: Layering violation
18170            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18171        }
18172
18173        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18174            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18175            return;
18176        }
18177
18178        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18179
18180        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18181                "installPackageLI")) {
18182            if (replace) {
18183                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18184                    // Static libs have a synthetic package name containing the version
18185                    // and cannot be updated as an update would get a new package name,
18186                    // unless this is the exact same version code which is useful for
18187                    // development.
18188                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18189                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18190                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18191                                + "static-shared libs cannot be updated");
18192                        return;
18193                    }
18194                }
18195                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18196                        installerPackageName, res, args.installReason);
18197            } else {
18198                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18199                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18200            }
18201        }
18202
18203        synchronized (mPackages) {
18204            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18205            if (ps != null) {
18206                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18207                ps.setUpdateAvailable(false /*updateAvailable*/);
18208            }
18209
18210            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18211            for (int i = 0; i < childCount; i++) {
18212                PackageParser.Package childPkg = pkg.childPackages.get(i);
18213                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18214                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18215                if (childPs != null) {
18216                    childRes.newUsers = childPs.queryInstalledUsers(
18217                            sUserManager.getUserIds(), true);
18218                }
18219            }
18220
18221            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18222                updateSequenceNumberLP(ps, res.newUsers);
18223                updateInstantAppInstallerLocked(pkgName);
18224            }
18225        }
18226    }
18227
18228    private void startIntentFilterVerifications(int userId, boolean replacing,
18229            PackageParser.Package pkg) {
18230        if (mIntentFilterVerifierComponent == null) {
18231            Slog.w(TAG, "No IntentFilter verification will not be done as "
18232                    + "there is no IntentFilterVerifier available!");
18233            return;
18234        }
18235
18236        final int verifierUid = getPackageUid(
18237                mIntentFilterVerifierComponent.getPackageName(),
18238                MATCH_DEBUG_TRIAGED_MISSING,
18239                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18240
18241        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18242        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18243        mHandler.sendMessage(msg);
18244
18245        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18246        for (int i = 0; i < childCount; i++) {
18247            PackageParser.Package childPkg = pkg.childPackages.get(i);
18248            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18249            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18250            mHandler.sendMessage(msg);
18251        }
18252    }
18253
18254    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18255            PackageParser.Package pkg) {
18256        int size = pkg.activities.size();
18257        if (size == 0) {
18258            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18259                    "No activity, so no need to verify any IntentFilter!");
18260            return;
18261        }
18262
18263        final boolean hasDomainURLs = hasDomainURLs(pkg);
18264        if (!hasDomainURLs) {
18265            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18266                    "No domain URLs, so no need to verify any IntentFilter!");
18267            return;
18268        }
18269
18270        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18271                + " if any IntentFilter from the " + size
18272                + " Activities needs verification ...");
18273
18274        int count = 0;
18275        final String packageName = pkg.packageName;
18276
18277        synchronized (mPackages) {
18278            // If this is a new install and we see that we've already run verification for this
18279            // package, we have nothing to do: it means the state was restored from backup.
18280            if (!replacing) {
18281                IntentFilterVerificationInfo ivi =
18282                        mSettings.getIntentFilterVerificationLPr(packageName);
18283                if (ivi != null) {
18284                    if (DEBUG_DOMAIN_VERIFICATION) {
18285                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18286                                + ivi.getStatusString());
18287                    }
18288                    return;
18289                }
18290            }
18291
18292            // If any filters need to be verified, then all need to be.
18293            boolean needToVerify = false;
18294            for (PackageParser.Activity a : pkg.activities) {
18295                for (ActivityIntentInfo filter : a.intents) {
18296                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18297                        if (DEBUG_DOMAIN_VERIFICATION) {
18298                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18299                        }
18300                        needToVerify = true;
18301                        break;
18302                    }
18303                }
18304            }
18305
18306            if (needToVerify) {
18307                final int verificationId = mIntentFilterVerificationToken++;
18308                for (PackageParser.Activity a : pkg.activities) {
18309                    for (ActivityIntentInfo filter : a.intents) {
18310                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18311                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18312                                    "Verification needed for IntentFilter:" + filter.toString());
18313                            mIntentFilterVerifier.addOneIntentFilterVerification(
18314                                    verifierUid, userId, verificationId, filter, packageName);
18315                            count++;
18316                        }
18317                    }
18318                }
18319            }
18320        }
18321
18322        if (count > 0) {
18323            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18324                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18325                    +  " for userId:" + userId);
18326            mIntentFilterVerifier.startVerifications(userId);
18327        } else {
18328            if (DEBUG_DOMAIN_VERIFICATION) {
18329                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18330            }
18331        }
18332    }
18333
18334    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18335        final ComponentName cn  = filter.activity.getComponentName();
18336        final String packageName = cn.getPackageName();
18337
18338        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18339                packageName);
18340        if (ivi == null) {
18341            return true;
18342        }
18343        int status = ivi.getStatus();
18344        switch (status) {
18345            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18346            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18347                return true;
18348
18349            default:
18350                // Nothing to do
18351                return false;
18352        }
18353    }
18354
18355    private static boolean isMultiArch(ApplicationInfo info) {
18356        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18357    }
18358
18359    private static boolean isExternal(PackageParser.Package pkg) {
18360        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18361    }
18362
18363    private static boolean isExternal(PackageSetting ps) {
18364        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18365    }
18366
18367    private static boolean isSystemApp(PackageParser.Package pkg) {
18368        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18369    }
18370
18371    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18372        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18373    }
18374
18375    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18376        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18377    }
18378
18379    private static boolean isSystemApp(PackageSetting ps) {
18380        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18381    }
18382
18383    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18384        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18385    }
18386
18387    private int packageFlagsToInstallFlags(PackageSetting ps) {
18388        int installFlags = 0;
18389        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18390            // This existing package was an external ASEC install when we have
18391            // the external flag without a UUID
18392            installFlags |= PackageManager.INSTALL_EXTERNAL;
18393        }
18394        if (ps.isForwardLocked()) {
18395            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18396        }
18397        return installFlags;
18398    }
18399
18400    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18401        if (isExternal(pkg)) {
18402            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18403                return StorageManager.UUID_PRIMARY_PHYSICAL;
18404            } else {
18405                return pkg.volumeUuid;
18406            }
18407        } else {
18408            return StorageManager.UUID_PRIVATE_INTERNAL;
18409        }
18410    }
18411
18412    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18413        if (isExternal(pkg)) {
18414            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18415                return mSettings.getExternalVersion();
18416            } else {
18417                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18418            }
18419        } else {
18420            return mSettings.getInternalVersion();
18421        }
18422    }
18423
18424    private void deleteTempPackageFiles() {
18425        final FilenameFilter filter = new FilenameFilter() {
18426            public boolean accept(File dir, String name) {
18427                return name.startsWith("vmdl") && name.endsWith(".tmp");
18428            }
18429        };
18430        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18431            file.delete();
18432        }
18433    }
18434
18435    @Override
18436    public void deletePackageAsUser(String packageName, int versionCode,
18437            IPackageDeleteObserver observer, int userId, int flags) {
18438        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18439                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18440    }
18441
18442    @Override
18443    public void deletePackageVersioned(VersionedPackage versionedPackage,
18444            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18445        final int callingUid = Binder.getCallingUid();
18446        mContext.enforceCallingOrSelfPermission(
18447                android.Manifest.permission.DELETE_PACKAGES, null);
18448        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18449        Preconditions.checkNotNull(versionedPackage);
18450        Preconditions.checkNotNull(observer);
18451        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18452                PackageManager.VERSION_CODE_HIGHEST,
18453                Integer.MAX_VALUE, "versionCode must be >= -1");
18454
18455        final String packageName = versionedPackage.getPackageName();
18456        final int versionCode = versionedPackage.getVersionCode();
18457        final String internalPackageName;
18458        synchronized (mPackages) {
18459            // Normalize package name to handle renamed packages and static libs
18460            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18461                    versionedPackage.getVersionCode());
18462        }
18463
18464        final int uid = Binder.getCallingUid();
18465        if (!isOrphaned(internalPackageName)
18466                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18467            try {
18468                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18469                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18470                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18471                observer.onUserActionRequired(intent);
18472            } catch (RemoteException re) {
18473            }
18474            return;
18475        }
18476        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18477        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18478        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18479            mContext.enforceCallingOrSelfPermission(
18480                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18481                    "deletePackage for user " + userId);
18482        }
18483
18484        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18485            try {
18486                observer.onPackageDeleted(packageName,
18487                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18488            } catch (RemoteException re) {
18489            }
18490            return;
18491        }
18492
18493        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18494            try {
18495                observer.onPackageDeleted(packageName,
18496                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18497            } catch (RemoteException re) {
18498            }
18499            return;
18500        }
18501
18502        if (DEBUG_REMOVE) {
18503            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18504                    + " deleteAllUsers: " + deleteAllUsers + " version="
18505                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18506                    ? "VERSION_CODE_HIGHEST" : versionCode));
18507        }
18508        // Queue up an async operation since the package deletion may take a little while.
18509        mHandler.post(new Runnable() {
18510            public void run() {
18511                mHandler.removeCallbacks(this);
18512                int returnCode;
18513                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18514                boolean doDeletePackage = true;
18515                if (ps != null) {
18516                    final boolean targetIsInstantApp =
18517                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18518                    doDeletePackage = !targetIsInstantApp
18519                            || canViewInstantApps;
18520                }
18521                if (doDeletePackage) {
18522                    if (!deleteAllUsers) {
18523                        returnCode = deletePackageX(internalPackageName, versionCode,
18524                                userId, deleteFlags);
18525                    } else {
18526                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18527                                internalPackageName, users);
18528                        // If nobody is blocking uninstall, proceed with delete for all users
18529                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18530                            returnCode = deletePackageX(internalPackageName, versionCode,
18531                                    userId, deleteFlags);
18532                        } else {
18533                            // Otherwise uninstall individually for users with blockUninstalls=false
18534                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18535                            for (int userId : users) {
18536                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18537                                    returnCode = deletePackageX(internalPackageName, versionCode,
18538                                            userId, userFlags);
18539                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18540                                        Slog.w(TAG, "Package delete failed for user " + userId
18541                                                + ", returnCode " + returnCode);
18542                                    }
18543                                }
18544                            }
18545                            // The app has only been marked uninstalled for certain users.
18546                            // We still need to report that delete was blocked
18547                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18548                        }
18549                    }
18550                } else {
18551                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18552                }
18553                try {
18554                    observer.onPackageDeleted(packageName, returnCode, null);
18555                } catch (RemoteException e) {
18556                    Log.i(TAG, "Observer no longer exists.");
18557                } //end catch
18558            } //end run
18559        });
18560    }
18561
18562    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18563        if (pkg.staticSharedLibName != null) {
18564            return pkg.manifestPackageName;
18565        }
18566        return pkg.packageName;
18567    }
18568
18569    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18570        // Handle renamed packages
18571        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18572        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18573
18574        // Is this a static library?
18575        SparseArray<SharedLibraryEntry> versionedLib =
18576                mStaticLibsByDeclaringPackage.get(packageName);
18577        if (versionedLib == null || versionedLib.size() <= 0) {
18578            return packageName;
18579        }
18580
18581        // Figure out which lib versions the caller can see
18582        SparseIntArray versionsCallerCanSee = null;
18583        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18584        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18585                && callingAppId != Process.ROOT_UID) {
18586            versionsCallerCanSee = new SparseIntArray();
18587            String libName = versionedLib.valueAt(0).info.getName();
18588            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18589            if (uidPackages != null) {
18590                for (String uidPackage : uidPackages) {
18591                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18592                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18593                    if (libIdx >= 0) {
18594                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18595                        versionsCallerCanSee.append(libVersion, libVersion);
18596                    }
18597                }
18598            }
18599        }
18600
18601        // Caller can see nothing - done
18602        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18603            return packageName;
18604        }
18605
18606        // Find the version the caller can see and the app version code
18607        SharedLibraryEntry highestVersion = null;
18608        final int versionCount = versionedLib.size();
18609        for (int i = 0; i < versionCount; i++) {
18610            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18611            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18612                    libEntry.info.getVersion()) < 0) {
18613                continue;
18614            }
18615            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18616            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18617                if (libVersionCode == versionCode) {
18618                    return libEntry.apk;
18619                }
18620            } else if (highestVersion == null) {
18621                highestVersion = libEntry;
18622            } else if (libVersionCode  > highestVersion.info
18623                    .getDeclaringPackage().getVersionCode()) {
18624                highestVersion = libEntry;
18625            }
18626        }
18627
18628        if (highestVersion != null) {
18629            return highestVersion.apk;
18630        }
18631
18632        return packageName;
18633    }
18634
18635    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18636        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18637              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18638            return true;
18639        }
18640        final int callingUserId = UserHandle.getUserId(callingUid);
18641        // If the caller installed the pkgName, then allow it to silently uninstall.
18642        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18643            return true;
18644        }
18645
18646        // Allow package verifier to silently uninstall.
18647        if (mRequiredVerifierPackage != null &&
18648                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18649            return true;
18650        }
18651
18652        // Allow package uninstaller to silently uninstall.
18653        if (mRequiredUninstallerPackage != null &&
18654                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18655            return true;
18656        }
18657
18658        // Allow storage manager to silently uninstall.
18659        if (mStorageManagerPackage != null &&
18660                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18661            return true;
18662        }
18663
18664        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18665        // uninstall for device owner provisioning.
18666        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18667                == PERMISSION_GRANTED) {
18668            return true;
18669        }
18670
18671        return false;
18672    }
18673
18674    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18675        int[] result = EMPTY_INT_ARRAY;
18676        for (int userId : userIds) {
18677            if (getBlockUninstallForUser(packageName, userId)) {
18678                result = ArrayUtils.appendInt(result, userId);
18679            }
18680        }
18681        return result;
18682    }
18683
18684    @Override
18685    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18686        final int callingUid = Binder.getCallingUid();
18687        if (getInstantAppPackageName(callingUid) != null
18688                && !isCallerSameApp(packageName, callingUid)) {
18689            return false;
18690        }
18691        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18692    }
18693
18694    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18695        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18696                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18697        try {
18698            if (dpm != null) {
18699                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18700                        /* callingUserOnly =*/ false);
18701                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18702                        : deviceOwnerComponentName.getPackageName();
18703                // Does the package contains the device owner?
18704                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18705                // this check is probably not needed, since DO should be registered as a device
18706                // admin on some user too. (Original bug for this: b/17657954)
18707                if (packageName.equals(deviceOwnerPackageName)) {
18708                    return true;
18709                }
18710                // Does it contain a device admin for any user?
18711                int[] users;
18712                if (userId == UserHandle.USER_ALL) {
18713                    users = sUserManager.getUserIds();
18714                } else {
18715                    users = new int[]{userId};
18716                }
18717                for (int i = 0; i < users.length; ++i) {
18718                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18719                        return true;
18720                    }
18721                }
18722            }
18723        } catch (RemoteException e) {
18724        }
18725        return false;
18726    }
18727
18728    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18729        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18730    }
18731
18732    /**
18733     *  This method is an internal method that could be get invoked either
18734     *  to delete an installed package or to clean up a failed installation.
18735     *  After deleting an installed package, a broadcast is sent to notify any
18736     *  listeners that the package has been removed. For cleaning up a failed
18737     *  installation, the broadcast is not necessary since the package's
18738     *  installation wouldn't have sent the initial broadcast either
18739     *  The key steps in deleting a package are
18740     *  deleting the package information in internal structures like mPackages,
18741     *  deleting the packages base directories through installd
18742     *  updating mSettings to reflect current status
18743     *  persisting settings for later use
18744     *  sending a broadcast if necessary
18745     */
18746    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18747        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18748        final boolean res;
18749
18750        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18751                ? UserHandle.USER_ALL : userId;
18752
18753        if (isPackageDeviceAdmin(packageName, removeUser)) {
18754            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18755            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18756        }
18757
18758        PackageSetting uninstalledPs = null;
18759        PackageParser.Package pkg = null;
18760
18761        // for the uninstall-updates case and restricted profiles, remember the per-
18762        // user handle installed state
18763        int[] allUsers;
18764        synchronized (mPackages) {
18765            uninstalledPs = mSettings.mPackages.get(packageName);
18766            if (uninstalledPs == null) {
18767                Slog.w(TAG, "Not removing non-existent package " + packageName);
18768                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18769            }
18770
18771            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18772                    && uninstalledPs.versionCode != versionCode) {
18773                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18774                        + uninstalledPs.versionCode + " != " + versionCode);
18775                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18776            }
18777
18778            // Static shared libs can be declared by any package, so let us not
18779            // allow removing a package if it provides a lib others depend on.
18780            pkg = mPackages.get(packageName);
18781
18782            allUsers = sUserManager.getUserIds();
18783
18784            if (pkg != null && pkg.staticSharedLibName != null) {
18785                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18786                        pkg.staticSharedLibVersion);
18787                if (libEntry != null) {
18788                    for (int currUserId : allUsers) {
18789                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18790                            continue;
18791                        }
18792                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18793                                libEntry.info, 0, currUserId);
18794                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18795                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18796                                    + " hosting lib " + libEntry.info.getName() + " version "
18797                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18798                                    + " for user " + currUserId);
18799                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18800                        }
18801                    }
18802                }
18803            }
18804
18805            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18806        }
18807
18808        final int freezeUser;
18809        if (isUpdatedSystemApp(uninstalledPs)
18810                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18811            // We're downgrading a system app, which will apply to all users, so
18812            // freeze them all during the downgrade
18813            freezeUser = UserHandle.USER_ALL;
18814        } else {
18815            freezeUser = removeUser;
18816        }
18817
18818        synchronized (mInstallLock) {
18819            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18820            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18821                    deleteFlags, "deletePackageX")) {
18822                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18823                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18824            }
18825            synchronized (mPackages) {
18826                if (res) {
18827                    if (pkg != null) {
18828                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18829                    }
18830                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18831                    updateInstantAppInstallerLocked(packageName);
18832                }
18833            }
18834        }
18835
18836        if (res) {
18837            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18838            info.sendPackageRemovedBroadcasts(killApp);
18839            info.sendSystemPackageUpdatedBroadcasts();
18840            info.sendSystemPackageAppearedBroadcasts();
18841        }
18842        // Force a gc here.
18843        Runtime.getRuntime().gc();
18844        // Delete the resources here after sending the broadcast to let
18845        // other processes clean up before deleting resources.
18846        if (info.args != null) {
18847            synchronized (mInstallLock) {
18848                info.args.doPostDeleteLI(true);
18849            }
18850        }
18851
18852        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18853    }
18854
18855    static class PackageRemovedInfo {
18856        final PackageSender packageSender;
18857        String removedPackage;
18858        String installerPackageName;
18859        int uid = -1;
18860        int removedAppId = -1;
18861        int[] origUsers;
18862        int[] removedUsers = null;
18863        int[] broadcastUsers = null;
18864        SparseArray<Integer> installReasons;
18865        boolean isRemovedPackageSystemUpdate = false;
18866        boolean isUpdate;
18867        boolean dataRemoved;
18868        boolean removedForAllUsers;
18869        boolean isStaticSharedLib;
18870        // Clean up resources deleted packages.
18871        InstallArgs args = null;
18872        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18873        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18874
18875        PackageRemovedInfo(PackageSender packageSender) {
18876            this.packageSender = packageSender;
18877        }
18878
18879        void sendPackageRemovedBroadcasts(boolean killApp) {
18880            sendPackageRemovedBroadcastInternal(killApp);
18881            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18882            for (int i = 0; i < childCount; i++) {
18883                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18884                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18885            }
18886        }
18887
18888        void sendSystemPackageUpdatedBroadcasts() {
18889            if (isRemovedPackageSystemUpdate) {
18890                sendSystemPackageUpdatedBroadcastsInternal();
18891                final int childCount = (removedChildPackages != null)
18892                        ? removedChildPackages.size() : 0;
18893                for (int i = 0; i < childCount; i++) {
18894                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18895                    if (childInfo.isRemovedPackageSystemUpdate) {
18896                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18897                    }
18898                }
18899            }
18900        }
18901
18902        void sendSystemPackageAppearedBroadcasts() {
18903            final int packageCount = (appearedChildPackages != null)
18904                    ? appearedChildPackages.size() : 0;
18905            for (int i = 0; i < packageCount; i++) {
18906                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18907                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18908                    true, UserHandle.getAppId(installedInfo.uid),
18909                    installedInfo.newUsers);
18910            }
18911        }
18912
18913        private void sendSystemPackageUpdatedBroadcastsInternal() {
18914            Bundle extras = new Bundle(2);
18915            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18916            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18917            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18918                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18919            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18920                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18921            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18922                null, null, 0, removedPackage, null, null);
18923            if (installerPackageName != null) {
18924                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18925                        removedPackage, extras, 0 /*flags*/,
18926                        installerPackageName, null, null);
18927                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18928                        removedPackage, extras, 0 /*flags*/,
18929                        installerPackageName, null, null);
18930            }
18931        }
18932
18933        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18934            // Don't send static shared library removal broadcasts as these
18935            // libs are visible only the the apps that depend on them an one
18936            // cannot remove the library if it has a dependency.
18937            if (isStaticSharedLib) {
18938                return;
18939            }
18940            Bundle extras = new Bundle(2);
18941            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18942            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18943            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18944            if (isUpdate || isRemovedPackageSystemUpdate) {
18945                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18946            }
18947            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18948            if (removedPackage != null) {
18949                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18950                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18951                if (installerPackageName != null) {
18952                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18953                            removedPackage, extras, 0 /*flags*/,
18954                            installerPackageName, null, broadcastUsers);
18955                }
18956                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18957                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18958                        removedPackage, extras,
18959                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18960                        null, null, broadcastUsers);
18961                }
18962            }
18963            if (removedAppId >= 0) {
18964                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
18965                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
18966            }
18967        }
18968
18969        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18970            removedUsers = userIds;
18971            if (removedUsers == null) {
18972                broadcastUsers = null;
18973                return;
18974            }
18975
18976            broadcastUsers = EMPTY_INT_ARRAY;
18977            for (int i = userIds.length - 1; i >= 0; --i) {
18978                final int userId = userIds[i];
18979                if (deletedPackageSetting.getInstantApp(userId)) {
18980                    continue;
18981                }
18982                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18983            }
18984        }
18985    }
18986
18987    /*
18988     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18989     * flag is not set, the data directory is removed as well.
18990     * make sure this flag is set for partially installed apps. If not its meaningless to
18991     * delete a partially installed application.
18992     */
18993    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18994            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18995        String packageName = ps.name;
18996        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18997        // Retrieve object to delete permissions for shared user later on
18998        final PackageParser.Package deletedPkg;
18999        final PackageSetting deletedPs;
19000        // reader
19001        synchronized (mPackages) {
19002            deletedPkg = mPackages.get(packageName);
19003            deletedPs = mSettings.mPackages.get(packageName);
19004            if (outInfo != null) {
19005                outInfo.removedPackage = packageName;
19006                outInfo.installerPackageName = ps.installerPackageName;
19007                outInfo.isStaticSharedLib = deletedPkg != null
19008                        && deletedPkg.staticSharedLibName != null;
19009                outInfo.populateUsers(deletedPs == null ? null
19010                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19011            }
19012        }
19013
19014        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19015
19016        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19017            final PackageParser.Package resolvedPkg;
19018            if (deletedPkg != null) {
19019                resolvedPkg = deletedPkg;
19020            } else {
19021                // We don't have a parsed package when it lives on an ejected
19022                // adopted storage device, so fake something together
19023                resolvedPkg = new PackageParser.Package(ps.name);
19024                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19025            }
19026            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19027                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19028            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19029            if (outInfo != null) {
19030                outInfo.dataRemoved = true;
19031            }
19032            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19033        }
19034
19035        int removedAppId = -1;
19036
19037        // writer
19038        synchronized (mPackages) {
19039            boolean installedStateChanged = false;
19040            if (deletedPs != null) {
19041                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19042                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19043                    clearDefaultBrowserIfNeeded(packageName);
19044                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19045                    removedAppId = mSettings.removePackageLPw(packageName);
19046                    if (outInfo != null) {
19047                        outInfo.removedAppId = removedAppId;
19048                    }
19049                    updatePermissionsLPw(deletedPs.name, null, 0);
19050                    if (deletedPs.sharedUser != null) {
19051                        // Remove permissions associated with package. Since runtime
19052                        // permissions are per user we have to kill the removed package
19053                        // or packages running under the shared user of the removed
19054                        // package if revoking the permissions requested only by the removed
19055                        // package is successful and this causes a change in gids.
19056                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19057                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19058                                    userId);
19059                            if (userIdToKill == UserHandle.USER_ALL
19060                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19061                                // If gids changed for this user, kill all affected packages.
19062                                mHandler.post(new Runnable() {
19063                                    @Override
19064                                    public void run() {
19065                                        // This has to happen with no lock held.
19066                                        killApplication(deletedPs.name, deletedPs.appId,
19067                                                KILL_APP_REASON_GIDS_CHANGED);
19068                                    }
19069                                });
19070                                break;
19071                            }
19072                        }
19073                    }
19074                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19075                }
19076                // make sure to preserve per-user disabled state if this removal was just
19077                // a downgrade of a system app to the factory package
19078                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19079                    if (DEBUG_REMOVE) {
19080                        Slog.d(TAG, "Propagating install state across downgrade");
19081                    }
19082                    for (int userId : allUserHandles) {
19083                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19084                        if (DEBUG_REMOVE) {
19085                            Slog.d(TAG, "    user " + userId + " => " + installed);
19086                        }
19087                        if (installed != ps.getInstalled(userId)) {
19088                            installedStateChanged = true;
19089                        }
19090                        ps.setInstalled(installed, userId);
19091                    }
19092                }
19093            }
19094            // can downgrade to reader
19095            if (writeSettings) {
19096                // Save settings now
19097                mSettings.writeLPr();
19098            }
19099            if (installedStateChanged) {
19100                mSettings.writeKernelMappingLPr(ps);
19101            }
19102        }
19103        if (removedAppId != -1) {
19104            // A user ID was deleted here. Go through all users and remove it
19105            // from KeyStore.
19106            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19107        }
19108    }
19109
19110    static boolean locationIsPrivileged(File path) {
19111        try {
19112            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19113                    .getCanonicalPath();
19114            return path.getCanonicalPath().startsWith(privilegedAppDir);
19115        } catch (IOException e) {
19116            Slog.e(TAG, "Unable to access code path " + path);
19117        }
19118        return false;
19119    }
19120
19121    /*
19122     * Tries to delete system package.
19123     */
19124    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19125            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19126            boolean writeSettings) {
19127        if (deletedPs.parentPackageName != null) {
19128            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19129            return false;
19130        }
19131
19132        final boolean applyUserRestrictions
19133                = (allUserHandles != null) && (outInfo.origUsers != null);
19134        final PackageSetting disabledPs;
19135        // Confirm if the system package has been updated
19136        // An updated system app can be deleted. This will also have to restore
19137        // the system pkg from system partition
19138        // reader
19139        synchronized (mPackages) {
19140            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19141        }
19142
19143        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19144                + " disabledPs=" + disabledPs);
19145
19146        if (disabledPs == null) {
19147            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19148            return false;
19149        } else if (DEBUG_REMOVE) {
19150            Slog.d(TAG, "Deleting system pkg from data partition");
19151        }
19152
19153        if (DEBUG_REMOVE) {
19154            if (applyUserRestrictions) {
19155                Slog.d(TAG, "Remembering install states:");
19156                for (int userId : allUserHandles) {
19157                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19158                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19159                }
19160            }
19161        }
19162
19163        // Delete the updated package
19164        outInfo.isRemovedPackageSystemUpdate = true;
19165        if (outInfo.removedChildPackages != null) {
19166            final int childCount = (deletedPs.childPackageNames != null)
19167                    ? deletedPs.childPackageNames.size() : 0;
19168            for (int i = 0; i < childCount; i++) {
19169                String childPackageName = deletedPs.childPackageNames.get(i);
19170                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19171                        .contains(childPackageName)) {
19172                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19173                            childPackageName);
19174                    if (childInfo != null) {
19175                        childInfo.isRemovedPackageSystemUpdate = true;
19176                    }
19177                }
19178            }
19179        }
19180
19181        if (disabledPs.versionCode < deletedPs.versionCode) {
19182            // Delete data for downgrades
19183            flags &= ~PackageManager.DELETE_KEEP_DATA;
19184        } else {
19185            // Preserve data by setting flag
19186            flags |= PackageManager.DELETE_KEEP_DATA;
19187        }
19188
19189        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19190                outInfo, writeSettings, disabledPs.pkg);
19191        if (!ret) {
19192            return false;
19193        }
19194
19195        // writer
19196        synchronized (mPackages) {
19197            // Reinstate the old system package
19198            enableSystemPackageLPw(disabledPs.pkg);
19199            // Remove any native libraries from the upgraded package.
19200            removeNativeBinariesLI(deletedPs);
19201        }
19202
19203        // Install the system package
19204        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19205        int parseFlags = mDefParseFlags
19206                | PackageParser.PARSE_MUST_BE_APK
19207                | PackageParser.PARSE_IS_SYSTEM
19208                | PackageParser.PARSE_IS_SYSTEM_DIR;
19209        if (locationIsPrivileged(disabledPs.codePath)) {
19210            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19211        }
19212
19213        final PackageParser.Package newPkg;
19214        try {
19215            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19216                0 /* currentTime */, null);
19217        } catch (PackageManagerException e) {
19218            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19219                    + e.getMessage());
19220            return false;
19221        }
19222
19223        try {
19224            // update shared libraries for the newly re-installed system package
19225            updateSharedLibrariesLPr(newPkg, null);
19226        } catch (PackageManagerException e) {
19227            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19228        }
19229
19230        prepareAppDataAfterInstallLIF(newPkg);
19231
19232        // writer
19233        synchronized (mPackages) {
19234            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19235
19236            // Propagate the permissions state as we do not want to drop on the floor
19237            // runtime permissions. The update permissions method below will take
19238            // care of removing obsolete permissions and grant install permissions.
19239            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19240            updatePermissionsLPw(newPkg.packageName, newPkg,
19241                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19242
19243            if (applyUserRestrictions) {
19244                boolean installedStateChanged = false;
19245                if (DEBUG_REMOVE) {
19246                    Slog.d(TAG, "Propagating install state across reinstall");
19247                }
19248                for (int userId : allUserHandles) {
19249                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19250                    if (DEBUG_REMOVE) {
19251                        Slog.d(TAG, "    user " + userId + " => " + installed);
19252                    }
19253                    if (installed != ps.getInstalled(userId)) {
19254                        installedStateChanged = true;
19255                    }
19256                    ps.setInstalled(installed, userId);
19257
19258                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19259                }
19260                // Regardless of writeSettings we need to ensure that this restriction
19261                // state propagation is persisted
19262                mSettings.writeAllUsersPackageRestrictionsLPr();
19263                if (installedStateChanged) {
19264                    mSettings.writeKernelMappingLPr(ps);
19265                }
19266            }
19267            // can downgrade to reader here
19268            if (writeSettings) {
19269                mSettings.writeLPr();
19270            }
19271        }
19272        return true;
19273    }
19274
19275    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19276            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19277            PackageRemovedInfo outInfo, boolean writeSettings,
19278            PackageParser.Package replacingPackage) {
19279        synchronized (mPackages) {
19280            if (outInfo != null) {
19281                outInfo.uid = ps.appId;
19282            }
19283
19284            if (outInfo != null && outInfo.removedChildPackages != null) {
19285                final int childCount = (ps.childPackageNames != null)
19286                        ? ps.childPackageNames.size() : 0;
19287                for (int i = 0; i < childCount; i++) {
19288                    String childPackageName = ps.childPackageNames.get(i);
19289                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19290                    if (childPs == null) {
19291                        return false;
19292                    }
19293                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19294                            childPackageName);
19295                    if (childInfo != null) {
19296                        childInfo.uid = childPs.appId;
19297                    }
19298                }
19299            }
19300        }
19301
19302        // Delete package data from internal structures and also remove data if flag is set
19303        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19304
19305        // Delete the child packages data
19306        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19307        for (int i = 0; i < childCount; i++) {
19308            PackageSetting childPs;
19309            synchronized (mPackages) {
19310                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19311            }
19312            if (childPs != null) {
19313                PackageRemovedInfo childOutInfo = (outInfo != null
19314                        && outInfo.removedChildPackages != null)
19315                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19316                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19317                        && (replacingPackage != null
19318                        && !replacingPackage.hasChildPackage(childPs.name))
19319                        ? flags & ~DELETE_KEEP_DATA : flags;
19320                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19321                        deleteFlags, writeSettings);
19322            }
19323        }
19324
19325        // Delete application code and resources only for parent packages
19326        if (ps.parentPackageName == null) {
19327            if (deleteCodeAndResources && (outInfo != null)) {
19328                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19329                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19330                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19331            }
19332        }
19333
19334        return true;
19335    }
19336
19337    @Override
19338    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19339            int userId) {
19340        mContext.enforceCallingOrSelfPermission(
19341                android.Manifest.permission.DELETE_PACKAGES, null);
19342        synchronized (mPackages) {
19343            // Cannot block uninstall of static shared libs as they are
19344            // considered a part of the using app (emulating static linking).
19345            // Also static libs are installed always on internal storage.
19346            PackageParser.Package pkg = mPackages.get(packageName);
19347            if (pkg != null && pkg.staticSharedLibName != null) {
19348                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19349                        + " providing static shared library: " + pkg.staticSharedLibName);
19350                return false;
19351            }
19352            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19353            mSettings.writePackageRestrictionsLPr(userId);
19354        }
19355        return true;
19356    }
19357
19358    @Override
19359    public boolean getBlockUninstallForUser(String packageName, int userId) {
19360        synchronized (mPackages) {
19361            final PackageSetting ps = mSettings.mPackages.get(packageName);
19362            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19363                return false;
19364            }
19365            return mSettings.getBlockUninstallLPr(userId, packageName);
19366        }
19367    }
19368
19369    @Override
19370    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19371        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19372        synchronized (mPackages) {
19373            PackageSetting ps = mSettings.mPackages.get(packageName);
19374            if (ps == null) {
19375                Log.w(TAG, "Package doesn't exist: " + packageName);
19376                return false;
19377            }
19378            if (systemUserApp) {
19379                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19380            } else {
19381                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19382            }
19383            mSettings.writeLPr();
19384        }
19385        return true;
19386    }
19387
19388    /*
19389     * This method handles package deletion in general
19390     */
19391    private boolean deletePackageLIF(String packageName, UserHandle user,
19392            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19393            PackageRemovedInfo outInfo, boolean writeSettings,
19394            PackageParser.Package replacingPackage) {
19395        if (packageName == null) {
19396            Slog.w(TAG, "Attempt to delete null packageName.");
19397            return false;
19398        }
19399
19400        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19401
19402        PackageSetting ps;
19403        synchronized (mPackages) {
19404            ps = mSettings.mPackages.get(packageName);
19405            if (ps == null) {
19406                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19407                return false;
19408            }
19409
19410            if (ps.parentPackageName != null && (!isSystemApp(ps)
19411                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19412                if (DEBUG_REMOVE) {
19413                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19414                            + ((user == null) ? UserHandle.USER_ALL : user));
19415                }
19416                final int removedUserId = (user != null) ? user.getIdentifier()
19417                        : UserHandle.USER_ALL;
19418                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19419                    return false;
19420                }
19421                markPackageUninstalledForUserLPw(ps, user);
19422                scheduleWritePackageRestrictionsLocked(user);
19423                return true;
19424            }
19425        }
19426
19427        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19428                && user.getIdentifier() != UserHandle.USER_ALL)) {
19429            // The caller is asking that the package only be deleted for a single
19430            // user.  To do this, we just mark its uninstalled state and delete
19431            // its data. If this is a system app, we only allow this to happen if
19432            // they have set the special DELETE_SYSTEM_APP which requests different
19433            // semantics than normal for uninstalling system apps.
19434            markPackageUninstalledForUserLPw(ps, user);
19435
19436            if (!isSystemApp(ps)) {
19437                // Do not uninstall the APK if an app should be cached
19438                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19439                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19440                    // Other user still have this package installed, so all
19441                    // we need to do is clear this user's data and save that
19442                    // it is uninstalled.
19443                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19444                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19445                        return false;
19446                    }
19447                    scheduleWritePackageRestrictionsLocked(user);
19448                    return true;
19449                } else {
19450                    // We need to set it back to 'installed' so the uninstall
19451                    // broadcasts will be sent correctly.
19452                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19453                    ps.setInstalled(true, user.getIdentifier());
19454                    mSettings.writeKernelMappingLPr(ps);
19455                }
19456            } else {
19457                // This is a system app, so we assume that the
19458                // other users still have this package installed, so all
19459                // we need to do is clear this user's data and save that
19460                // it is uninstalled.
19461                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19462                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19463                    return false;
19464                }
19465                scheduleWritePackageRestrictionsLocked(user);
19466                return true;
19467            }
19468        }
19469
19470        // If we are deleting a composite package for all users, keep track
19471        // of result for each child.
19472        if (ps.childPackageNames != null && outInfo != null) {
19473            synchronized (mPackages) {
19474                final int childCount = ps.childPackageNames.size();
19475                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19476                for (int i = 0; i < childCount; i++) {
19477                    String childPackageName = ps.childPackageNames.get(i);
19478                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19479                    childInfo.removedPackage = childPackageName;
19480                    childInfo.installerPackageName = ps.installerPackageName;
19481                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19482                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19483                    if (childPs != null) {
19484                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19485                    }
19486                }
19487            }
19488        }
19489
19490        boolean ret = false;
19491        if (isSystemApp(ps)) {
19492            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19493            // When an updated system application is deleted we delete the existing resources
19494            // as well and fall back to existing code in system partition
19495            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19496        } else {
19497            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19498            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19499                    outInfo, writeSettings, replacingPackage);
19500        }
19501
19502        // Take a note whether we deleted the package for all users
19503        if (outInfo != null) {
19504            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19505            if (outInfo.removedChildPackages != null) {
19506                synchronized (mPackages) {
19507                    final int childCount = outInfo.removedChildPackages.size();
19508                    for (int i = 0; i < childCount; i++) {
19509                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19510                        if (childInfo != null) {
19511                            childInfo.removedForAllUsers = mPackages.get(
19512                                    childInfo.removedPackage) == null;
19513                        }
19514                    }
19515                }
19516            }
19517            // If we uninstalled an update to a system app there may be some
19518            // child packages that appeared as they are declared in the system
19519            // app but were not declared in the update.
19520            if (isSystemApp(ps)) {
19521                synchronized (mPackages) {
19522                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19523                    final int childCount = (updatedPs.childPackageNames != null)
19524                            ? updatedPs.childPackageNames.size() : 0;
19525                    for (int i = 0; i < childCount; i++) {
19526                        String childPackageName = updatedPs.childPackageNames.get(i);
19527                        if (outInfo.removedChildPackages == null
19528                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19529                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19530                            if (childPs == null) {
19531                                continue;
19532                            }
19533                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19534                            installRes.name = childPackageName;
19535                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19536                            installRes.pkg = mPackages.get(childPackageName);
19537                            installRes.uid = childPs.pkg.applicationInfo.uid;
19538                            if (outInfo.appearedChildPackages == null) {
19539                                outInfo.appearedChildPackages = new ArrayMap<>();
19540                            }
19541                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19542                        }
19543                    }
19544                }
19545            }
19546        }
19547
19548        return ret;
19549    }
19550
19551    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19552        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19553                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19554        for (int nextUserId : userIds) {
19555            if (DEBUG_REMOVE) {
19556                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19557            }
19558            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19559                    false /*installed*/,
19560                    true /*stopped*/,
19561                    true /*notLaunched*/,
19562                    false /*hidden*/,
19563                    false /*suspended*/,
19564                    false /*instantApp*/,
19565                    null /*lastDisableAppCaller*/,
19566                    null /*enabledComponents*/,
19567                    null /*disabledComponents*/,
19568                    ps.readUserState(nextUserId).domainVerificationStatus,
19569                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19570        }
19571        mSettings.writeKernelMappingLPr(ps);
19572    }
19573
19574    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19575            PackageRemovedInfo outInfo) {
19576        final PackageParser.Package pkg;
19577        synchronized (mPackages) {
19578            pkg = mPackages.get(ps.name);
19579        }
19580
19581        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19582                : new int[] {userId};
19583        for (int nextUserId : userIds) {
19584            if (DEBUG_REMOVE) {
19585                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19586                        + nextUserId);
19587            }
19588
19589            destroyAppDataLIF(pkg, userId,
19590                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19591            destroyAppProfilesLIF(pkg, userId);
19592            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19593            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19594            schedulePackageCleaning(ps.name, nextUserId, false);
19595            synchronized (mPackages) {
19596                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19597                    scheduleWritePackageRestrictionsLocked(nextUserId);
19598                }
19599                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19600            }
19601        }
19602
19603        if (outInfo != null) {
19604            outInfo.removedPackage = ps.name;
19605            outInfo.installerPackageName = ps.installerPackageName;
19606            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19607            outInfo.removedAppId = ps.appId;
19608            outInfo.removedUsers = userIds;
19609            outInfo.broadcastUsers = userIds;
19610        }
19611
19612        return true;
19613    }
19614
19615    private final class ClearStorageConnection implements ServiceConnection {
19616        IMediaContainerService mContainerService;
19617
19618        @Override
19619        public void onServiceConnected(ComponentName name, IBinder service) {
19620            synchronized (this) {
19621                mContainerService = IMediaContainerService.Stub
19622                        .asInterface(Binder.allowBlocking(service));
19623                notifyAll();
19624            }
19625        }
19626
19627        @Override
19628        public void onServiceDisconnected(ComponentName name) {
19629        }
19630    }
19631
19632    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19633        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19634
19635        final boolean mounted;
19636        if (Environment.isExternalStorageEmulated()) {
19637            mounted = true;
19638        } else {
19639            final String status = Environment.getExternalStorageState();
19640
19641            mounted = status.equals(Environment.MEDIA_MOUNTED)
19642                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19643        }
19644
19645        if (!mounted) {
19646            return;
19647        }
19648
19649        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19650        int[] users;
19651        if (userId == UserHandle.USER_ALL) {
19652            users = sUserManager.getUserIds();
19653        } else {
19654            users = new int[] { userId };
19655        }
19656        final ClearStorageConnection conn = new ClearStorageConnection();
19657        if (mContext.bindServiceAsUser(
19658                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19659            try {
19660                for (int curUser : users) {
19661                    long timeout = SystemClock.uptimeMillis() + 5000;
19662                    synchronized (conn) {
19663                        long now;
19664                        while (conn.mContainerService == null &&
19665                                (now = SystemClock.uptimeMillis()) < timeout) {
19666                            try {
19667                                conn.wait(timeout - now);
19668                            } catch (InterruptedException e) {
19669                            }
19670                        }
19671                    }
19672                    if (conn.mContainerService == null) {
19673                        return;
19674                    }
19675
19676                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19677                    clearDirectory(conn.mContainerService,
19678                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19679                    if (allData) {
19680                        clearDirectory(conn.mContainerService,
19681                                userEnv.buildExternalStorageAppDataDirs(packageName));
19682                        clearDirectory(conn.mContainerService,
19683                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19684                    }
19685                }
19686            } finally {
19687                mContext.unbindService(conn);
19688            }
19689        }
19690    }
19691
19692    @Override
19693    public void clearApplicationProfileData(String packageName) {
19694        enforceSystemOrRoot("Only the system can clear all profile data");
19695
19696        final PackageParser.Package pkg;
19697        synchronized (mPackages) {
19698            pkg = mPackages.get(packageName);
19699        }
19700
19701        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19702            synchronized (mInstallLock) {
19703                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19704            }
19705        }
19706    }
19707
19708    @Override
19709    public void clearApplicationUserData(final String packageName,
19710            final IPackageDataObserver observer, final int userId) {
19711        mContext.enforceCallingOrSelfPermission(
19712                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19713
19714        final int callingUid = Binder.getCallingUid();
19715        enforceCrossUserPermission(callingUid, userId,
19716                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19717
19718        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19719        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19720            return;
19721        }
19722        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19723            throw new SecurityException("Cannot clear data for a protected package: "
19724                    + packageName);
19725        }
19726        // Queue up an async operation since the package deletion may take a little while.
19727        mHandler.post(new Runnable() {
19728            public void run() {
19729                mHandler.removeCallbacks(this);
19730                final boolean succeeded;
19731                try (PackageFreezer freezer = freezePackage(packageName,
19732                        "clearApplicationUserData")) {
19733                    synchronized (mInstallLock) {
19734                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19735                    }
19736                    clearExternalStorageDataSync(packageName, userId, true);
19737                    synchronized (mPackages) {
19738                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19739                                packageName, userId);
19740                    }
19741                }
19742                if (succeeded) {
19743                    // invoke DeviceStorageMonitor's update method to clear any notifications
19744                    DeviceStorageMonitorInternal dsm = LocalServices
19745                            .getService(DeviceStorageMonitorInternal.class);
19746                    if (dsm != null) {
19747                        dsm.checkMemory();
19748                    }
19749                }
19750                if(observer != null) {
19751                    try {
19752                        observer.onRemoveCompleted(packageName, succeeded);
19753                    } catch (RemoteException e) {
19754                        Log.i(TAG, "Observer no longer exists.");
19755                    }
19756                } //end if observer
19757            } //end run
19758        });
19759    }
19760
19761    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19762        if (packageName == null) {
19763            Slog.w(TAG, "Attempt to delete null packageName.");
19764            return false;
19765        }
19766
19767        // Try finding details about the requested package
19768        PackageParser.Package pkg;
19769        synchronized (mPackages) {
19770            pkg = mPackages.get(packageName);
19771            if (pkg == null) {
19772                final PackageSetting ps = mSettings.mPackages.get(packageName);
19773                if (ps != null) {
19774                    pkg = ps.pkg;
19775                }
19776            }
19777
19778            if (pkg == null) {
19779                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19780                return false;
19781            }
19782
19783            PackageSetting ps = (PackageSetting) pkg.mExtras;
19784            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19785        }
19786
19787        clearAppDataLIF(pkg, userId,
19788                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19789
19790        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19791        removeKeystoreDataIfNeeded(userId, appId);
19792
19793        UserManagerInternal umInternal = getUserManagerInternal();
19794        final int flags;
19795        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19796            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19797        } else if (umInternal.isUserRunning(userId)) {
19798            flags = StorageManager.FLAG_STORAGE_DE;
19799        } else {
19800            flags = 0;
19801        }
19802        prepareAppDataContentsLIF(pkg, userId, flags);
19803
19804        return true;
19805    }
19806
19807    /**
19808     * Reverts user permission state changes (permissions and flags) in
19809     * all packages for a given user.
19810     *
19811     * @param userId The device user for which to do a reset.
19812     */
19813    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19814        final int packageCount = mPackages.size();
19815        for (int i = 0; i < packageCount; i++) {
19816            PackageParser.Package pkg = mPackages.valueAt(i);
19817            PackageSetting ps = (PackageSetting) pkg.mExtras;
19818            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19819        }
19820    }
19821
19822    private void resetNetworkPolicies(int userId) {
19823        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19824    }
19825
19826    /**
19827     * Reverts user permission state changes (permissions and flags).
19828     *
19829     * @param ps The package for which to reset.
19830     * @param userId The device user for which to do a reset.
19831     */
19832    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19833            final PackageSetting ps, final int userId) {
19834        if (ps.pkg == null) {
19835            return;
19836        }
19837
19838        // These are flags that can change base on user actions.
19839        final int userSettableMask = FLAG_PERMISSION_USER_SET
19840                | FLAG_PERMISSION_USER_FIXED
19841                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19842                | FLAG_PERMISSION_REVIEW_REQUIRED;
19843
19844        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19845                | FLAG_PERMISSION_POLICY_FIXED;
19846
19847        boolean writeInstallPermissions = false;
19848        boolean writeRuntimePermissions = false;
19849
19850        final int permissionCount = ps.pkg.requestedPermissions.size();
19851        for (int i = 0; i < permissionCount; i++) {
19852            String permission = ps.pkg.requestedPermissions.get(i);
19853
19854            BasePermission bp = mSettings.mPermissions.get(permission);
19855            if (bp == null) {
19856                continue;
19857            }
19858
19859            // If shared user we just reset the state to which only this app contributed.
19860            if (ps.sharedUser != null) {
19861                boolean used = false;
19862                final int packageCount = ps.sharedUser.packages.size();
19863                for (int j = 0; j < packageCount; j++) {
19864                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19865                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19866                            && pkg.pkg.requestedPermissions.contains(permission)) {
19867                        used = true;
19868                        break;
19869                    }
19870                }
19871                if (used) {
19872                    continue;
19873                }
19874            }
19875
19876            PermissionsState permissionsState = ps.getPermissionsState();
19877
19878            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19879
19880            // Always clear the user settable flags.
19881            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19882                    bp.name) != null;
19883            // If permission review is enabled and this is a legacy app, mark the
19884            // permission as requiring a review as this is the initial state.
19885            int flags = 0;
19886            if (mPermissionReviewRequired
19887                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19888                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19889            }
19890            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19891                if (hasInstallState) {
19892                    writeInstallPermissions = true;
19893                } else {
19894                    writeRuntimePermissions = true;
19895                }
19896            }
19897
19898            // Below is only runtime permission handling.
19899            if (!bp.isRuntime()) {
19900                continue;
19901            }
19902
19903            // Never clobber system or policy.
19904            if ((oldFlags & policyOrSystemFlags) != 0) {
19905                continue;
19906            }
19907
19908            // If this permission was granted by default, make sure it is.
19909            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19910                if (permissionsState.grantRuntimePermission(bp, userId)
19911                        != PERMISSION_OPERATION_FAILURE) {
19912                    writeRuntimePermissions = true;
19913                }
19914            // If permission review is enabled the permissions for a legacy apps
19915            // are represented as constantly granted runtime ones, so don't revoke.
19916            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19917                // Otherwise, reset the permission.
19918                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19919                switch (revokeResult) {
19920                    case PERMISSION_OPERATION_SUCCESS:
19921                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19922                        writeRuntimePermissions = true;
19923                        final int appId = ps.appId;
19924                        mHandler.post(new Runnable() {
19925                            @Override
19926                            public void run() {
19927                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19928                            }
19929                        });
19930                    } break;
19931                }
19932            }
19933        }
19934
19935        // Synchronously write as we are taking permissions away.
19936        if (writeRuntimePermissions) {
19937            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19938        }
19939
19940        // Synchronously write as we are taking permissions away.
19941        if (writeInstallPermissions) {
19942            mSettings.writeLPr();
19943        }
19944    }
19945
19946    /**
19947     * Remove entries from the keystore daemon. Will only remove it if the
19948     * {@code appId} is valid.
19949     */
19950    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19951        if (appId < 0) {
19952            return;
19953        }
19954
19955        final KeyStore keyStore = KeyStore.getInstance();
19956        if (keyStore != null) {
19957            if (userId == UserHandle.USER_ALL) {
19958                for (final int individual : sUserManager.getUserIds()) {
19959                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19960                }
19961            } else {
19962                keyStore.clearUid(UserHandle.getUid(userId, appId));
19963            }
19964        } else {
19965            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19966        }
19967    }
19968
19969    @Override
19970    public void deleteApplicationCacheFiles(final String packageName,
19971            final IPackageDataObserver observer) {
19972        final int userId = UserHandle.getCallingUserId();
19973        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19974    }
19975
19976    @Override
19977    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19978            final IPackageDataObserver observer) {
19979        final int callingUid = Binder.getCallingUid();
19980        mContext.enforceCallingOrSelfPermission(
19981                android.Manifest.permission.DELETE_CACHE_FILES, null);
19982        enforceCrossUserPermission(callingUid, userId,
19983                /* requireFullPermission= */ true, /* checkShell= */ false,
19984                "delete application cache files");
19985        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19986                android.Manifest.permission.ACCESS_INSTANT_APPS);
19987
19988        final PackageParser.Package pkg;
19989        synchronized (mPackages) {
19990            pkg = mPackages.get(packageName);
19991        }
19992
19993        // Queue up an async operation since the package deletion may take a little while.
19994        mHandler.post(new Runnable() {
19995            public void run() {
19996                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19997                boolean doClearData = true;
19998                if (ps != null) {
19999                    final boolean targetIsInstantApp =
20000                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20001                    doClearData = !targetIsInstantApp
20002                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20003                }
20004                if (doClearData) {
20005                    synchronized (mInstallLock) {
20006                        final int flags = StorageManager.FLAG_STORAGE_DE
20007                                | StorageManager.FLAG_STORAGE_CE;
20008                        // We're only clearing cache files, so we don't care if the
20009                        // app is unfrozen and still able to run
20010                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20011                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20012                    }
20013                    clearExternalStorageDataSync(packageName, userId, false);
20014                }
20015                if (observer != null) {
20016                    try {
20017                        observer.onRemoveCompleted(packageName, true);
20018                    } catch (RemoteException e) {
20019                        Log.i(TAG, "Observer no longer exists.");
20020                    }
20021                }
20022            }
20023        });
20024    }
20025
20026    @Override
20027    public void getPackageSizeInfo(final String packageName, int userHandle,
20028            final IPackageStatsObserver observer) {
20029        throw new UnsupportedOperationException(
20030                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20031    }
20032
20033    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20034        final PackageSetting ps;
20035        synchronized (mPackages) {
20036            ps = mSettings.mPackages.get(packageName);
20037            if (ps == null) {
20038                Slog.w(TAG, "Failed to find settings for " + packageName);
20039                return false;
20040            }
20041        }
20042
20043        final String[] packageNames = { packageName };
20044        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20045        final String[] codePaths = { ps.codePathString };
20046
20047        try {
20048            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20049                    ps.appId, ceDataInodes, codePaths, stats);
20050
20051            // For now, ignore code size of packages on system partition
20052            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20053                stats.codeSize = 0;
20054            }
20055
20056            // External clients expect these to be tracked separately
20057            stats.dataSize -= stats.cacheSize;
20058
20059        } catch (InstallerException e) {
20060            Slog.w(TAG, String.valueOf(e));
20061            return false;
20062        }
20063
20064        return true;
20065    }
20066
20067    private int getUidTargetSdkVersionLockedLPr(int uid) {
20068        Object obj = mSettings.getUserIdLPr(uid);
20069        if (obj instanceof SharedUserSetting) {
20070            final SharedUserSetting sus = (SharedUserSetting) obj;
20071            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20072            final Iterator<PackageSetting> it = sus.packages.iterator();
20073            while (it.hasNext()) {
20074                final PackageSetting ps = it.next();
20075                if (ps.pkg != null) {
20076                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20077                    if (v < vers) vers = v;
20078                }
20079            }
20080            return vers;
20081        } else if (obj instanceof PackageSetting) {
20082            final PackageSetting ps = (PackageSetting) obj;
20083            if (ps.pkg != null) {
20084                return ps.pkg.applicationInfo.targetSdkVersion;
20085            }
20086        }
20087        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20088    }
20089
20090    @Override
20091    public void addPreferredActivity(IntentFilter filter, int match,
20092            ComponentName[] set, ComponentName activity, int userId) {
20093        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20094                "Adding preferred");
20095    }
20096
20097    private void addPreferredActivityInternal(IntentFilter filter, int match,
20098            ComponentName[] set, ComponentName activity, boolean always, int userId,
20099            String opname) {
20100        // writer
20101        int callingUid = Binder.getCallingUid();
20102        enforceCrossUserPermission(callingUid, userId,
20103                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20104        if (filter.countActions() == 0) {
20105            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20106            return;
20107        }
20108        synchronized (mPackages) {
20109            if (mContext.checkCallingOrSelfPermission(
20110                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20111                    != PackageManager.PERMISSION_GRANTED) {
20112                if (getUidTargetSdkVersionLockedLPr(callingUid)
20113                        < Build.VERSION_CODES.FROYO) {
20114                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20115                            + callingUid);
20116                    return;
20117                }
20118                mContext.enforceCallingOrSelfPermission(
20119                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20120            }
20121
20122            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20123            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20124                    + userId + ":");
20125            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20126            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20127            scheduleWritePackageRestrictionsLocked(userId);
20128            postPreferredActivityChangedBroadcast(userId);
20129        }
20130    }
20131
20132    private void postPreferredActivityChangedBroadcast(int userId) {
20133        mHandler.post(() -> {
20134            final IActivityManager am = ActivityManager.getService();
20135            if (am == null) {
20136                return;
20137            }
20138
20139            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20140            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20141            try {
20142                am.broadcastIntent(null, intent, null, null,
20143                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20144                        null, false, false, userId);
20145            } catch (RemoteException e) {
20146            }
20147        });
20148    }
20149
20150    @Override
20151    public void replacePreferredActivity(IntentFilter filter, int match,
20152            ComponentName[] set, ComponentName activity, int userId) {
20153        if (filter.countActions() != 1) {
20154            throw new IllegalArgumentException(
20155                    "replacePreferredActivity expects filter to have only 1 action.");
20156        }
20157        if (filter.countDataAuthorities() != 0
20158                || filter.countDataPaths() != 0
20159                || filter.countDataSchemes() > 1
20160                || filter.countDataTypes() != 0) {
20161            throw new IllegalArgumentException(
20162                    "replacePreferredActivity expects filter to have no data authorities, " +
20163                    "paths, or types; and at most one scheme.");
20164        }
20165
20166        final int callingUid = Binder.getCallingUid();
20167        enforceCrossUserPermission(callingUid, userId,
20168                true /* requireFullPermission */, false /* checkShell */,
20169                "replace preferred activity");
20170        synchronized (mPackages) {
20171            if (mContext.checkCallingOrSelfPermission(
20172                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20173                    != PackageManager.PERMISSION_GRANTED) {
20174                if (getUidTargetSdkVersionLockedLPr(callingUid)
20175                        < Build.VERSION_CODES.FROYO) {
20176                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20177                            + Binder.getCallingUid());
20178                    return;
20179                }
20180                mContext.enforceCallingOrSelfPermission(
20181                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20182            }
20183
20184            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20185            if (pir != null) {
20186                // Get all of the existing entries that exactly match this filter.
20187                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20188                if (existing != null && existing.size() == 1) {
20189                    PreferredActivity cur = existing.get(0);
20190                    if (DEBUG_PREFERRED) {
20191                        Slog.i(TAG, "Checking replace of preferred:");
20192                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20193                        if (!cur.mPref.mAlways) {
20194                            Slog.i(TAG, "  -- CUR; not mAlways!");
20195                        } else {
20196                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20197                            Slog.i(TAG, "  -- CUR: mSet="
20198                                    + Arrays.toString(cur.mPref.mSetComponents));
20199                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20200                            Slog.i(TAG, "  -- NEW: mMatch="
20201                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20202                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20203                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20204                        }
20205                    }
20206                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20207                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20208                            && cur.mPref.sameSet(set)) {
20209                        // Setting the preferred activity to what it happens to be already
20210                        if (DEBUG_PREFERRED) {
20211                            Slog.i(TAG, "Replacing with same preferred activity "
20212                                    + cur.mPref.mShortComponent + " for user "
20213                                    + userId + ":");
20214                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20215                        }
20216                        return;
20217                    }
20218                }
20219
20220                if (existing != null) {
20221                    if (DEBUG_PREFERRED) {
20222                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20223                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20224                    }
20225                    for (int i = 0; i < existing.size(); i++) {
20226                        PreferredActivity pa = existing.get(i);
20227                        if (DEBUG_PREFERRED) {
20228                            Slog.i(TAG, "Removing existing preferred activity "
20229                                    + pa.mPref.mComponent + ":");
20230                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20231                        }
20232                        pir.removeFilter(pa);
20233                    }
20234                }
20235            }
20236            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20237                    "Replacing preferred");
20238        }
20239    }
20240
20241    @Override
20242    public void clearPackagePreferredActivities(String packageName) {
20243        final int callingUid = Binder.getCallingUid();
20244        if (getInstantAppPackageName(callingUid) != null) {
20245            return;
20246        }
20247        // writer
20248        synchronized (mPackages) {
20249            PackageParser.Package pkg = mPackages.get(packageName);
20250            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20251                if (mContext.checkCallingOrSelfPermission(
20252                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20253                        != PackageManager.PERMISSION_GRANTED) {
20254                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20255                            < Build.VERSION_CODES.FROYO) {
20256                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20257                                + callingUid);
20258                        return;
20259                    }
20260                    mContext.enforceCallingOrSelfPermission(
20261                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20262                }
20263            }
20264            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20265            if (ps != null
20266                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20267                return;
20268            }
20269            int user = UserHandle.getCallingUserId();
20270            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20271                scheduleWritePackageRestrictionsLocked(user);
20272            }
20273        }
20274    }
20275
20276    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20277    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20278        ArrayList<PreferredActivity> removed = null;
20279        boolean changed = false;
20280        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20281            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20282            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20283            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20284                continue;
20285            }
20286            Iterator<PreferredActivity> it = pir.filterIterator();
20287            while (it.hasNext()) {
20288                PreferredActivity pa = it.next();
20289                // Mark entry for removal only if it matches the package name
20290                // and the entry is of type "always".
20291                if (packageName == null ||
20292                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20293                                && pa.mPref.mAlways)) {
20294                    if (removed == null) {
20295                        removed = new ArrayList<PreferredActivity>();
20296                    }
20297                    removed.add(pa);
20298                }
20299            }
20300            if (removed != null) {
20301                for (int j=0; j<removed.size(); j++) {
20302                    PreferredActivity pa = removed.get(j);
20303                    pir.removeFilter(pa);
20304                }
20305                changed = true;
20306            }
20307        }
20308        if (changed) {
20309            postPreferredActivityChangedBroadcast(userId);
20310        }
20311        return changed;
20312    }
20313
20314    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20315    private void clearIntentFilterVerificationsLPw(int userId) {
20316        final int packageCount = mPackages.size();
20317        for (int i = 0; i < packageCount; i++) {
20318            PackageParser.Package pkg = mPackages.valueAt(i);
20319            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20320        }
20321    }
20322
20323    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20324    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20325        if (userId == UserHandle.USER_ALL) {
20326            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20327                    sUserManager.getUserIds())) {
20328                for (int oneUserId : sUserManager.getUserIds()) {
20329                    scheduleWritePackageRestrictionsLocked(oneUserId);
20330                }
20331            }
20332        } else {
20333            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20334                scheduleWritePackageRestrictionsLocked(userId);
20335            }
20336        }
20337    }
20338
20339    /** Clears state for all users, and touches intent filter verification policy */
20340    void clearDefaultBrowserIfNeeded(String packageName) {
20341        for (int oneUserId : sUserManager.getUserIds()) {
20342            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20343        }
20344    }
20345
20346    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20347        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20348        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20349            if (packageName.equals(defaultBrowserPackageName)) {
20350                setDefaultBrowserPackageName(null, userId);
20351            }
20352        }
20353    }
20354
20355    @Override
20356    public void resetApplicationPreferences(int userId) {
20357        mContext.enforceCallingOrSelfPermission(
20358                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20359        final long identity = Binder.clearCallingIdentity();
20360        // writer
20361        try {
20362            synchronized (mPackages) {
20363                clearPackagePreferredActivitiesLPw(null, userId);
20364                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20365                // TODO: We have to reset the default SMS and Phone. This requires
20366                // significant refactoring to keep all default apps in the package
20367                // manager (cleaner but more work) or have the services provide
20368                // callbacks to the package manager to request a default app reset.
20369                applyFactoryDefaultBrowserLPw(userId);
20370                clearIntentFilterVerificationsLPw(userId);
20371                primeDomainVerificationsLPw(userId);
20372                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20373                scheduleWritePackageRestrictionsLocked(userId);
20374            }
20375            resetNetworkPolicies(userId);
20376        } finally {
20377            Binder.restoreCallingIdentity(identity);
20378        }
20379    }
20380
20381    @Override
20382    public int getPreferredActivities(List<IntentFilter> outFilters,
20383            List<ComponentName> outActivities, String packageName) {
20384        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20385            return 0;
20386        }
20387        int num = 0;
20388        final int userId = UserHandle.getCallingUserId();
20389        // reader
20390        synchronized (mPackages) {
20391            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20392            if (pir != null) {
20393                final Iterator<PreferredActivity> it = pir.filterIterator();
20394                while (it.hasNext()) {
20395                    final PreferredActivity pa = it.next();
20396                    if (packageName == null
20397                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20398                                    && pa.mPref.mAlways)) {
20399                        if (outFilters != null) {
20400                            outFilters.add(new IntentFilter(pa));
20401                        }
20402                        if (outActivities != null) {
20403                            outActivities.add(pa.mPref.mComponent);
20404                        }
20405                    }
20406                }
20407            }
20408        }
20409
20410        return num;
20411    }
20412
20413    @Override
20414    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20415            int userId) {
20416        int callingUid = Binder.getCallingUid();
20417        if (callingUid != Process.SYSTEM_UID) {
20418            throw new SecurityException(
20419                    "addPersistentPreferredActivity can only be run by the system");
20420        }
20421        if (filter.countActions() == 0) {
20422            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20423            return;
20424        }
20425        synchronized (mPackages) {
20426            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20427                    ":");
20428            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20429            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20430                    new PersistentPreferredActivity(filter, activity));
20431            scheduleWritePackageRestrictionsLocked(userId);
20432            postPreferredActivityChangedBroadcast(userId);
20433        }
20434    }
20435
20436    @Override
20437    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20438        int callingUid = Binder.getCallingUid();
20439        if (callingUid != Process.SYSTEM_UID) {
20440            throw new SecurityException(
20441                    "clearPackagePersistentPreferredActivities can only be run by the system");
20442        }
20443        ArrayList<PersistentPreferredActivity> removed = null;
20444        boolean changed = false;
20445        synchronized (mPackages) {
20446            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20447                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20448                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20449                        .valueAt(i);
20450                if (userId != thisUserId) {
20451                    continue;
20452                }
20453                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20454                while (it.hasNext()) {
20455                    PersistentPreferredActivity ppa = it.next();
20456                    // Mark entry for removal only if it matches the package name.
20457                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20458                        if (removed == null) {
20459                            removed = new ArrayList<PersistentPreferredActivity>();
20460                        }
20461                        removed.add(ppa);
20462                    }
20463                }
20464                if (removed != null) {
20465                    for (int j=0; j<removed.size(); j++) {
20466                        PersistentPreferredActivity ppa = removed.get(j);
20467                        ppir.removeFilter(ppa);
20468                    }
20469                    changed = true;
20470                }
20471            }
20472
20473            if (changed) {
20474                scheduleWritePackageRestrictionsLocked(userId);
20475                postPreferredActivityChangedBroadcast(userId);
20476            }
20477        }
20478    }
20479
20480    /**
20481     * Common machinery for picking apart a restored XML blob and passing
20482     * it to a caller-supplied functor to be applied to the running system.
20483     */
20484    private void restoreFromXml(XmlPullParser parser, int userId,
20485            String expectedStartTag, BlobXmlRestorer functor)
20486            throws IOException, XmlPullParserException {
20487        int type;
20488        while ((type = parser.next()) != XmlPullParser.START_TAG
20489                && type != XmlPullParser.END_DOCUMENT) {
20490        }
20491        if (type != XmlPullParser.START_TAG) {
20492            // oops didn't find a start tag?!
20493            if (DEBUG_BACKUP) {
20494                Slog.e(TAG, "Didn't find start tag during restore");
20495            }
20496            return;
20497        }
20498Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20499        // this is supposed to be TAG_PREFERRED_BACKUP
20500        if (!expectedStartTag.equals(parser.getName())) {
20501            if (DEBUG_BACKUP) {
20502                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20503            }
20504            return;
20505        }
20506
20507        // skip interfering stuff, then we're aligned with the backing implementation
20508        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20509Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20510        functor.apply(parser, userId);
20511    }
20512
20513    private interface BlobXmlRestorer {
20514        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20515    }
20516
20517    /**
20518     * Non-Binder method, support for the backup/restore mechanism: write the
20519     * full set of preferred activities in its canonical XML format.  Returns the
20520     * XML output as a byte array, or null if there is none.
20521     */
20522    @Override
20523    public byte[] getPreferredActivityBackup(int userId) {
20524        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20525            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20526        }
20527
20528        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20529        try {
20530            final XmlSerializer serializer = new FastXmlSerializer();
20531            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20532            serializer.startDocument(null, true);
20533            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20534
20535            synchronized (mPackages) {
20536                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20537            }
20538
20539            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20540            serializer.endDocument();
20541            serializer.flush();
20542        } catch (Exception e) {
20543            if (DEBUG_BACKUP) {
20544                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20545            }
20546            return null;
20547        }
20548
20549        return dataStream.toByteArray();
20550    }
20551
20552    @Override
20553    public void restorePreferredActivities(byte[] backup, int userId) {
20554        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20555            throw new SecurityException("Only the system may call restorePreferredActivities()");
20556        }
20557
20558        try {
20559            final XmlPullParser parser = Xml.newPullParser();
20560            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20561            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20562                    new BlobXmlRestorer() {
20563                        @Override
20564                        public void apply(XmlPullParser parser, int userId)
20565                                throws XmlPullParserException, IOException {
20566                            synchronized (mPackages) {
20567                                mSettings.readPreferredActivitiesLPw(parser, userId);
20568                            }
20569                        }
20570                    } );
20571        } catch (Exception e) {
20572            if (DEBUG_BACKUP) {
20573                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20574            }
20575        }
20576    }
20577
20578    /**
20579     * Non-Binder method, support for the backup/restore mechanism: write the
20580     * default browser (etc) settings in its canonical XML format.  Returns the default
20581     * browser XML representation as a byte array, or null if there is none.
20582     */
20583    @Override
20584    public byte[] getDefaultAppsBackup(int userId) {
20585        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20586            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20587        }
20588
20589        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20590        try {
20591            final XmlSerializer serializer = new FastXmlSerializer();
20592            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20593            serializer.startDocument(null, true);
20594            serializer.startTag(null, TAG_DEFAULT_APPS);
20595
20596            synchronized (mPackages) {
20597                mSettings.writeDefaultAppsLPr(serializer, userId);
20598            }
20599
20600            serializer.endTag(null, TAG_DEFAULT_APPS);
20601            serializer.endDocument();
20602            serializer.flush();
20603        } catch (Exception e) {
20604            if (DEBUG_BACKUP) {
20605                Slog.e(TAG, "Unable to write default apps for backup", e);
20606            }
20607            return null;
20608        }
20609
20610        return dataStream.toByteArray();
20611    }
20612
20613    @Override
20614    public void restoreDefaultApps(byte[] backup, int userId) {
20615        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20616            throw new SecurityException("Only the system may call restoreDefaultApps()");
20617        }
20618
20619        try {
20620            final XmlPullParser parser = Xml.newPullParser();
20621            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20622            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20623                    new BlobXmlRestorer() {
20624                        @Override
20625                        public void apply(XmlPullParser parser, int userId)
20626                                throws XmlPullParserException, IOException {
20627                            synchronized (mPackages) {
20628                                mSettings.readDefaultAppsLPw(parser, userId);
20629                            }
20630                        }
20631                    } );
20632        } catch (Exception e) {
20633            if (DEBUG_BACKUP) {
20634                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20635            }
20636        }
20637    }
20638
20639    @Override
20640    public byte[] getIntentFilterVerificationBackup(int userId) {
20641        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20642            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20643        }
20644
20645        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20646        try {
20647            final XmlSerializer serializer = new FastXmlSerializer();
20648            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20649            serializer.startDocument(null, true);
20650            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20651
20652            synchronized (mPackages) {
20653                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20654            }
20655
20656            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20657            serializer.endDocument();
20658            serializer.flush();
20659        } catch (Exception e) {
20660            if (DEBUG_BACKUP) {
20661                Slog.e(TAG, "Unable to write default apps for backup", e);
20662            }
20663            return null;
20664        }
20665
20666        return dataStream.toByteArray();
20667    }
20668
20669    @Override
20670    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20671        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20672            throw new SecurityException("Only the system may call restorePreferredActivities()");
20673        }
20674
20675        try {
20676            final XmlPullParser parser = Xml.newPullParser();
20677            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20678            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20679                    new BlobXmlRestorer() {
20680                        @Override
20681                        public void apply(XmlPullParser parser, int userId)
20682                                throws XmlPullParserException, IOException {
20683                            synchronized (mPackages) {
20684                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20685                                mSettings.writeLPr();
20686                            }
20687                        }
20688                    } );
20689        } catch (Exception e) {
20690            if (DEBUG_BACKUP) {
20691                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20692            }
20693        }
20694    }
20695
20696    @Override
20697    public byte[] getPermissionGrantBackup(int userId) {
20698        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20699            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20700        }
20701
20702        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20703        try {
20704            final XmlSerializer serializer = new FastXmlSerializer();
20705            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20706            serializer.startDocument(null, true);
20707            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20708
20709            synchronized (mPackages) {
20710                serializeRuntimePermissionGrantsLPr(serializer, userId);
20711            }
20712
20713            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20714            serializer.endDocument();
20715            serializer.flush();
20716        } catch (Exception e) {
20717            if (DEBUG_BACKUP) {
20718                Slog.e(TAG, "Unable to write default apps for backup", e);
20719            }
20720            return null;
20721        }
20722
20723        return dataStream.toByteArray();
20724    }
20725
20726    @Override
20727    public void restorePermissionGrants(byte[] backup, int userId) {
20728        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20729            throw new SecurityException("Only the system may call restorePermissionGrants()");
20730        }
20731
20732        try {
20733            final XmlPullParser parser = Xml.newPullParser();
20734            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20735            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20736                    new BlobXmlRestorer() {
20737                        @Override
20738                        public void apply(XmlPullParser parser, int userId)
20739                                throws XmlPullParserException, IOException {
20740                            synchronized (mPackages) {
20741                                processRestoredPermissionGrantsLPr(parser, userId);
20742                            }
20743                        }
20744                    } );
20745        } catch (Exception e) {
20746            if (DEBUG_BACKUP) {
20747                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20748            }
20749        }
20750    }
20751
20752    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20753            throws IOException {
20754        serializer.startTag(null, TAG_ALL_GRANTS);
20755
20756        final int N = mSettings.mPackages.size();
20757        for (int i = 0; i < N; i++) {
20758            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20759            boolean pkgGrantsKnown = false;
20760
20761            PermissionsState packagePerms = ps.getPermissionsState();
20762
20763            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20764                final int grantFlags = state.getFlags();
20765                // only look at grants that are not system/policy fixed
20766                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20767                    final boolean isGranted = state.isGranted();
20768                    // And only back up the user-twiddled state bits
20769                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20770                        final String packageName = mSettings.mPackages.keyAt(i);
20771                        if (!pkgGrantsKnown) {
20772                            serializer.startTag(null, TAG_GRANT);
20773                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20774                            pkgGrantsKnown = true;
20775                        }
20776
20777                        final boolean userSet =
20778                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20779                        final boolean userFixed =
20780                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20781                        final boolean revoke =
20782                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20783
20784                        serializer.startTag(null, TAG_PERMISSION);
20785                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20786                        if (isGranted) {
20787                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20788                        }
20789                        if (userSet) {
20790                            serializer.attribute(null, ATTR_USER_SET, "true");
20791                        }
20792                        if (userFixed) {
20793                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20794                        }
20795                        if (revoke) {
20796                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20797                        }
20798                        serializer.endTag(null, TAG_PERMISSION);
20799                    }
20800                }
20801            }
20802
20803            if (pkgGrantsKnown) {
20804                serializer.endTag(null, TAG_GRANT);
20805            }
20806        }
20807
20808        serializer.endTag(null, TAG_ALL_GRANTS);
20809    }
20810
20811    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20812            throws XmlPullParserException, IOException {
20813        String pkgName = null;
20814        int outerDepth = parser.getDepth();
20815        int type;
20816        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20817                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20818            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20819                continue;
20820            }
20821
20822            final String tagName = parser.getName();
20823            if (tagName.equals(TAG_GRANT)) {
20824                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20825                if (DEBUG_BACKUP) {
20826                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20827                }
20828            } else if (tagName.equals(TAG_PERMISSION)) {
20829
20830                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20831                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20832
20833                int newFlagSet = 0;
20834                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20835                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20836                }
20837                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20838                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20839                }
20840                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20841                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20842                }
20843                if (DEBUG_BACKUP) {
20844                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20845                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20846                }
20847                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20848                if (ps != null) {
20849                    // Already installed so we apply the grant immediately
20850                    if (DEBUG_BACKUP) {
20851                        Slog.v(TAG, "        + already installed; applying");
20852                    }
20853                    PermissionsState perms = ps.getPermissionsState();
20854                    BasePermission bp = mSettings.mPermissions.get(permName);
20855                    if (bp != null) {
20856                        if (isGranted) {
20857                            perms.grantRuntimePermission(bp, userId);
20858                        }
20859                        if (newFlagSet != 0) {
20860                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20861                        }
20862                    }
20863                } else {
20864                    // Need to wait for post-restore install to apply the grant
20865                    if (DEBUG_BACKUP) {
20866                        Slog.v(TAG, "        - not yet installed; saving for later");
20867                    }
20868                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20869                            isGranted, newFlagSet, userId);
20870                }
20871            } else {
20872                PackageManagerService.reportSettingsProblem(Log.WARN,
20873                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20874                XmlUtils.skipCurrentTag(parser);
20875            }
20876        }
20877
20878        scheduleWriteSettingsLocked();
20879        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20880    }
20881
20882    @Override
20883    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20884            int sourceUserId, int targetUserId, int flags) {
20885        mContext.enforceCallingOrSelfPermission(
20886                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20887        int callingUid = Binder.getCallingUid();
20888        enforceOwnerRights(ownerPackage, callingUid);
20889        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20890        if (intentFilter.countActions() == 0) {
20891            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20892            return;
20893        }
20894        synchronized (mPackages) {
20895            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20896                    ownerPackage, targetUserId, flags);
20897            CrossProfileIntentResolver resolver =
20898                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20899            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20900            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20901            if (existing != null) {
20902                int size = existing.size();
20903                for (int i = 0; i < size; i++) {
20904                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20905                        return;
20906                    }
20907                }
20908            }
20909            resolver.addFilter(newFilter);
20910            scheduleWritePackageRestrictionsLocked(sourceUserId);
20911        }
20912    }
20913
20914    @Override
20915    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20916        mContext.enforceCallingOrSelfPermission(
20917                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20918        final int callingUid = Binder.getCallingUid();
20919        enforceOwnerRights(ownerPackage, callingUid);
20920        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20921        synchronized (mPackages) {
20922            CrossProfileIntentResolver resolver =
20923                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20924            ArraySet<CrossProfileIntentFilter> set =
20925                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20926            for (CrossProfileIntentFilter filter : set) {
20927                if (filter.getOwnerPackage().equals(ownerPackage)) {
20928                    resolver.removeFilter(filter);
20929                }
20930            }
20931            scheduleWritePackageRestrictionsLocked(sourceUserId);
20932        }
20933    }
20934
20935    // Enforcing that callingUid is owning pkg on userId
20936    private void enforceOwnerRights(String pkg, int callingUid) {
20937        // The system owns everything.
20938        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20939            return;
20940        }
20941        final int callingUserId = UserHandle.getUserId(callingUid);
20942        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20943        if (pi == null) {
20944            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20945                    + callingUserId);
20946        }
20947        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20948            throw new SecurityException("Calling uid " + callingUid
20949                    + " does not own package " + pkg);
20950        }
20951    }
20952
20953    @Override
20954    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20955        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20956            return null;
20957        }
20958        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20959    }
20960
20961    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20962        UserManagerService ums = UserManagerService.getInstance();
20963        if (ums != null) {
20964            final UserInfo parent = ums.getProfileParent(userId);
20965            final int launcherUid = (parent != null) ? parent.id : userId;
20966            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20967            if (launcherComponent != null) {
20968                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20969                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20970                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20971                        .setPackage(launcherComponent.getPackageName());
20972                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20973            }
20974        }
20975    }
20976
20977    /**
20978     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20979     * then reports the most likely home activity or null if there are more than one.
20980     */
20981    private ComponentName getDefaultHomeActivity(int userId) {
20982        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20983        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20984        if (cn != null) {
20985            return cn;
20986        }
20987
20988        // Find the launcher with the highest priority and return that component if there are no
20989        // other home activity with the same priority.
20990        int lastPriority = Integer.MIN_VALUE;
20991        ComponentName lastComponent = null;
20992        final int size = allHomeCandidates.size();
20993        for (int i = 0; i < size; i++) {
20994            final ResolveInfo ri = allHomeCandidates.get(i);
20995            if (ri.priority > lastPriority) {
20996                lastComponent = ri.activityInfo.getComponentName();
20997                lastPriority = ri.priority;
20998            } else if (ri.priority == lastPriority) {
20999                // Two components found with same priority.
21000                lastComponent = null;
21001            }
21002        }
21003        return lastComponent;
21004    }
21005
21006    private Intent getHomeIntent() {
21007        Intent intent = new Intent(Intent.ACTION_MAIN);
21008        intent.addCategory(Intent.CATEGORY_HOME);
21009        intent.addCategory(Intent.CATEGORY_DEFAULT);
21010        return intent;
21011    }
21012
21013    private IntentFilter getHomeFilter() {
21014        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21015        filter.addCategory(Intent.CATEGORY_HOME);
21016        filter.addCategory(Intent.CATEGORY_DEFAULT);
21017        return filter;
21018    }
21019
21020    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21021            int userId) {
21022        Intent intent  = getHomeIntent();
21023        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21024                PackageManager.GET_META_DATA, userId);
21025        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21026                true, false, false, userId);
21027
21028        allHomeCandidates.clear();
21029        if (list != null) {
21030            for (ResolveInfo ri : list) {
21031                allHomeCandidates.add(ri);
21032            }
21033        }
21034        return (preferred == null || preferred.activityInfo == null)
21035                ? null
21036                : new ComponentName(preferred.activityInfo.packageName,
21037                        preferred.activityInfo.name);
21038    }
21039
21040    @Override
21041    public void setHomeActivity(ComponentName comp, int userId) {
21042        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21043            return;
21044        }
21045        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21046        getHomeActivitiesAsUser(homeActivities, userId);
21047
21048        boolean found = false;
21049
21050        final int size = homeActivities.size();
21051        final ComponentName[] set = new ComponentName[size];
21052        for (int i = 0; i < size; i++) {
21053            final ResolveInfo candidate = homeActivities.get(i);
21054            final ActivityInfo info = candidate.activityInfo;
21055            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21056            set[i] = activityName;
21057            if (!found && activityName.equals(comp)) {
21058                found = true;
21059            }
21060        }
21061        if (!found) {
21062            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21063                    + userId);
21064        }
21065        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21066                set, comp, userId);
21067    }
21068
21069    private @Nullable String getSetupWizardPackageName() {
21070        final Intent intent = new Intent(Intent.ACTION_MAIN);
21071        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21072
21073        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21074                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21075                        | MATCH_DISABLED_COMPONENTS,
21076                UserHandle.myUserId());
21077        if (matches.size() == 1) {
21078            return matches.get(0).getComponentInfo().packageName;
21079        } else {
21080            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21081                    + ": matches=" + matches);
21082            return null;
21083        }
21084    }
21085
21086    private @Nullable String getStorageManagerPackageName() {
21087        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21088
21089        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21090                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21091                        | MATCH_DISABLED_COMPONENTS,
21092                UserHandle.myUserId());
21093        if (matches.size() == 1) {
21094            return matches.get(0).getComponentInfo().packageName;
21095        } else {
21096            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21097                    + matches.size() + ": matches=" + matches);
21098            return null;
21099        }
21100    }
21101
21102    @Override
21103    public void setApplicationEnabledSetting(String appPackageName,
21104            int newState, int flags, int userId, String callingPackage) {
21105        if (!sUserManager.exists(userId)) return;
21106        if (callingPackage == null) {
21107            callingPackage = Integer.toString(Binder.getCallingUid());
21108        }
21109        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21110    }
21111
21112    @Override
21113    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21114        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21115        synchronized (mPackages) {
21116            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21117            if (pkgSetting != null) {
21118                pkgSetting.setUpdateAvailable(updateAvailable);
21119            }
21120        }
21121    }
21122
21123    @Override
21124    public void setComponentEnabledSetting(ComponentName componentName,
21125            int newState, int flags, int userId) {
21126        if (!sUserManager.exists(userId)) return;
21127        setEnabledSetting(componentName.getPackageName(),
21128                componentName.getClassName(), newState, flags, userId, null);
21129    }
21130
21131    private void setEnabledSetting(final String packageName, String className, int newState,
21132            final int flags, int userId, String callingPackage) {
21133        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21134              || newState == COMPONENT_ENABLED_STATE_ENABLED
21135              || newState == COMPONENT_ENABLED_STATE_DISABLED
21136              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21137              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21138            throw new IllegalArgumentException("Invalid new component state: "
21139                    + newState);
21140        }
21141        PackageSetting pkgSetting;
21142        final int callingUid = Binder.getCallingUid();
21143        final int permission;
21144        if (callingUid == Process.SYSTEM_UID) {
21145            permission = PackageManager.PERMISSION_GRANTED;
21146        } else {
21147            permission = mContext.checkCallingOrSelfPermission(
21148                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21149        }
21150        enforceCrossUserPermission(callingUid, userId,
21151                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21152        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21153        boolean sendNow = false;
21154        boolean isApp = (className == null);
21155        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21156        String componentName = isApp ? packageName : className;
21157        int packageUid = -1;
21158        ArrayList<String> components;
21159
21160        // reader
21161        synchronized (mPackages) {
21162            pkgSetting = mSettings.mPackages.get(packageName);
21163            if (pkgSetting == null) {
21164                if (!isCallerInstantApp) {
21165                    if (className == null) {
21166                        throw new IllegalArgumentException("Unknown package: " + packageName);
21167                    }
21168                    throw new IllegalArgumentException(
21169                            "Unknown component: " + packageName + "/" + className);
21170                } else {
21171                    // throw SecurityException to prevent leaking package information
21172                    throw new SecurityException(
21173                            "Attempt to change component state; "
21174                            + "pid=" + Binder.getCallingPid()
21175                            + ", uid=" + callingUid
21176                            + (className == null
21177                                    ? ", package=" + packageName
21178                                    : ", component=" + packageName + "/" + className));
21179                }
21180            }
21181        }
21182
21183        // Limit who can change which apps
21184        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21185            // Don't allow apps that don't have permission to modify other apps
21186            if (!allowedByPermission
21187                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21188                throw new SecurityException(
21189                        "Attempt to change component state; "
21190                        + "pid=" + Binder.getCallingPid()
21191                        + ", uid=" + callingUid
21192                        + (className == null
21193                                ? ", package=" + packageName
21194                                : ", component=" + packageName + "/" + className));
21195            }
21196            // Don't allow changing protected packages.
21197            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21198                throw new SecurityException("Cannot disable a protected package: " + packageName);
21199            }
21200        }
21201
21202        synchronized (mPackages) {
21203            if (callingUid == Process.SHELL_UID
21204                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21205                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21206                // unless it is a test package.
21207                int oldState = pkgSetting.getEnabled(userId);
21208                if (className == null
21209                    &&
21210                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21211                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21212                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21213                    &&
21214                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21215                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21216                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21217                    // ok
21218                } else {
21219                    throw new SecurityException(
21220                            "Shell cannot change component state for " + packageName + "/"
21221                            + className + " to " + newState);
21222                }
21223            }
21224            if (className == null) {
21225                // We're dealing with an application/package level state change
21226                if (pkgSetting.getEnabled(userId) == newState) {
21227                    // Nothing to do
21228                    return;
21229                }
21230                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21231                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21232                    // Don't care about who enables an app.
21233                    callingPackage = null;
21234                }
21235                pkgSetting.setEnabled(newState, userId, callingPackage);
21236                // pkgSetting.pkg.mSetEnabled = newState;
21237            } else {
21238                // We're dealing with a component level state change
21239                // First, verify that this is a valid class name.
21240                PackageParser.Package pkg = pkgSetting.pkg;
21241                if (pkg == null || !pkg.hasComponentClassName(className)) {
21242                    if (pkg != null &&
21243                            pkg.applicationInfo.targetSdkVersion >=
21244                                    Build.VERSION_CODES.JELLY_BEAN) {
21245                        throw new IllegalArgumentException("Component class " + className
21246                                + " does not exist in " + packageName);
21247                    } else {
21248                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21249                                + className + " does not exist in " + packageName);
21250                    }
21251                }
21252                switch (newState) {
21253                case COMPONENT_ENABLED_STATE_ENABLED:
21254                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21255                        return;
21256                    }
21257                    break;
21258                case COMPONENT_ENABLED_STATE_DISABLED:
21259                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21260                        return;
21261                    }
21262                    break;
21263                case COMPONENT_ENABLED_STATE_DEFAULT:
21264                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21265                        return;
21266                    }
21267                    break;
21268                default:
21269                    Slog.e(TAG, "Invalid new component state: " + newState);
21270                    return;
21271                }
21272            }
21273            scheduleWritePackageRestrictionsLocked(userId);
21274            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21275            final long callingId = Binder.clearCallingIdentity();
21276            try {
21277                updateInstantAppInstallerLocked(packageName);
21278            } finally {
21279                Binder.restoreCallingIdentity(callingId);
21280            }
21281            components = mPendingBroadcasts.get(userId, packageName);
21282            final boolean newPackage = components == null;
21283            if (newPackage) {
21284                components = new ArrayList<String>();
21285            }
21286            if (!components.contains(componentName)) {
21287                components.add(componentName);
21288            }
21289            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21290                sendNow = true;
21291                // Purge entry from pending broadcast list if another one exists already
21292                // since we are sending one right away.
21293                mPendingBroadcasts.remove(userId, packageName);
21294            } else {
21295                if (newPackage) {
21296                    mPendingBroadcasts.put(userId, packageName, components);
21297                }
21298                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21299                    // Schedule a message
21300                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21301                }
21302            }
21303        }
21304
21305        long callingId = Binder.clearCallingIdentity();
21306        try {
21307            if (sendNow) {
21308                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21309                sendPackageChangedBroadcast(packageName,
21310                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21311            }
21312        } finally {
21313            Binder.restoreCallingIdentity(callingId);
21314        }
21315    }
21316
21317    @Override
21318    public void flushPackageRestrictionsAsUser(int userId) {
21319        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21320            return;
21321        }
21322        if (!sUserManager.exists(userId)) {
21323            return;
21324        }
21325        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21326                false /* checkShell */, "flushPackageRestrictions");
21327        synchronized (mPackages) {
21328            mSettings.writePackageRestrictionsLPr(userId);
21329            mDirtyUsers.remove(userId);
21330            if (mDirtyUsers.isEmpty()) {
21331                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21332            }
21333        }
21334    }
21335
21336    private void sendPackageChangedBroadcast(String packageName,
21337            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21338        if (DEBUG_INSTALL)
21339            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21340                    + componentNames);
21341        Bundle extras = new Bundle(4);
21342        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21343        String nameList[] = new String[componentNames.size()];
21344        componentNames.toArray(nameList);
21345        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21346        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21347        extras.putInt(Intent.EXTRA_UID, packageUid);
21348        // If this is not reporting a change of the overall package, then only send it
21349        // to registered receivers.  We don't want to launch a swath of apps for every
21350        // little component state change.
21351        final int flags = !componentNames.contains(packageName)
21352                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21353        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21354                new int[] {UserHandle.getUserId(packageUid)});
21355    }
21356
21357    @Override
21358    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21359        if (!sUserManager.exists(userId)) return;
21360        final int callingUid = Binder.getCallingUid();
21361        if (getInstantAppPackageName(callingUid) != null) {
21362            return;
21363        }
21364        final int permission = mContext.checkCallingOrSelfPermission(
21365                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21366        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21367        enforceCrossUserPermission(callingUid, userId,
21368                true /* requireFullPermission */, true /* checkShell */, "stop package");
21369        // writer
21370        synchronized (mPackages) {
21371            final PackageSetting ps = mSettings.mPackages.get(packageName);
21372            if (!filterAppAccessLPr(ps, callingUid, userId)
21373                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21374                            allowedByPermission, callingUid, userId)) {
21375                scheduleWritePackageRestrictionsLocked(userId);
21376            }
21377        }
21378    }
21379
21380    @Override
21381    public String getInstallerPackageName(String packageName) {
21382        final int callingUid = Binder.getCallingUid();
21383        if (getInstantAppPackageName(callingUid) != null) {
21384            return null;
21385        }
21386        // reader
21387        synchronized (mPackages) {
21388            final PackageSetting ps = mSettings.mPackages.get(packageName);
21389            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21390                return null;
21391            }
21392            return mSettings.getInstallerPackageNameLPr(packageName);
21393        }
21394    }
21395
21396    public boolean isOrphaned(String packageName) {
21397        // reader
21398        synchronized (mPackages) {
21399            return mSettings.isOrphaned(packageName);
21400        }
21401    }
21402
21403    @Override
21404    public int getApplicationEnabledSetting(String packageName, int userId) {
21405        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21406        int callingUid = Binder.getCallingUid();
21407        enforceCrossUserPermission(callingUid, userId,
21408                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21409        // reader
21410        synchronized (mPackages) {
21411            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21412                return COMPONENT_ENABLED_STATE_DISABLED;
21413            }
21414            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21415        }
21416    }
21417
21418    @Override
21419    public int getComponentEnabledSetting(ComponentName component, int userId) {
21420        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21421        int callingUid = Binder.getCallingUid();
21422        enforceCrossUserPermission(callingUid, userId,
21423                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21424        synchronized (mPackages) {
21425            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21426                    component, TYPE_UNKNOWN, userId)) {
21427                return COMPONENT_ENABLED_STATE_DISABLED;
21428            }
21429            return mSettings.getComponentEnabledSettingLPr(component, userId);
21430        }
21431    }
21432
21433    @Override
21434    public void enterSafeMode() {
21435        enforceSystemOrRoot("Only the system can request entering safe mode");
21436
21437        if (!mSystemReady) {
21438            mSafeMode = true;
21439        }
21440    }
21441
21442    @Override
21443    public void systemReady() {
21444        enforceSystemOrRoot("Only the system can claim the system is ready");
21445
21446        mSystemReady = true;
21447        final ContentResolver resolver = mContext.getContentResolver();
21448        ContentObserver co = new ContentObserver(mHandler) {
21449            @Override
21450            public void onChange(boolean selfChange) {
21451                mEphemeralAppsDisabled =
21452                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21453                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21454            }
21455        };
21456        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21457                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21458                false, co, UserHandle.USER_SYSTEM);
21459        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21460                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21461        co.onChange(true);
21462
21463        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21464        // disabled after already being started.
21465        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21466                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21467
21468        // Read the compatibilty setting when the system is ready.
21469        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21470                mContext.getContentResolver(),
21471                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21472        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21473        if (DEBUG_SETTINGS) {
21474            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21475        }
21476
21477        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21478
21479        synchronized (mPackages) {
21480            // Verify that all of the preferred activity components actually
21481            // exist.  It is possible for applications to be updated and at
21482            // that point remove a previously declared activity component that
21483            // had been set as a preferred activity.  We try to clean this up
21484            // the next time we encounter that preferred activity, but it is
21485            // possible for the user flow to never be able to return to that
21486            // situation so here we do a sanity check to make sure we haven't
21487            // left any junk around.
21488            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21489            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21490                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21491                removed.clear();
21492                for (PreferredActivity pa : pir.filterSet()) {
21493                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21494                        removed.add(pa);
21495                    }
21496                }
21497                if (removed.size() > 0) {
21498                    for (int r=0; r<removed.size(); r++) {
21499                        PreferredActivity pa = removed.get(r);
21500                        Slog.w(TAG, "Removing dangling preferred activity: "
21501                                + pa.mPref.mComponent);
21502                        pir.removeFilter(pa);
21503                    }
21504                    mSettings.writePackageRestrictionsLPr(
21505                            mSettings.mPreferredActivities.keyAt(i));
21506                }
21507            }
21508
21509            for (int userId : UserManagerService.getInstance().getUserIds()) {
21510                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21511                    grantPermissionsUserIds = ArrayUtils.appendInt(
21512                            grantPermissionsUserIds, userId);
21513                }
21514            }
21515        }
21516        sUserManager.systemReady();
21517
21518        // If we upgraded grant all default permissions before kicking off.
21519        for (int userId : grantPermissionsUserIds) {
21520            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21521        }
21522
21523        // If we did not grant default permissions, we preload from this the
21524        // default permission exceptions lazily to ensure we don't hit the
21525        // disk on a new user creation.
21526        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21527            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21528        }
21529
21530        // Kick off any messages waiting for system ready
21531        if (mPostSystemReadyMessages != null) {
21532            for (Message msg : mPostSystemReadyMessages) {
21533                msg.sendToTarget();
21534            }
21535            mPostSystemReadyMessages = null;
21536        }
21537
21538        // Watch for external volumes that come and go over time
21539        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21540        storage.registerListener(mStorageListener);
21541
21542        mInstallerService.systemReady();
21543        mPackageDexOptimizer.systemReady();
21544
21545        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21546                StorageManagerInternal.class);
21547        StorageManagerInternal.addExternalStoragePolicy(
21548                new StorageManagerInternal.ExternalStorageMountPolicy() {
21549            @Override
21550            public int getMountMode(int uid, String packageName) {
21551                if (Process.isIsolated(uid)) {
21552                    return Zygote.MOUNT_EXTERNAL_NONE;
21553                }
21554                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21555                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21556                }
21557                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21558                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21559                }
21560                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21561                    return Zygote.MOUNT_EXTERNAL_READ;
21562                }
21563                return Zygote.MOUNT_EXTERNAL_WRITE;
21564            }
21565
21566            @Override
21567            public boolean hasExternalStorage(int uid, String packageName) {
21568                return true;
21569            }
21570        });
21571
21572        // Now that we're mostly running, clean up stale users and apps
21573        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21574        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21575
21576        if (mPrivappPermissionsViolations != null) {
21577            Slog.wtf(TAG,"Signature|privileged permissions not in "
21578                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21579            mPrivappPermissionsViolations = null;
21580        }
21581    }
21582
21583    public void waitForAppDataPrepared() {
21584        if (mPrepareAppDataFuture == null) {
21585            return;
21586        }
21587        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21588        mPrepareAppDataFuture = null;
21589    }
21590
21591    @Override
21592    public boolean isSafeMode() {
21593        // allow instant applications
21594        return mSafeMode;
21595    }
21596
21597    @Override
21598    public boolean hasSystemUidErrors() {
21599        // allow instant applications
21600        return mHasSystemUidErrors;
21601    }
21602
21603    static String arrayToString(int[] array) {
21604        StringBuffer buf = new StringBuffer(128);
21605        buf.append('[');
21606        if (array != null) {
21607            for (int i=0; i<array.length; i++) {
21608                if (i > 0) buf.append(", ");
21609                buf.append(array[i]);
21610            }
21611        }
21612        buf.append(']');
21613        return buf.toString();
21614    }
21615
21616    static class DumpState {
21617        public static final int DUMP_LIBS = 1 << 0;
21618        public static final int DUMP_FEATURES = 1 << 1;
21619        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21620        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21621        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21622        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21623        public static final int DUMP_PERMISSIONS = 1 << 6;
21624        public static final int DUMP_PACKAGES = 1 << 7;
21625        public static final int DUMP_SHARED_USERS = 1 << 8;
21626        public static final int DUMP_MESSAGES = 1 << 9;
21627        public static final int DUMP_PROVIDERS = 1 << 10;
21628        public static final int DUMP_VERIFIERS = 1 << 11;
21629        public static final int DUMP_PREFERRED = 1 << 12;
21630        public static final int DUMP_PREFERRED_XML = 1 << 13;
21631        public static final int DUMP_KEYSETS = 1 << 14;
21632        public static final int DUMP_VERSION = 1 << 15;
21633        public static final int DUMP_INSTALLS = 1 << 16;
21634        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21635        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21636        public static final int DUMP_FROZEN = 1 << 19;
21637        public static final int DUMP_DEXOPT = 1 << 20;
21638        public static final int DUMP_COMPILER_STATS = 1 << 21;
21639        public static final int DUMP_CHANGES = 1 << 22;
21640
21641        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21642
21643        private int mTypes;
21644
21645        private int mOptions;
21646
21647        private boolean mTitlePrinted;
21648
21649        private SharedUserSetting mSharedUser;
21650
21651        public boolean isDumping(int type) {
21652            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21653                return true;
21654            }
21655
21656            return (mTypes & type) != 0;
21657        }
21658
21659        public void setDump(int type) {
21660            mTypes |= type;
21661        }
21662
21663        public boolean isOptionEnabled(int option) {
21664            return (mOptions & option) != 0;
21665        }
21666
21667        public void setOptionEnabled(int option) {
21668            mOptions |= option;
21669        }
21670
21671        public boolean onTitlePrinted() {
21672            final boolean printed = mTitlePrinted;
21673            mTitlePrinted = true;
21674            return printed;
21675        }
21676
21677        public boolean getTitlePrinted() {
21678            return mTitlePrinted;
21679        }
21680
21681        public void setTitlePrinted(boolean enabled) {
21682            mTitlePrinted = enabled;
21683        }
21684
21685        public SharedUserSetting getSharedUser() {
21686            return mSharedUser;
21687        }
21688
21689        public void setSharedUser(SharedUserSetting user) {
21690            mSharedUser = user;
21691        }
21692    }
21693
21694    @Override
21695    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21696            FileDescriptor err, String[] args, ShellCallback callback,
21697            ResultReceiver resultReceiver) {
21698        (new PackageManagerShellCommand(this)).exec(
21699                this, in, out, err, args, callback, resultReceiver);
21700    }
21701
21702    @Override
21703    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21704        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21705
21706        DumpState dumpState = new DumpState();
21707        boolean fullPreferred = false;
21708        boolean checkin = false;
21709
21710        String packageName = null;
21711        ArraySet<String> permissionNames = null;
21712
21713        int opti = 0;
21714        while (opti < args.length) {
21715            String opt = args[opti];
21716            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21717                break;
21718            }
21719            opti++;
21720
21721            if ("-a".equals(opt)) {
21722                // Right now we only know how to print all.
21723            } else if ("-h".equals(opt)) {
21724                pw.println("Package manager dump options:");
21725                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21726                pw.println("    --checkin: dump for a checkin");
21727                pw.println("    -f: print details of intent filters");
21728                pw.println("    -h: print this help");
21729                pw.println("  cmd may be one of:");
21730                pw.println("    l[ibraries]: list known shared libraries");
21731                pw.println("    f[eatures]: list device features");
21732                pw.println("    k[eysets]: print known keysets");
21733                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21734                pw.println("    perm[issions]: dump permissions");
21735                pw.println("    permission [name ...]: dump declaration and use of given permission");
21736                pw.println("    pref[erred]: print preferred package settings");
21737                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21738                pw.println("    prov[iders]: dump content providers");
21739                pw.println("    p[ackages]: dump installed packages");
21740                pw.println("    s[hared-users]: dump shared user IDs");
21741                pw.println("    m[essages]: print collected runtime messages");
21742                pw.println("    v[erifiers]: print package verifier info");
21743                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21744                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21745                pw.println("    version: print database version info");
21746                pw.println("    write: write current settings now");
21747                pw.println("    installs: details about install sessions");
21748                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21749                pw.println("    dexopt: dump dexopt state");
21750                pw.println("    compiler-stats: dump compiler statistics");
21751                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21752                pw.println("    <package.name>: info about given package");
21753                return;
21754            } else if ("--checkin".equals(opt)) {
21755                checkin = true;
21756            } else if ("-f".equals(opt)) {
21757                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21758            } else if ("--proto".equals(opt)) {
21759                dumpProto(fd);
21760                return;
21761            } else {
21762                pw.println("Unknown argument: " + opt + "; use -h for help");
21763            }
21764        }
21765
21766        // Is the caller requesting to dump a particular piece of data?
21767        if (opti < args.length) {
21768            String cmd = args[opti];
21769            opti++;
21770            // Is this a package name?
21771            if ("android".equals(cmd) || cmd.contains(".")) {
21772                packageName = cmd;
21773                // When dumping a single package, we always dump all of its
21774                // filter information since the amount of data will be reasonable.
21775                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21776            } else if ("check-permission".equals(cmd)) {
21777                if (opti >= args.length) {
21778                    pw.println("Error: check-permission missing permission argument");
21779                    return;
21780                }
21781                String perm = args[opti];
21782                opti++;
21783                if (opti >= args.length) {
21784                    pw.println("Error: check-permission missing package argument");
21785                    return;
21786                }
21787
21788                String pkg = args[opti];
21789                opti++;
21790                int user = UserHandle.getUserId(Binder.getCallingUid());
21791                if (opti < args.length) {
21792                    try {
21793                        user = Integer.parseInt(args[opti]);
21794                    } catch (NumberFormatException e) {
21795                        pw.println("Error: check-permission user argument is not a number: "
21796                                + args[opti]);
21797                        return;
21798                    }
21799                }
21800
21801                // Normalize package name to handle renamed packages and static libs
21802                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21803
21804                pw.println(checkPermission(perm, pkg, user));
21805                return;
21806            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21807                dumpState.setDump(DumpState.DUMP_LIBS);
21808            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21809                dumpState.setDump(DumpState.DUMP_FEATURES);
21810            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21811                if (opti >= args.length) {
21812                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21813                            | DumpState.DUMP_SERVICE_RESOLVERS
21814                            | DumpState.DUMP_RECEIVER_RESOLVERS
21815                            | DumpState.DUMP_CONTENT_RESOLVERS);
21816                } else {
21817                    while (opti < args.length) {
21818                        String name = args[opti];
21819                        if ("a".equals(name) || "activity".equals(name)) {
21820                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21821                        } else if ("s".equals(name) || "service".equals(name)) {
21822                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21823                        } else if ("r".equals(name) || "receiver".equals(name)) {
21824                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21825                        } else if ("c".equals(name) || "content".equals(name)) {
21826                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21827                        } else {
21828                            pw.println("Error: unknown resolver table type: " + name);
21829                            return;
21830                        }
21831                        opti++;
21832                    }
21833                }
21834            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21835                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21836            } else if ("permission".equals(cmd)) {
21837                if (opti >= args.length) {
21838                    pw.println("Error: permission requires permission name");
21839                    return;
21840                }
21841                permissionNames = new ArraySet<>();
21842                while (opti < args.length) {
21843                    permissionNames.add(args[opti]);
21844                    opti++;
21845                }
21846                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21847                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21848            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21849                dumpState.setDump(DumpState.DUMP_PREFERRED);
21850            } else if ("preferred-xml".equals(cmd)) {
21851                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21852                if (opti < args.length && "--full".equals(args[opti])) {
21853                    fullPreferred = true;
21854                    opti++;
21855                }
21856            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21857                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21858            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21859                dumpState.setDump(DumpState.DUMP_PACKAGES);
21860            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21861                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21862            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21863                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21864            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21865                dumpState.setDump(DumpState.DUMP_MESSAGES);
21866            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21867                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21868            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21869                    || "intent-filter-verifiers".equals(cmd)) {
21870                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21871            } else if ("version".equals(cmd)) {
21872                dumpState.setDump(DumpState.DUMP_VERSION);
21873            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21874                dumpState.setDump(DumpState.DUMP_KEYSETS);
21875            } else if ("installs".equals(cmd)) {
21876                dumpState.setDump(DumpState.DUMP_INSTALLS);
21877            } else if ("frozen".equals(cmd)) {
21878                dumpState.setDump(DumpState.DUMP_FROZEN);
21879            } else if ("dexopt".equals(cmd)) {
21880                dumpState.setDump(DumpState.DUMP_DEXOPT);
21881            } else if ("compiler-stats".equals(cmd)) {
21882                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21883            } else if ("changes".equals(cmd)) {
21884                dumpState.setDump(DumpState.DUMP_CHANGES);
21885            } else if ("write".equals(cmd)) {
21886                synchronized (mPackages) {
21887                    mSettings.writeLPr();
21888                    pw.println("Settings written.");
21889                    return;
21890                }
21891            }
21892        }
21893
21894        if (checkin) {
21895            pw.println("vers,1");
21896        }
21897
21898        // reader
21899        synchronized (mPackages) {
21900            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21901                if (!checkin) {
21902                    if (dumpState.onTitlePrinted())
21903                        pw.println();
21904                    pw.println("Database versions:");
21905                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21906                }
21907            }
21908
21909            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21910                if (!checkin) {
21911                    if (dumpState.onTitlePrinted())
21912                        pw.println();
21913                    pw.println("Verifiers:");
21914                    pw.print("  Required: ");
21915                    pw.print(mRequiredVerifierPackage);
21916                    pw.print(" (uid=");
21917                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21918                            UserHandle.USER_SYSTEM));
21919                    pw.println(")");
21920                } else if (mRequiredVerifierPackage != null) {
21921                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21922                    pw.print(",");
21923                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21924                            UserHandle.USER_SYSTEM));
21925                }
21926            }
21927
21928            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21929                    packageName == null) {
21930                if (mIntentFilterVerifierComponent != null) {
21931                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21932                    if (!checkin) {
21933                        if (dumpState.onTitlePrinted())
21934                            pw.println();
21935                        pw.println("Intent Filter Verifier:");
21936                        pw.print("  Using: ");
21937                        pw.print(verifierPackageName);
21938                        pw.print(" (uid=");
21939                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21940                                UserHandle.USER_SYSTEM));
21941                        pw.println(")");
21942                    } else if (verifierPackageName != null) {
21943                        pw.print("ifv,"); pw.print(verifierPackageName);
21944                        pw.print(",");
21945                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21946                                UserHandle.USER_SYSTEM));
21947                    }
21948                } else {
21949                    pw.println();
21950                    pw.println("No Intent Filter Verifier available!");
21951                }
21952            }
21953
21954            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21955                boolean printedHeader = false;
21956                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21957                while (it.hasNext()) {
21958                    String libName = it.next();
21959                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21960                    if (versionedLib == null) {
21961                        continue;
21962                    }
21963                    final int versionCount = versionedLib.size();
21964                    for (int i = 0; i < versionCount; i++) {
21965                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21966                        if (!checkin) {
21967                            if (!printedHeader) {
21968                                if (dumpState.onTitlePrinted())
21969                                    pw.println();
21970                                pw.println("Libraries:");
21971                                printedHeader = true;
21972                            }
21973                            pw.print("  ");
21974                        } else {
21975                            pw.print("lib,");
21976                        }
21977                        pw.print(libEntry.info.getName());
21978                        if (libEntry.info.isStatic()) {
21979                            pw.print(" version=" + libEntry.info.getVersion());
21980                        }
21981                        if (!checkin) {
21982                            pw.print(" -> ");
21983                        }
21984                        if (libEntry.path != null) {
21985                            pw.print(" (jar) ");
21986                            pw.print(libEntry.path);
21987                        } else {
21988                            pw.print(" (apk) ");
21989                            pw.print(libEntry.apk);
21990                        }
21991                        pw.println();
21992                    }
21993                }
21994            }
21995
21996            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21997                if (dumpState.onTitlePrinted())
21998                    pw.println();
21999                if (!checkin) {
22000                    pw.println("Features:");
22001                }
22002
22003                synchronized (mAvailableFeatures) {
22004                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22005                        if (checkin) {
22006                            pw.print("feat,");
22007                            pw.print(feat.name);
22008                            pw.print(",");
22009                            pw.println(feat.version);
22010                        } else {
22011                            pw.print("  ");
22012                            pw.print(feat.name);
22013                            if (feat.version > 0) {
22014                                pw.print(" version=");
22015                                pw.print(feat.version);
22016                            }
22017                            pw.println();
22018                        }
22019                    }
22020                }
22021            }
22022
22023            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22024                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22025                        : "Activity Resolver Table:", "  ", packageName,
22026                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22027                    dumpState.setTitlePrinted(true);
22028                }
22029            }
22030            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22031                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22032                        : "Receiver Resolver Table:", "  ", packageName,
22033                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22034                    dumpState.setTitlePrinted(true);
22035                }
22036            }
22037            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22038                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22039                        : "Service Resolver Table:", "  ", packageName,
22040                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22041                    dumpState.setTitlePrinted(true);
22042                }
22043            }
22044            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22045                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22046                        : "Provider Resolver Table:", "  ", packageName,
22047                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22048                    dumpState.setTitlePrinted(true);
22049                }
22050            }
22051
22052            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22053                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22054                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22055                    int user = mSettings.mPreferredActivities.keyAt(i);
22056                    if (pir.dump(pw,
22057                            dumpState.getTitlePrinted()
22058                                ? "\nPreferred Activities User " + user + ":"
22059                                : "Preferred Activities User " + user + ":", "  ",
22060                            packageName, true, false)) {
22061                        dumpState.setTitlePrinted(true);
22062                    }
22063                }
22064            }
22065
22066            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22067                pw.flush();
22068                FileOutputStream fout = new FileOutputStream(fd);
22069                BufferedOutputStream str = new BufferedOutputStream(fout);
22070                XmlSerializer serializer = new FastXmlSerializer();
22071                try {
22072                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22073                    serializer.startDocument(null, true);
22074                    serializer.setFeature(
22075                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22076                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22077                    serializer.endDocument();
22078                    serializer.flush();
22079                } catch (IllegalArgumentException e) {
22080                    pw.println("Failed writing: " + e);
22081                } catch (IllegalStateException e) {
22082                    pw.println("Failed writing: " + e);
22083                } catch (IOException e) {
22084                    pw.println("Failed writing: " + e);
22085                }
22086            }
22087
22088            if (!checkin
22089                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22090                    && packageName == null) {
22091                pw.println();
22092                int count = mSettings.mPackages.size();
22093                if (count == 0) {
22094                    pw.println("No applications!");
22095                    pw.println();
22096                } else {
22097                    final String prefix = "  ";
22098                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22099                    if (allPackageSettings.size() == 0) {
22100                        pw.println("No domain preferred apps!");
22101                        pw.println();
22102                    } else {
22103                        pw.println("App verification status:");
22104                        pw.println();
22105                        count = 0;
22106                        for (PackageSetting ps : allPackageSettings) {
22107                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22108                            if (ivi == null || ivi.getPackageName() == null) continue;
22109                            pw.println(prefix + "Package: " + ivi.getPackageName());
22110                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22111                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22112                            pw.println();
22113                            count++;
22114                        }
22115                        if (count == 0) {
22116                            pw.println(prefix + "No app verification established.");
22117                            pw.println();
22118                        }
22119                        for (int userId : sUserManager.getUserIds()) {
22120                            pw.println("App linkages for user " + userId + ":");
22121                            pw.println();
22122                            count = 0;
22123                            for (PackageSetting ps : allPackageSettings) {
22124                                final long status = ps.getDomainVerificationStatusForUser(userId);
22125                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22126                                        && !DEBUG_DOMAIN_VERIFICATION) {
22127                                    continue;
22128                                }
22129                                pw.println(prefix + "Package: " + ps.name);
22130                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22131                                String statusStr = IntentFilterVerificationInfo.
22132                                        getStatusStringFromValue(status);
22133                                pw.println(prefix + "Status:  " + statusStr);
22134                                pw.println();
22135                                count++;
22136                            }
22137                            if (count == 0) {
22138                                pw.println(prefix + "No configured app linkages.");
22139                                pw.println();
22140                            }
22141                        }
22142                    }
22143                }
22144            }
22145
22146            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22147                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22148                if (packageName == null && permissionNames == null) {
22149                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22150                        if (iperm == 0) {
22151                            if (dumpState.onTitlePrinted())
22152                                pw.println();
22153                            pw.println("AppOp Permissions:");
22154                        }
22155                        pw.print("  AppOp Permission ");
22156                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22157                        pw.println(":");
22158                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22159                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22160                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22161                        }
22162                    }
22163                }
22164            }
22165
22166            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22167                boolean printedSomething = false;
22168                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22169                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22170                        continue;
22171                    }
22172                    if (!printedSomething) {
22173                        if (dumpState.onTitlePrinted())
22174                            pw.println();
22175                        pw.println("Registered ContentProviders:");
22176                        printedSomething = true;
22177                    }
22178                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22179                    pw.print("    "); pw.println(p.toString());
22180                }
22181                printedSomething = false;
22182                for (Map.Entry<String, PackageParser.Provider> entry :
22183                        mProvidersByAuthority.entrySet()) {
22184                    PackageParser.Provider p = entry.getValue();
22185                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22186                        continue;
22187                    }
22188                    if (!printedSomething) {
22189                        if (dumpState.onTitlePrinted())
22190                            pw.println();
22191                        pw.println("ContentProvider Authorities:");
22192                        printedSomething = true;
22193                    }
22194                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22195                    pw.print("    "); pw.println(p.toString());
22196                    if (p.info != null && p.info.applicationInfo != null) {
22197                        final String appInfo = p.info.applicationInfo.toString();
22198                        pw.print("      applicationInfo="); pw.println(appInfo);
22199                    }
22200                }
22201            }
22202
22203            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22204                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22205            }
22206
22207            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22208                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22209            }
22210
22211            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22212                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22213            }
22214
22215            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22216                if (dumpState.onTitlePrinted()) pw.println();
22217                pw.println("Package Changes:");
22218                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22219                final int K = mChangedPackages.size();
22220                for (int i = 0; i < K; i++) {
22221                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22222                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22223                    final int N = changes.size();
22224                    if (N == 0) {
22225                        pw.print("    "); pw.println("No packages changed");
22226                    } else {
22227                        for (int j = 0; j < N; j++) {
22228                            final String pkgName = changes.valueAt(j);
22229                            final int sequenceNumber = changes.keyAt(j);
22230                            pw.print("    ");
22231                            pw.print("seq=");
22232                            pw.print(sequenceNumber);
22233                            pw.print(", package=");
22234                            pw.println(pkgName);
22235                        }
22236                    }
22237                }
22238            }
22239
22240            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22241                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22242            }
22243
22244            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22245                // XXX should handle packageName != null by dumping only install data that
22246                // the given package is involved with.
22247                if (dumpState.onTitlePrinted()) pw.println();
22248
22249                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22250                ipw.println();
22251                ipw.println("Frozen packages:");
22252                ipw.increaseIndent();
22253                if (mFrozenPackages.size() == 0) {
22254                    ipw.println("(none)");
22255                } else {
22256                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22257                        ipw.println(mFrozenPackages.valueAt(i));
22258                    }
22259                }
22260                ipw.decreaseIndent();
22261            }
22262
22263            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22264                if (dumpState.onTitlePrinted()) pw.println();
22265                dumpDexoptStateLPr(pw, packageName);
22266            }
22267
22268            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22269                if (dumpState.onTitlePrinted()) pw.println();
22270                dumpCompilerStatsLPr(pw, packageName);
22271            }
22272
22273            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22274                if (dumpState.onTitlePrinted()) pw.println();
22275                mSettings.dumpReadMessagesLPr(pw, dumpState);
22276
22277                pw.println();
22278                pw.println("Package warning messages:");
22279                BufferedReader in = null;
22280                String line = null;
22281                try {
22282                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22283                    while ((line = in.readLine()) != null) {
22284                        if (line.contains("ignored: updated version")) continue;
22285                        pw.println(line);
22286                    }
22287                } catch (IOException ignored) {
22288                } finally {
22289                    IoUtils.closeQuietly(in);
22290                }
22291            }
22292
22293            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22294                BufferedReader in = null;
22295                String line = null;
22296                try {
22297                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22298                    while ((line = in.readLine()) != null) {
22299                        if (line.contains("ignored: updated version")) continue;
22300                        pw.print("msg,");
22301                        pw.println(line);
22302                    }
22303                } catch (IOException ignored) {
22304                } finally {
22305                    IoUtils.closeQuietly(in);
22306                }
22307            }
22308        }
22309
22310        // PackageInstaller should be called outside of mPackages lock
22311        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22312            // XXX should handle packageName != null by dumping only install data that
22313            // the given package is involved with.
22314            if (dumpState.onTitlePrinted()) pw.println();
22315            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22316        }
22317    }
22318
22319    private void dumpProto(FileDescriptor fd) {
22320        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22321
22322        synchronized (mPackages) {
22323            final long requiredVerifierPackageToken =
22324                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22325            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22326            proto.write(
22327                    PackageServiceDumpProto.PackageShortProto.UID,
22328                    getPackageUid(
22329                            mRequiredVerifierPackage,
22330                            MATCH_DEBUG_TRIAGED_MISSING,
22331                            UserHandle.USER_SYSTEM));
22332            proto.end(requiredVerifierPackageToken);
22333
22334            if (mIntentFilterVerifierComponent != null) {
22335                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22336                final long verifierPackageToken =
22337                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22338                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22339                proto.write(
22340                        PackageServiceDumpProto.PackageShortProto.UID,
22341                        getPackageUid(
22342                                verifierPackageName,
22343                                MATCH_DEBUG_TRIAGED_MISSING,
22344                                UserHandle.USER_SYSTEM));
22345                proto.end(verifierPackageToken);
22346            }
22347
22348            dumpSharedLibrariesProto(proto);
22349            dumpFeaturesProto(proto);
22350            mSettings.dumpPackagesProto(proto);
22351            mSettings.dumpSharedUsersProto(proto);
22352            dumpMessagesProto(proto);
22353        }
22354        proto.flush();
22355    }
22356
22357    private void dumpMessagesProto(ProtoOutputStream proto) {
22358        BufferedReader in = null;
22359        String line = null;
22360        try {
22361            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22362            while ((line = in.readLine()) != null) {
22363                if (line.contains("ignored: updated version")) continue;
22364                proto.write(PackageServiceDumpProto.MESSAGES, line);
22365            }
22366        } catch (IOException ignored) {
22367        } finally {
22368            IoUtils.closeQuietly(in);
22369        }
22370    }
22371
22372    private void dumpFeaturesProto(ProtoOutputStream proto) {
22373        synchronized (mAvailableFeatures) {
22374            final int count = mAvailableFeatures.size();
22375            for (int i = 0; i < count; i++) {
22376                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22377                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22378                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22379                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22380                proto.end(featureToken);
22381            }
22382        }
22383    }
22384
22385    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22386        final int count = mSharedLibraries.size();
22387        for (int i = 0; i < count; i++) {
22388            final String libName = mSharedLibraries.keyAt(i);
22389            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22390            if (versionedLib == null) {
22391                continue;
22392            }
22393            final int versionCount = versionedLib.size();
22394            for (int j = 0; j < versionCount; j++) {
22395                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22396                final long sharedLibraryToken =
22397                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22398                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22399                final boolean isJar = (libEntry.path != null);
22400                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22401                if (isJar) {
22402                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22403                } else {
22404                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22405                }
22406                proto.end(sharedLibraryToken);
22407            }
22408        }
22409    }
22410
22411    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22412        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22413        ipw.println();
22414        ipw.println("Dexopt state:");
22415        ipw.increaseIndent();
22416        Collection<PackageParser.Package> packages = null;
22417        if (packageName != null) {
22418            PackageParser.Package targetPackage = mPackages.get(packageName);
22419            if (targetPackage != null) {
22420                packages = Collections.singletonList(targetPackage);
22421            } else {
22422                ipw.println("Unable to find package: " + packageName);
22423                return;
22424            }
22425        } else {
22426            packages = mPackages.values();
22427        }
22428
22429        for (PackageParser.Package pkg : packages) {
22430            ipw.println("[" + pkg.packageName + "]");
22431            ipw.increaseIndent();
22432            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22433            ipw.decreaseIndent();
22434        }
22435    }
22436
22437    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22438        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22439        ipw.println();
22440        ipw.println("Compiler stats:");
22441        ipw.increaseIndent();
22442        Collection<PackageParser.Package> packages = null;
22443        if (packageName != null) {
22444            PackageParser.Package targetPackage = mPackages.get(packageName);
22445            if (targetPackage != null) {
22446                packages = Collections.singletonList(targetPackage);
22447            } else {
22448                ipw.println("Unable to find package: " + packageName);
22449                return;
22450            }
22451        } else {
22452            packages = mPackages.values();
22453        }
22454
22455        for (PackageParser.Package pkg : packages) {
22456            ipw.println("[" + pkg.packageName + "]");
22457            ipw.increaseIndent();
22458
22459            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22460            if (stats == null) {
22461                ipw.println("(No recorded stats)");
22462            } else {
22463                stats.dump(ipw);
22464            }
22465            ipw.decreaseIndent();
22466        }
22467    }
22468
22469    private String dumpDomainString(String packageName) {
22470        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22471                .getList();
22472        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22473
22474        ArraySet<String> result = new ArraySet<>();
22475        if (iviList.size() > 0) {
22476            for (IntentFilterVerificationInfo ivi : iviList) {
22477                for (String host : ivi.getDomains()) {
22478                    result.add(host);
22479                }
22480            }
22481        }
22482        if (filters != null && filters.size() > 0) {
22483            for (IntentFilter filter : filters) {
22484                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22485                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22486                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22487                    result.addAll(filter.getHostsList());
22488                }
22489            }
22490        }
22491
22492        StringBuilder sb = new StringBuilder(result.size() * 16);
22493        for (String domain : result) {
22494            if (sb.length() > 0) sb.append(" ");
22495            sb.append(domain);
22496        }
22497        return sb.toString();
22498    }
22499
22500    // ------- apps on sdcard specific code -------
22501    static final boolean DEBUG_SD_INSTALL = false;
22502
22503    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22504
22505    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22506
22507    private boolean mMediaMounted = false;
22508
22509    static String getEncryptKey() {
22510        try {
22511            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22512                    SD_ENCRYPTION_KEYSTORE_NAME);
22513            if (sdEncKey == null) {
22514                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22515                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22516                if (sdEncKey == null) {
22517                    Slog.e(TAG, "Failed to create encryption keys");
22518                    return null;
22519                }
22520            }
22521            return sdEncKey;
22522        } catch (NoSuchAlgorithmException nsae) {
22523            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22524            return null;
22525        } catch (IOException ioe) {
22526            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22527            return null;
22528        }
22529    }
22530
22531    /*
22532     * Update media status on PackageManager.
22533     */
22534    @Override
22535    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22536        enforceSystemOrRoot("Media status can only be updated by the system");
22537        // reader; this apparently protects mMediaMounted, but should probably
22538        // be a different lock in that case.
22539        synchronized (mPackages) {
22540            Log.i(TAG, "Updating external media status from "
22541                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22542                    + (mediaStatus ? "mounted" : "unmounted"));
22543            if (DEBUG_SD_INSTALL)
22544                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22545                        + ", mMediaMounted=" + mMediaMounted);
22546            if (mediaStatus == mMediaMounted) {
22547                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22548                        : 0, -1);
22549                mHandler.sendMessage(msg);
22550                return;
22551            }
22552            mMediaMounted = mediaStatus;
22553        }
22554        // Queue up an async operation since the package installation may take a
22555        // little while.
22556        mHandler.post(new Runnable() {
22557            public void run() {
22558                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22559            }
22560        });
22561    }
22562
22563    /**
22564     * Called by StorageManagerService when the initial ASECs to scan are available.
22565     * Should block until all the ASEC containers are finished being scanned.
22566     */
22567    public void scanAvailableAsecs() {
22568        updateExternalMediaStatusInner(true, false, false);
22569    }
22570
22571    /*
22572     * Collect information of applications on external media, map them against
22573     * existing containers and update information based on current mount status.
22574     * Please note that we always have to report status if reportStatus has been
22575     * set to true especially when unloading packages.
22576     */
22577    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22578            boolean externalStorage) {
22579        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22580        int[] uidArr = EmptyArray.INT;
22581
22582        final String[] list = PackageHelper.getSecureContainerList();
22583        if (ArrayUtils.isEmpty(list)) {
22584            Log.i(TAG, "No secure containers found");
22585        } else {
22586            // Process list of secure containers and categorize them
22587            // as active or stale based on their package internal state.
22588
22589            // reader
22590            synchronized (mPackages) {
22591                for (String cid : list) {
22592                    // Leave stages untouched for now; installer service owns them
22593                    if (PackageInstallerService.isStageName(cid)) continue;
22594
22595                    if (DEBUG_SD_INSTALL)
22596                        Log.i(TAG, "Processing container " + cid);
22597                    String pkgName = getAsecPackageName(cid);
22598                    if (pkgName == null) {
22599                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22600                        continue;
22601                    }
22602                    if (DEBUG_SD_INSTALL)
22603                        Log.i(TAG, "Looking for pkg : " + pkgName);
22604
22605                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22606                    if (ps == null) {
22607                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22608                        continue;
22609                    }
22610
22611                    /*
22612                     * Skip packages that are not external if we're unmounting
22613                     * external storage.
22614                     */
22615                    if (externalStorage && !isMounted && !isExternal(ps)) {
22616                        continue;
22617                    }
22618
22619                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22620                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22621                    // The package status is changed only if the code path
22622                    // matches between settings and the container id.
22623                    if (ps.codePathString != null
22624                            && ps.codePathString.startsWith(args.getCodePath())) {
22625                        if (DEBUG_SD_INSTALL) {
22626                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22627                                    + " at code path: " + ps.codePathString);
22628                        }
22629
22630                        // We do have a valid package installed on sdcard
22631                        processCids.put(args, ps.codePathString);
22632                        final int uid = ps.appId;
22633                        if (uid != -1) {
22634                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22635                        }
22636                    } else {
22637                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22638                                + ps.codePathString);
22639                    }
22640                }
22641            }
22642
22643            Arrays.sort(uidArr);
22644        }
22645
22646        // Process packages with valid entries.
22647        if (isMounted) {
22648            if (DEBUG_SD_INSTALL)
22649                Log.i(TAG, "Loading packages");
22650            loadMediaPackages(processCids, uidArr, externalStorage);
22651            startCleaningPackages();
22652            mInstallerService.onSecureContainersAvailable();
22653        } else {
22654            if (DEBUG_SD_INSTALL)
22655                Log.i(TAG, "Unloading packages");
22656            unloadMediaPackages(processCids, uidArr, reportStatus);
22657        }
22658    }
22659
22660    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22661            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22662        final int size = infos.size();
22663        final String[] packageNames = new String[size];
22664        final int[] packageUids = new int[size];
22665        for (int i = 0; i < size; i++) {
22666            final ApplicationInfo info = infos.get(i);
22667            packageNames[i] = info.packageName;
22668            packageUids[i] = info.uid;
22669        }
22670        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22671                finishedReceiver);
22672    }
22673
22674    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22675            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22676        sendResourcesChangedBroadcast(mediaStatus, replacing,
22677                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22678    }
22679
22680    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22681            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22682        int size = pkgList.length;
22683        if (size > 0) {
22684            // Send broadcasts here
22685            Bundle extras = new Bundle();
22686            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22687            if (uidArr != null) {
22688                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22689            }
22690            if (replacing) {
22691                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22692            }
22693            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22694                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22695            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22696        }
22697    }
22698
22699   /*
22700     * Look at potentially valid container ids from processCids If package
22701     * information doesn't match the one on record or package scanning fails,
22702     * the cid is added to list of removeCids. We currently don't delete stale
22703     * containers.
22704     */
22705    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22706            boolean externalStorage) {
22707        ArrayList<String> pkgList = new ArrayList<String>();
22708        Set<AsecInstallArgs> keys = processCids.keySet();
22709
22710        for (AsecInstallArgs args : keys) {
22711            String codePath = processCids.get(args);
22712            if (DEBUG_SD_INSTALL)
22713                Log.i(TAG, "Loading container : " + args.cid);
22714            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22715            try {
22716                // Make sure there are no container errors first.
22717                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22718                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22719                            + " when installing from sdcard");
22720                    continue;
22721                }
22722                // Check code path here.
22723                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22724                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22725                            + " does not match one in settings " + codePath);
22726                    continue;
22727                }
22728                // Parse package
22729                int parseFlags = mDefParseFlags;
22730                if (args.isExternalAsec()) {
22731                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22732                }
22733                if (args.isFwdLocked()) {
22734                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22735                }
22736
22737                synchronized (mInstallLock) {
22738                    PackageParser.Package pkg = null;
22739                    try {
22740                        // Sadly we don't know the package name yet to freeze it
22741                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22742                                SCAN_IGNORE_FROZEN, 0, null);
22743                    } catch (PackageManagerException e) {
22744                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22745                    }
22746                    // Scan the package
22747                    if (pkg != null) {
22748                        /*
22749                         * TODO why is the lock being held? doPostInstall is
22750                         * called in other places without the lock. This needs
22751                         * to be straightened out.
22752                         */
22753                        // writer
22754                        synchronized (mPackages) {
22755                            retCode = PackageManager.INSTALL_SUCCEEDED;
22756                            pkgList.add(pkg.packageName);
22757                            // Post process args
22758                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22759                                    pkg.applicationInfo.uid);
22760                        }
22761                    } else {
22762                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22763                    }
22764                }
22765
22766            } finally {
22767                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22768                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22769                }
22770            }
22771        }
22772        // writer
22773        synchronized (mPackages) {
22774            // If the platform SDK has changed since the last time we booted,
22775            // we need to re-grant app permission to catch any new ones that
22776            // appear. This is really a hack, and means that apps can in some
22777            // cases get permissions that the user didn't initially explicitly
22778            // allow... it would be nice to have some better way to handle
22779            // this situation.
22780            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22781                    : mSettings.getInternalVersion();
22782            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22783                    : StorageManager.UUID_PRIVATE_INTERNAL;
22784
22785            int updateFlags = UPDATE_PERMISSIONS_ALL;
22786            if (ver.sdkVersion != mSdkVersion) {
22787                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22788                        + mSdkVersion + "; regranting permissions for external");
22789                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22790            }
22791            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22792
22793            // Yay, everything is now upgraded
22794            ver.forceCurrent();
22795
22796            // can downgrade to reader
22797            // Persist settings
22798            mSettings.writeLPr();
22799        }
22800        // Send a broadcast to let everyone know we are done processing
22801        if (pkgList.size() > 0) {
22802            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22803        }
22804    }
22805
22806   /*
22807     * Utility method to unload a list of specified containers
22808     */
22809    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22810        // Just unmount all valid containers.
22811        for (AsecInstallArgs arg : cidArgs) {
22812            synchronized (mInstallLock) {
22813                arg.doPostDeleteLI(false);
22814           }
22815       }
22816   }
22817
22818    /*
22819     * Unload packages mounted on external media. This involves deleting package
22820     * data from internal structures, sending broadcasts about disabled packages,
22821     * gc'ing to free up references, unmounting all secure containers
22822     * corresponding to packages on external media, and posting a
22823     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22824     * that we always have to post this message if status has been requested no
22825     * matter what.
22826     */
22827    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22828            final boolean reportStatus) {
22829        if (DEBUG_SD_INSTALL)
22830            Log.i(TAG, "unloading media packages");
22831        ArrayList<String> pkgList = new ArrayList<String>();
22832        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22833        final Set<AsecInstallArgs> keys = processCids.keySet();
22834        for (AsecInstallArgs args : keys) {
22835            String pkgName = args.getPackageName();
22836            if (DEBUG_SD_INSTALL)
22837                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22838            // Delete package internally
22839            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22840            synchronized (mInstallLock) {
22841                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22842                final boolean res;
22843                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22844                        "unloadMediaPackages")) {
22845                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22846                            null);
22847                }
22848                if (res) {
22849                    pkgList.add(pkgName);
22850                } else {
22851                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22852                    failedList.add(args);
22853                }
22854            }
22855        }
22856
22857        // reader
22858        synchronized (mPackages) {
22859            // We didn't update the settings after removing each package;
22860            // write them now for all packages.
22861            mSettings.writeLPr();
22862        }
22863
22864        // We have to absolutely send UPDATED_MEDIA_STATUS only
22865        // after confirming that all the receivers processed the ordered
22866        // broadcast when packages get disabled, force a gc to clean things up.
22867        // and unload all the containers.
22868        if (pkgList.size() > 0) {
22869            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22870                    new IIntentReceiver.Stub() {
22871                public void performReceive(Intent intent, int resultCode, String data,
22872                        Bundle extras, boolean ordered, boolean sticky,
22873                        int sendingUser) throws RemoteException {
22874                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22875                            reportStatus ? 1 : 0, 1, keys);
22876                    mHandler.sendMessage(msg);
22877                }
22878            });
22879        } else {
22880            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22881                    keys);
22882            mHandler.sendMessage(msg);
22883        }
22884    }
22885
22886    private void loadPrivatePackages(final VolumeInfo vol) {
22887        mHandler.post(new Runnable() {
22888            @Override
22889            public void run() {
22890                loadPrivatePackagesInner(vol);
22891            }
22892        });
22893    }
22894
22895    private void loadPrivatePackagesInner(VolumeInfo vol) {
22896        final String volumeUuid = vol.fsUuid;
22897        if (TextUtils.isEmpty(volumeUuid)) {
22898            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22899            return;
22900        }
22901
22902        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22903        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22904        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22905
22906        final VersionInfo ver;
22907        final List<PackageSetting> packages;
22908        synchronized (mPackages) {
22909            ver = mSettings.findOrCreateVersion(volumeUuid);
22910            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22911        }
22912
22913        for (PackageSetting ps : packages) {
22914            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22915            synchronized (mInstallLock) {
22916                final PackageParser.Package pkg;
22917                try {
22918                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22919                    loaded.add(pkg.applicationInfo);
22920
22921                } catch (PackageManagerException e) {
22922                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22923                }
22924
22925                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22926                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22927                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22928                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22929                }
22930            }
22931        }
22932
22933        // Reconcile app data for all started/unlocked users
22934        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22935        final UserManager um = mContext.getSystemService(UserManager.class);
22936        UserManagerInternal umInternal = getUserManagerInternal();
22937        for (UserInfo user : um.getUsers()) {
22938            final int flags;
22939            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22940                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22941            } else if (umInternal.isUserRunning(user.id)) {
22942                flags = StorageManager.FLAG_STORAGE_DE;
22943            } else {
22944                continue;
22945            }
22946
22947            try {
22948                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22949                synchronized (mInstallLock) {
22950                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22951                }
22952            } catch (IllegalStateException e) {
22953                // Device was probably ejected, and we'll process that event momentarily
22954                Slog.w(TAG, "Failed to prepare storage: " + e);
22955            }
22956        }
22957
22958        synchronized (mPackages) {
22959            int updateFlags = UPDATE_PERMISSIONS_ALL;
22960            if (ver.sdkVersion != mSdkVersion) {
22961                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22962                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22963                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22964            }
22965            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22966
22967            // Yay, everything is now upgraded
22968            ver.forceCurrent();
22969
22970            mSettings.writeLPr();
22971        }
22972
22973        for (PackageFreezer freezer : freezers) {
22974            freezer.close();
22975        }
22976
22977        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22978        sendResourcesChangedBroadcast(true, false, loaded, null);
22979    }
22980
22981    private void unloadPrivatePackages(final VolumeInfo vol) {
22982        mHandler.post(new Runnable() {
22983            @Override
22984            public void run() {
22985                unloadPrivatePackagesInner(vol);
22986            }
22987        });
22988    }
22989
22990    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22991        final String volumeUuid = vol.fsUuid;
22992        if (TextUtils.isEmpty(volumeUuid)) {
22993            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22994            return;
22995        }
22996
22997        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22998        synchronized (mInstallLock) {
22999        synchronized (mPackages) {
23000            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23001            for (PackageSetting ps : packages) {
23002                if (ps.pkg == null) continue;
23003
23004                final ApplicationInfo info = ps.pkg.applicationInfo;
23005                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23006                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23007
23008                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23009                        "unloadPrivatePackagesInner")) {
23010                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23011                            false, null)) {
23012                        unloaded.add(info);
23013                    } else {
23014                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23015                    }
23016                }
23017
23018                // Try very hard to release any references to this package
23019                // so we don't risk the system server being killed due to
23020                // open FDs
23021                AttributeCache.instance().removePackage(ps.name);
23022            }
23023
23024            mSettings.writeLPr();
23025        }
23026        }
23027
23028        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23029        sendResourcesChangedBroadcast(false, false, unloaded, null);
23030
23031        // Try very hard to release any references to this path so we don't risk
23032        // the system server being killed due to open FDs
23033        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23034
23035        for (int i = 0; i < 3; i++) {
23036            System.gc();
23037            System.runFinalization();
23038        }
23039    }
23040
23041    private void assertPackageKnown(String volumeUuid, String packageName)
23042            throws PackageManagerException {
23043        synchronized (mPackages) {
23044            // Normalize package name to handle renamed packages
23045            packageName = normalizePackageNameLPr(packageName);
23046
23047            final PackageSetting ps = mSettings.mPackages.get(packageName);
23048            if (ps == null) {
23049                throw new PackageManagerException("Package " + packageName + " is unknown");
23050            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23051                throw new PackageManagerException(
23052                        "Package " + packageName + " found on unknown volume " + volumeUuid
23053                                + "; expected volume " + ps.volumeUuid);
23054            }
23055        }
23056    }
23057
23058    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23059            throws PackageManagerException {
23060        synchronized (mPackages) {
23061            // Normalize package name to handle renamed packages
23062            packageName = normalizePackageNameLPr(packageName);
23063
23064            final PackageSetting ps = mSettings.mPackages.get(packageName);
23065            if (ps == null) {
23066                throw new PackageManagerException("Package " + packageName + " is unknown");
23067            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23068                throw new PackageManagerException(
23069                        "Package " + packageName + " found on unknown volume " + volumeUuid
23070                                + "; expected volume " + ps.volumeUuid);
23071            } else if (!ps.getInstalled(userId)) {
23072                throw new PackageManagerException(
23073                        "Package " + packageName + " not installed for user " + userId);
23074            }
23075        }
23076    }
23077
23078    private List<String> collectAbsoluteCodePaths() {
23079        synchronized (mPackages) {
23080            List<String> codePaths = new ArrayList<>();
23081            final int packageCount = mSettings.mPackages.size();
23082            for (int i = 0; i < packageCount; i++) {
23083                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23084                codePaths.add(ps.codePath.getAbsolutePath());
23085            }
23086            return codePaths;
23087        }
23088    }
23089
23090    /**
23091     * Examine all apps present on given mounted volume, and destroy apps that
23092     * aren't expected, either due to uninstallation or reinstallation on
23093     * another volume.
23094     */
23095    private void reconcileApps(String volumeUuid) {
23096        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23097        List<File> filesToDelete = null;
23098
23099        final File[] files = FileUtils.listFilesOrEmpty(
23100                Environment.getDataAppDirectory(volumeUuid));
23101        for (File file : files) {
23102            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23103                    && !PackageInstallerService.isStageName(file.getName());
23104            if (!isPackage) {
23105                // Ignore entries which are not packages
23106                continue;
23107            }
23108
23109            String absolutePath = file.getAbsolutePath();
23110
23111            boolean pathValid = false;
23112            final int absoluteCodePathCount = absoluteCodePaths.size();
23113            for (int i = 0; i < absoluteCodePathCount; i++) {
23114                String absoluteCodePath = absoluteCodePaths.get(i);
23115                if (absolutePath.startsWith(absoluteCodePath)) {
23116                    pathValid = true;
23117                    break;
23118                }
23119            }
23120
23121            if (!pathValid) {
23122                if (filesToDelete == null) {
23123                    filesToDelete = new ArrayList<>();
23124                }
23125                filesToDelete.add(file);
23126            }
23127        }
23128
23129        if (filesToDelete != null) {
23130            final int fileToDeleteCount = filesToDelete.size();
23131            for (int i = 0; i < fileToDeleteCount; i++) {
23132                File fileToDelete = filesToDelete.get(i);
23133                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23134                synchronized (mInstallLock) {
23135                    removeCodePathLI(fileToDelete);
23136                }
23137            }
23138        }
23139    }
23140
23141    /**
23142     * Reconcile all app data for the given user.
23143     * <p>
23144     * Verifies that directories exist and that ownership and labeling is
23145     * correct for all installed apps on all mounted volumes.
23146     */
23147    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23148        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23149        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23150            final String volumeUuid = vol.getFsUuid();
23151            synchronized (mInstallLock) {
23152                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23153            }
23154        }
23155    }
23156
23157    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23158            boolean migrateAppData) {
23159        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23160    }
23161
23162    /**
23163     * Reconcile all app data on given mounted volume.
23164     * <p>
23165     * Destroys app data that isn't expected, either due to uninstallation or
23166     * reinstallation on another volume.
23167     * <p>
23168     * Verifies that directories exist and that ownership and labeling is
23169     * correct for all installed apps.
23170     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23171     */
23172    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23173            boolean migrateAppData, boolean onlyCoreApps) {
23174        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23175                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23176        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23177
23178        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23179        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23180
23181        // First look for stale data that doesn't belong, and check if things
23182        // have changed since we did our last restorecon
23183        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23184            if (StorageManager.isFileEncryptedNativeOrEmulated()
23185                    && !StorageManager.isUserKeyUnlocked(userId)) {
23186                throw new RuntimeException(
23187                        "Yikes, someone asked us to reconcile CE storage while " + userId
23188                                + " was still locked; this would have caused massive data loss!");
23189            }
23190
23191            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23192            for (File file : files) {
23193                final String packageName = file.getName();
23194                try {
23195                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23196                } catch (PackageManagerException e) {
23197                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23198                    try {
23199                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23200                                StorageManager.FLAG_STORAGE_CE, 0);
23201                    } catch (InstallerException e2) {
23202                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23203                    }
23204                }
23205            }
23206        }
23207        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23208            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23209            for (File file : files) {
23210                final String packageName = file.getName();
23211                try {
23212                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23213                } catch (PackageManagerException e) {
23214                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23215                    try {
23216                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23217                                StorageManager.FLAG_STORAGE_DE, 0);
23218                    } catch (InstallerException e2) {
23219                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23220                    }
23221                }
23222            }
23223        }
23224
23225        // Ensure that data directories are ready to roll for all packages
23226        // installed for this volume and user
23227        final List<PackageSetting> packages;
23228        synchronized (mPackages) {
23229            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23230        }
23231        int preparedCount = 0;
23232        for (PackageSetting ps : packages) {
23233            final String packageName = ps.name;
23234            if (ps.pkg == null) {
23235                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23236                // TODO: might be due to legacy ASEC apps; we should circle back
23237                // and reconcile again once they're scanned
23238                continue;
23239            }
23240            // Skip non-core apps if requested
23241            if (onlyCoreApps && !ps.pkg.coreApp) {
23242                result.add(packageName);
23243                continue;
23244            }
23245
23246            if (ps.getInstalled(userId)) {
23247                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23248                preparedCount++;
23249            }
23250        }
23251
23252        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23253        return result;
23254    }
23255
23256    /**
23257     * Prepare app data for the given app just after it was installed or
23258     * upgraded. This method carefully only touches users that it's installed
23259     * for, and it forces a restorecon to handle any seinfo changes.
23260     * <p>
23261     * Verifies that directories exist and that ownership and labeling is
23262     * correct for all installed apps. If there is an ownership mismatch, it
23263     * will try recovering system apps by wiping data; third-party app data is
23264     * left intact.
23265     * <p>
23266     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23267     */
23268    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23269        final PackageSetting ps;
23270        synchronized (mPackages) {
23271            ps = mSettings.mPackages.get(pkg.packageName);
23272            mSettings.writeKernelMappingLPr(ps);
23273        }
23274
23275        final UserManager um = mContext.getSystemService(UserManager.class);
23276        UserManagerInternal umInternal = getUserManagerInternal();
23277        for (UserInfo user : um.getUsers()) {
23278            final int flags;
23279            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23280                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23281            } else if (umInternal.isUserRunning(user.id)) {
23282                flags = StorageManager.FLAG_STORAGE_DE;
23283            } else {
23284                continue;
23285            }
23286
23287            if (ps.getInstalled(user.id)) {
23288                // TODO: when user data is locked, mark that we're still dirty
23289                prepareAppDataLIF(pkg, user.id, flags);
23290            }
23291        }
23292    }
23293
23294    /**
23295     * Prepare app data for the given app.
23296     * <p>
23297     * Verifies that directories exist and that ownership and labeling is
23298     * correct for all installed apps. If there is an ownership mismatch, this
23299     * will try recovering system apps by wiping data; third-party app data is
23300     * left intact.
23301     */
23302    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23303        if (pkg == null) {
23304            Slog.wtf(TAG, "Package was null!", new Throwable());
23305            return;
23306        }
23307        prepareAppDataLeafLIF(pkg, userId, flags);
23308        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23309        for (int i = 0; i < childCount; i++) {
23310            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23311        }
23312    }
23313
23314    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23315            boolean maybeMigrateAppData) {
23316        prepareAppDataLIF(pkg, userId, flags);
23317
23318        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23319            // We may have just shuffled around app data directories, so
23320            // prepare them one more time
23321            prepareAppDataLIF(pkg, userId, flags);
23322        }
23323    }
23324
23325    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23326        if (DEBUG_APP_DATA) {
23327            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23328                    + Integer.toHexString(flags));
23329        }
23330
23331        final String volumeUuid = pkg.volumeUuid;
23332        final String packageName = pkg.packageName;
23333        final ApplicationInfo app = pkg.applicationInfo;
23334        final int appId = UserHandle.getAppId(app.uid);
23335
23336        Preconditions.checkNotNull(app.seInfo);
23337
23338        long ceDataInode = -1;
23339        try {
23340            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23341                    appId, app.seInfo, app.targetSdkVersion);
23342        } catch (InstallerException e) {
23343            if (app.isSystemApp()) {
23344                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23345                        + ", but trying to recover: " + e);
23346                destroyAppDataLeafLIF(pkg, userId, flags);
23347                try {
23348                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23349                            appId, app.seInfo, app.targetSdkVersion);
23350                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23351                } catch (InstallerException e2) {
23352                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23353                }
23354            } else {
23355                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23356            }
23357        }
23358
23359        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23360            // TODO: mark this structure as dirty so we persist it!
23361            synchronized (mPackages) {
23362                final PackageSetting ps = mSettings.mPackages.get(packageName);
23363                if (ps != null) {
23364                    ps.setCeDataInode(ceDataInode, userId);
23365                }
23366            }
23367        }
23368
23369        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23370    }
23371
23372    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23373        if (pkg == null) {
23374            Slog.wtf(TAG, "Package was null!", new Throwable());
23375            return;
23376        }
23377        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23378        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23379        for (int i = 0; i < childCount; i++) {
23380            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23381        }
23382    }
23383
23384    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23385        final String volumeUuid = pkg.volumeUuid;
23386        final String packageName = pkg.packageName;
23387        final ApplicationInfo app = pkg.applicationInfo;
23388
23389        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23390            // Create a native library symlink only if we have native libraries
23391            // and if the native libraries are 32 bit libraries. We do not provide
23392            // this symlink for 64 bit libraries.
23393            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23394                final String nativeLibPath = app.nativeLibraryDir;
23395                try {
23396                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23397                            nativeLibPath, userId);
23398                } catch (InstallerException e) {
23399                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23400                }
23401            }
23402        }
23403    }
23404
23405    /**
23406     * For system apps on non-FBE devices, this method migrates any existing
23407     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23408     * requested by the app.
23409     */
23410    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23411        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23412                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23413            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23414                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23415            try {
23416                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23417                        storageTarget);
23418            } catch (InstallerException e) {
23419                logCriticalInfo(Log.WARN,
23420                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23421            }
23422            return true;
23423        } else {
23424            return false;
23425        }
23426    }
23427
23428    public PackageFreezer freezePackage(String packageName, String killReason) {
23429        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23430    }
23431
23432    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23433        return new PackageFreezer(packageName, userId, killReason);
23434    }
23435
23436    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23437            String killReason) {
23438        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23439    }
23440
23441    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23442            String killReason) {
23443        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23444            return new PackageFreezer();
23445        } else {
23446            return freezePackage(packageName, userId, killReason);
23447        }
23448    }
23449
23450    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23451            String killReason) {
23452        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23453    }
23454
23455    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23456            String killReason) {
23457        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23458            return new PackageFreezer();
23459        } else {
23460            return freezePackage(packageName, userId, killReason);
23461        }
23462    }
23463
23464    /**
23465     * Class that freezes and kills the given package upon creation, and
23466     * unfreezes it upon closing. This is typically used when doing surgery on
23467     * app code/data to prevent the app from running while you're working.
23468     */
23469    private class PackageFreezer implements AutoCloseable {
23470        private final String mPackageName;
23471        private final PackageFreezer[] mChildren;
23472
23473        private final boolean mWeFroze;
23474
23475        private final AtomicBoolean mClosed = new AtomicBoolean();
23476        private final CloseGuard mCloseGuard = CloseGuard.get();
23477
23478        /**
23479         * Create and return a stub freezer that doesn't actually do anything,
23480         * typically used when someone requested
23481         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23482         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23483         */
23484        public PackageFreezer() {
23485            mPackageName = null;
23486            mChildren = null;
23487            mWeFroze = false;
23488            mCloseGuard.open("close");
23489        }
23490
23491        public PackageFreezer(String packageName, int userId, String killReason) {
23492            synchronized (mPackages) {
23493                mPackageName = packageName;
23494                mWeFroze = mFrozenPackages.add(mPackageName);
23495
23496                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23497                if (ps != null) {
23498                    killApplication(ps.name, ps.appId, userId, killReason);
23499                }
23500
23501                final PackageParser.Package p = mPackages.get(packageName);
23502                if (p != null && p.childPackages != null) {
23503                    final int N = p.childPackages.size();
23504                    mChildren = new PackageFreezer[N];
23505                    for (int i = 0; i < N; i++) {
23506                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23507                                userId, killReason);
23508                    }
23509                } else {
23510                    mChildren = null;
23511                }
23512            }
23513            mCloseGuard.open("close");
23514        }
23515
23516        @Override
23517        protected void finalize() throws Throwable {
23518            try {
23519                mCloseGuard.warnIfOpen();
23520                close();
23521            } finally {
23522                super.finalize();
23523            }
23524        }
23525
23526        @Override
23527        public void close() {
23528            mCloseGuard.close();
23529            if (mClosed.compareAndSet(false, true)) {
23530                synchronized (mPackages) {
23531                    if (mWeFroze) {
23532                        mFrozenPackages.remove(mPackageName);
23533                    }
23534
23535                    if (mChildren != null) {
23536                        for (PackageFreezer freezer : mChildren) {
23537                            freezer.close();
23538                        }
23539                    }
23540                }
23541            }
23542        }
23543    }
23544
23545    /**
23546     * Verify that given package is currently frozen.
23547     */
23548    private void checkPackageFrozen(String packageName) {
23549        synchronized (mPackages) {
23550            if (!mFrozenPackages.contains(packageName)) {
23551                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23552            }
23553        }
23554    }
23555
23556    @Override
23557    public int movePackage(final String packageName, final String volumeUuid) {
23558        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23559
23560        final int callingUid = Binder.getCallingUid();
23561        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23562        final int moveId = mNextMoveId.getAndIncrement();
23563        mHandler.post(new Runnable() {
23564            @Override
23565            public void run() {
23566                try {
23567                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23568                } catch (PackageManagerException e) {
23569                    Slog.w(TAG, "Failed to move " + packageName, e);
23570                    mMoveCallbacks.notifyStatusChanged(moveId,
23571                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23572                }
23573            }
23574        });
23575        return moveId;
23576    }
23577
23578    private void movePackageInternal(final String packageName, final String volumeUuid,
23579            final int moveId, final int callingUid, UserHandle user)
23580                    throws PackageManagerException {
23581        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23582        final PackageManager pm = mContext.getPackageManager();
23583
23584        final boolean currentAsec;
23585        final String currentVolumeUuid;
23586        final File codeFile;
23587        final String installerPackageName;
23588        final String packageAbiOverride;
23589        final int appId;
23590        final String seinfo;
23591        final String label;
23592        final int targetSdkVersion;
23593        final PackageFreezer freezer;
23594        final int[] installedUserIds;
23595
23596        // reader
23597        synchronized (mPackages) {
23598            final PackageParser.Package pkg = mPackages.get(packageName);
23599            final PackageSetting ps = mSettings.mPackages.get(packageName);
23600            if (pkg == null
23601                    || ps == null
23602                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23603                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23604            }
23605            if (pkg.applicationInfo.isSystemApp()) {
23606                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23607                        "Cannot move system application");
23608            }
23609
23610            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23611            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23612                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23613            if (isInternalStorage && !allow3rdPartyOnInternal) {
23614                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23615                        "3rd party apps are not allowed on internal storage");
23616            }
23617
23618            if (pkg.applicationInfo.isExternalAsec()) {
23619                currentAsec = true;
23620                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23621            } else if (pkg.applicationInfo.isForwardLocked()) {
23622                currentAsec = true;
23623                currentVolumeUuid = "forward_locked";
23624            } else {
23625                currentAsec = false;
23626                currentVolumeUuid = ps.volumeUuid;
23627
23628                final File probe = new File(pkg.codePath);
23629                final File probeOat = new File(probe, "oat");
23630                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23631                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23632                            "Move only supported for modern cluster style installs");
23633                }
23634            }
23635
23636            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23637                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23638                        "Package already moved to " + volumeUuid);
23639            }
23640            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23641                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23642                        "Device admin cannot be moved");
23643            }
23644
23645            if (mFrozenPackages.contains(packageName)) {
23646                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23647                        "Failed to move already frozen package");
23648            }
23649
23650            codeFile = new File(pkg.codePath);
23651            installerPackageName = ps.installerPackageName;
23652            packageAbiOverride = ps.cpuAbiOverrideString;
23653            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23654            seinfo = pkg.applicationInfo.seInfo;
23655            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23656            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23657            freezer = freezePackage(packageName, "movePackageInternal");
23658            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23659        }
23660
23661        final Bundle extras = new Bundle();
23662        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23663        extras.putString(Intent.EXTRA_TITLE, label);
23664        mMoveCallbacks.notifyCreated(moveId, extras);
23665
23666        int installFlags;
23667        final boolean moveCompleteApp;
23668        final File measurePath;
23669
23670        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23671            installFlags = INSTALL_INTERNAL;
23672            moveCompleteApp = !currentAsec;
23673            measurePath = Environment.getDataAppDirectory(volumeUuid);
23674        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23675            installFlags = INSTALL_EXTERNAL;
23676            moveCompleteApp = false;
23677            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23678        } else {
23679            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23680            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23681                    || !volume.isMountedWritable()) {
23682                freezer.close();
23683                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23684                        "Move location not mounted private volume");
23685            }
23686
23687            Preconditions.checkState(!currentAsec);
23688
23689            installFlags = INSTALL_INTERNAL;
23690            moveCompleteApp = true;
23691            measurePath = Environment.getDataAppDirectory(volumeUuid);
23692        }
23693
23694        final PackageStats stats = new PackageStats(null, -1);
23695        synchronized (mInstaller) {
23696            for (int userId : installedUserIds) {
23697                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23698                    freezer.close();
23699                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23700                            "Failed to measure package size");
23701                }
23702            }
23703        }
23704
23705        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23706                + stats.dataSize);
23707
23708        final long startFreeBytes = measurePath.getUsableSpace();
23709        final long sizeBytes;
23710        if (moveCompleteApp) {
23711            sizeBytes = stats.codeSize + stats.dataSize;
23712        } else {
23713            sizeBytes = stats.codeSize;
23714        }
23715
23716        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23717            freezer.close();
23718            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23719                    "Not enough free space to move");
23720        }
23721
23722        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23723
23724        final CountDownLatch installedLatch = new CountDownLatch(1);
23725        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23726            @Override
23727            public void onUserActionRequired(Intent intent) throws RemoteException {
23728                throw new IllegalStateException();
23729            }
23730
23731            @Override
23732            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23733                    Bundle extras) throws RemoteException {
23734                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23735                        + PackageManager.installStatusToString(returnCode, msg));
23736
23737                installedLatch.countDown();
23738                freezer.close();
23739
23740                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23741                switch (status) {
23742                    case PackageInstaller.STATUS_SUCCESS:
23743                        mMoveCallbacks.notifyStatusChanged(moveId,
23744                                PackageManager.MOVE_SUCCEEDED);
23745                        break;
23746                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23747                        mMoveCallbacks.notifyStatusChanged(moveId,
23748                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23749                        break;
23750                    default:
23751                        mMoveCallbacks.notifyStatusChanged(moveId,
23752                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23753                        break;
23754                }
23755            }
23756        };
23757
23758        final MoveInfo move;
23759        if (moveCompleteApp) {
23760            // Kick off a thread to report progress estimates
23761            new Thread() {
23762                @Override
23763                public void run() {
23764                    while (true) {
23765                        try {
23766                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23767                                break;
23768                            }
23769                        } catch (InterruptedException ignored) {
23770                        }
23771
23772                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23773                        final int progress = 10 + (int) MathUtils.constrain(
23774                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23775                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23776                    }
23777                }
23778            }.start();
23779
23780            final String dataAppName = codeFile.getName();
23781            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23782                    dataAppName, appId, seinfo, targetSdkVersion);
23783        } else {
23784            move = null;
23785        }
23786
23787        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23788
23789        final Message msg = mHandler.obtainMessage(INIT_COPY);
23790        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23791        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23792                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23793                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23794                PackageManager.INSTALL_REASON_UNKNOWN);
23795        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23796        msg.obj = params;
23797
23798        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23799                System.identityHashCode(msg.obj));
23800        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23801                System.identityHashCode(msg.obj));
23802
23803        mHandler.sendMessage(msg);
23804    }
23805
23806    @Override
23807    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23808        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23809
23810        final int realMoveId = mNextMoveId.getAndIncrement();
23811        final Bundle extras = new Bundle();
23812        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23813        mMoveCallbacks.notifyCreated(realMoveId, extras);
23814
23815        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23816            @Override
23817            public void onCreated(int moveId, Bundle extras) {
23818                // Ignored
23819            }
23820
23821            @Override
23822            public void onStatusChanged(int moveId, int status, long estMillis) {
23823                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23824            }
23825        };
23826
23827        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23828        storage.setPrimaryStorageUuid(volumeUuid, callback);
23829        return realMoveId;
23830    }
23831
23832    @Override
23833    public int getMoveStatus(int moveId) {
23834        mContext.enforceCallingOrSelfPermission(
23835                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23836        return mMoveCallbacks.mLastStatus.get(moveId);
23837    }
23838
23839    @Override
23840    public void registerMoveCallback(IPackageMoveObserver callback) {
23841        mContext.enforceCallingOrSelfPermission(
23842                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23843        mMoveCallbacks.register(callback);
23844    }
23845
23846    @Override
23847    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23848        mContext.enforceCallingOrSelfPermission(
23849                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23850        mMoveCallbacks.unregister(callback);
23851    }
23852
23853    @Override
23854    public boolean setInstallLocation(int loc) {
23855        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23856                null);
23857        if (getInstallLocation() == loc) {
23858            return true;
23859        }
23860        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23861                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23862            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23863                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23864            return true;
23865        }
23866        return false;
23867   }
23868
23869    @Override
23870    public int getInstallLocation() {
23871        // allow instant app access
23872        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23873                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23874                PackageHelper.APP_INSTALL_AUTO);
23875    }
23876
23877    /** Called by UserManagerService */
23878    void cleanUpUser(UserManagerService userManager, int userHandle) {
23879        synchronized (mPackages) {
23880            mDirtyUsers.remove(userHandle);
23881            mUserNeedsBadging.delete(userHandle);
23882            mSettings.removeUserLPw(userHandle);
23883            mPendingBroadcasts.remove(userHandle);
23884            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23885            removeUnusedPackagesLPw(userManager, userHandle);
23886        }
23887    }
23888
23889    /**
23890     * We're removing userHandle and would like to remove any downloaded packages
23891     * that are no longer in use by any other user.
23892     * @param userHandle the user being removed
23893     */
23894    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23895        final boolean DEBUG_CLEAN_APKS = false;
23896        int [] users = userManager.getUserIds();
23897        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23898        while (psit.hasNext()) {
23899            PackageSetting ps = psit.next();
23900            if (ps.pkg == null) {
23901                continue;
23902            }
23903            final String packageName = ps.pkg.packageName;
23904            // Skip over if system app
23905            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23906                continue;
23907            }
23908            if (DEBUG_CLEAN_APKS) {
23909                Slog.i(TAG, "Checking package " + packageName);
23910            }
23911            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23912            if (keep) {
23913                if (DEBUG_CLEAN_APKS) {
23914                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23915                }
23916            } else {
23917                for (int i = 0; i < users.length; i++) {
23918                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23919                        keep = true;
23920                        if (DEBUG_CLEAN_APKS) {
23921                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23922                                    + users[i]);
23923                        }
23924                        break;
23925                    }
23926                }
23927            }
23928            if (!keep) {
23929                if (DEBUG_CLEAN_APKS) {
23930                    Slog.i(TAG, "  Removing package " + packageName);
23931                }
23932                mHandler.post(new Runnable() {
23933                    public void run() {
23934                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23935                                userHandle, 0);
23936                    } //end run
23937                });
23938            }
23939        }
23940    }
23941
23942    /** Called by UserManagerService */
23943    void createNewUser(int userId, String[] disallowedPackages) {
23944        synchronized (mInstallLock) {
23945            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23946        }
23947        synchronized (mPackages) {
23948            scheduleWritePackageRestrictionsLocked(userId);
23949            scheduleWritePackageListLocked(userId);
23950            applyFactoryDefaultBrowserLPw(userId);
23951            primeDomainVerificationsLPw(userId);
23952        }
23953    }
23954
23955    void onNewUserCreated(final int userId) {
23956        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23957        // If permission review for legacy apps is required, we represent
23958        // dagerous permissions for such apps as always granted runtime
23959        // permissions to keep per user flag state whether review is needed.
23960        // Hence, if a new user is added we have to propagate dangerous
23961        // permission grants for these legacy apps.
23962        if (mPermissionReviewRequired) {
23963            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23964                    | UPDATE_PERMISSIONS_REPLACE_ALL);
23965        }
23966    }
23967
23968    @Override
23969    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23970        mContext.enforceCallingOrSelfPermission(
23971                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23972                "Only package verification agents can read the verifier device identity");
23973
23974        synchronized (mPackages) {
23975            return mSettings.getVerifierDeviceIdentityLPw();
23976        }
23977    }
23978
23979    @Override
23980    public void setPermissionEnforced(String permission, boolean enforced) {
23981        // TODO: Now that we no longer change GID for storage, this should to away.
23982        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23983                "setPermissionEnforced");
23984        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23985            synchronized (mPackages) {
23986                if (mSettings.mReadExternalStorageEnforced == null
23987                        || mSettings.mReadExternalStorageEnforced != enforced) {
23988                    mSettings.mReadExternalStorageEnforced = enforced;
23989                    mSettings.writeLPr();
23990                }
23991            }
23992            // kill any non-foreground processes so we restart them and
23993            // grant/revoke the GID.
23994            final IActivityManager am = ActivityManager.getService();
23995            if (am != null) {
23996                final long token = Binder.clearCallingIdentity();
23997                try {
23998                    am.killProcessesBelowForeground("setPermissionEnforcement");
23999                } catch (RemoteException e) {
24000                } finally {
24001                    Binder.restoreCallingIdentity(token);
24002                }
24003            }
24004        } else {
24005            throw new IllegalArgumentException("No selective enforcement for " + permission);
24006        }
24007    }
24008
24009    @Override
24010    @Deprecated
24011    public boolean isPermissionEnforced(String permission) {
24012        // allow instant applications
24013        return true;
24014    }
24015
24016    @Override
24017    public boolean isStorageLow() {
24018        // allow instant applications
24019        final long token = Binder.clearCallingIdentity();
24020        try {
24021            final DeviceStorageMonitorInternal
24022                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24023            if (dsm != null) {
24024                return dsm.isMemoryLow();
24025            } else {
24026                return false;
24027            }
24028        } finally {
24029            Binder.restoreCallingIdentity(token);
24030        }
24031    }
24032
24033    @Override
24034    public IPackageInstaller getPackageInstaller() {
24035        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24036            return null;
24037        }
24038        return mInstallerService;
24039    }
24040
24041    private boolean userNeedsBadging(int userId) {
24042        int index = mUserNeedsBadging.indexOfKey(userId);
24043        if (index < 0) {
24044            final UserInfo userInfo;
24045            final long token = Binder.clearCallingIdentity();
24046            try {
24047                userInfo = sUserManager.getUserInfo(userId);
24048            } finally {
24049                Binder.restoreCallingIdentity(token);
24050            }
24051            final boolean b;
24052            if (userInfo != null && userInfo.isManagedProfile()) {
24053                b = true;
24054            } else {
24055                b = false;
24056            }
24057            mUserNeedsBadging.put(userId, b);
24058            return b;
24059        }
24060        return mUserNeedsBadging.valueAt(index);
24061    }
24062
24063    @Override
24064    public KeySet getKeySetByAlias(String packageName, String alias) {
24065        if (packageName == null || alias == null) {
24066            return null;
24067        }
24068        synchronized(mPackages) {
24069            final PackageParser.Package pkg = mPackages.get(packageName);
24070            if (pkg == null) {
24071                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24072                throw new IllegalArgumentException("Unknown package: " + packageName);
24073            }
24074            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24075            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24076                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24077                throw new IllegalArgumentException("Unknown package: " + packageName);
24078            }
24079            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24080            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24081        }
24082    }
24083
24084    @Override
24085    public KeySet getSigningKeySet(String packageName) {
24086        if (packageName == null) {
24087            return null;
24088        }
24089        synchronized(mPackages) {
24090            final int callingUid = Binder.getCallingUid();
24091            final int callingUserId = UserHandle.getUserId(callingUid);
24092            final PackageParser.Package pkg = mPackages.get(packageName);
24093            if (pkg == null) {
24094                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24095                throw new IllegalArgumentException("Unknown package: " + packageName);
24096            }
24097            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24098            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24099                // filter and pretend the package doesn't exist
24100                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24101                        + ", uid:" + callingUid);
24102                throw new IllegalArgumentException("Unknown package: " + packageName);
24103            }
24104            if (pkg.applicationInfo.uid != callingUid
24105                    && Process.SYSTEM_UID != callingUid) {
24106                throw new SecurityException("May not access signing KeySet of other apps.");
24107            }
24108            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24109            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24110        }
24111    }
24112
24113    @Override
24114    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24115        final int callingUid = Binder.getCallingUid();
24116        if (getInstantAppPackageName(callingUid) != null) {
24117            return false;
24118        }
24119        if (packageName == null || ks == null) {
24120            return false;
24121        }
24122        synchronized(mPackages) {
24123            final PackageParser.Package pkg = mPackages.get(packageName);
24124            if (pkg == null
24125                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24126                            UserHandle.getUserId(callingUid))) {
24127                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24128                throw new IllegalArgumentException("Unknown package: " + packageName);
24129            }
24130            IBinder ksh = ks.getToken();
24131            if (ksh instanceof KeySetHandle) {
24132                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24133                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24134            }
24135            return false;
24136        }
24137    }
24138
24139    @Override
24140    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24141        final int callingUid = Binder.getCallingUid();
24142        if (getInstantAppPackageName(callingUid) != null) {
24143            return false;
24144        }
24145        if (packageName == null || ks == null) {
24146            return false;
24147        }
24148        synchronized(mPackages) {
24149            final PackageParser.Package pkg = mPackages.get(packageName);
24150            if (pkg == null
24151                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24152                            UserHandle.getUserId(callingUid))) {
24153                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24154                throw new IllegalArgumentException("Unknown package: " + packageName);
24155            }
24156            IBinder ksh = ks.getToken();
24157            if (ksh instanceof KeySetHandle) {
24158                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24159                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24160            }
24161            return false;
24162        }
24163    }
24164
24165    private void deletePackageIfUnusedLPr(final String packageName) {
24166        PackageSetting ps = mSettings.mPackages.get(packageName);
24167        if (ps == null) {
24168            return;
24169        }
24170        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24171            // TODO Implement atomic delete if package is unused
24172            // It is currently possible that the package will be deleted even if it is installed
24173            // after this method returns.
24174            mHandler.post(new Runnable() {
24175                public void run() {
24176                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24177                            0, PackageManager.DELETE_ALL_USERS);
24178                }
24179            });
24180        }
24181    }
24182
24183    /**
24184     * Check and throw if the given before/after packages would be considered a
24185     * downgrade.
24186     */
24187    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24188            throws PackageManagerException {
24189        if (after.versionCode < before.mVersionCode) {
24190            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24191                    "Update version code " + after.versionCode + " is older than current "
24192                    + before.mVersionCode);
24193        } else if (after.versionCode == before.mVersionCode) {
24194            if (after.baseRevisionCode < before.baseRevisionCode) {
24195                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24196                        "Update base revision code " + after.baseRevisionCode
24197                        + " is older than current " + before.baseRevisionCode);
24198            }
24199
24200            if (!ArrayUtils.isEmpty(after.splitNames)) {
24201                for (int i = 0; i < after.splitNames.length; i++) {
24202                    final String splitName = after.splitNames[i];
24203                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24204                    if (j != -1) {
24205                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24206                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24207                                    "Update split " + splitName + " revision code "
24208                                    + after.splitRevisionCodes[i] + " is older than current "
24209                                    + before.splitRevisionCodes[j]);
24210                        }
24211                    }
24212                }
24213            }
24214        }
24215    }
24216
24217    private static class MoveCallbacks extends Handler {
24218        private static final int MSG_CREATED = 1;
24219        private static final int MSG_STATUS_CHANGED = 2;
24220
24221        private final RemoteCallbackList<IPackageMoveObserver>
24222                mCallbacks = new RemoteCallbackList<>();
24223
24224        private final SparseIntArray mLastStatus = new SparseIntArray();
24225
24226        public MoveCallbacks(Looper looper) {
24227            super(looper);
24228        }
24229
24230        public void register(IPackageMoveObserver callback) {
24231            mCallbacks.register(callback);
24232        }
24233
24234        public void unregister(IPackageMoveObserver callback) {
24235            mCallbacks.unregister(callback);
24236        }
24237
24238        @Override
24239        public void handleMessage(Message msg) {
24240            final SomeArgs args = (SomeArgs) msg.obj;
24241            final int n = mCallbacks.beginBroadcast();
24242            for (int i = 0; i < n; i++) {
24243                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24244                try {
24245                    invokeCallback(callback, msg.what, args);
24246                } catch (RemoteException ignored) {
24247                }
24248            }
24249            mCallbacks.finishBroadcast();
24250            args.recycle();
24251        }
24252
24253        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24254                throws RemoteException {
24255            switch (what) {
24256                case MSG_CREATED: {
24257                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24258                    break;
24259                }
24260                case MSG_STATUS_CHANGED: {
24261                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24262                    break;
24263                }
24264            }
24265        }
24266
24267        private void notifyCreated(int moveId, Bundle extras) {
24268            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24269
24270            final SomeArgs args = SomeArgs.obtain();
24271            args.argi1 = moveId;
24272            args.arg2 = extras;
24273            obtainMessage(MSG_CREATED, args).sendToTarget();
24274        }
24275
24276        private void notifyStatusChanged(int moveId, int status) {
24277            notifyStatusChanged(moveId, status, -1);
24278        }
24279
24280        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24281            Slog.v(TAG, "Move " + moveId + " status " + status);
24282
24283            final SomeArgs args = SomeArgs.obtain();
24284            args.argi1 = moveId;
24285            args.argi2 = status;
24286            args.arg3 = estMillis;
24287            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24288
24289            synchronized (mLastStatus) {
24290                mLastStatus.put(moveId, status);
24291            }
24292        }
24293    }
24294
24295    private final static class OnPermissionChangeListeners extends Handler {
24296        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24297
24298        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24299                new RemoteCallbackList<>();
24300
24301        public OnPermissionChangeListeners(Looper looper) {
24302            super(looper);
24303        }
24304
24305        @Override
24306        public void handleMessage(Message msg) {
24307            switch (msg.what) {
24308                case MSG_ON_PERMISSIONS_CHANGED: {
24309                    final int uid = msg.arg1;
24310                    handleOnPermissionsChanged(uid);
24311                } break;
24312            }
24313        }
24314
24315        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24316            mPermissionListeners.register(listener);
24317
24318        }
24319
24320        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24321            mPermissionListeners.unregister(listener);
24322        }
24323
24324        public void onPermissionsChanged(int uid) {
24325            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24326                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24327            }
24328        }
24329
24330        private void handleOnPermissionsChanged(int uid) {
24331            final int count = mPermissionListeners.beginBroadcast();
24332            try {
24333                for (int i = 0; i < count; i++) {
24334                    IOnPermissionsChangeListener callback = mPermissionListeners
24335                            .getBroadcastItem(i);
24336                    try {
24337                        callback.onPermissionsChanged(uid);
24338                    } catch (RemoteException e) {
24339                        Log.e(TAG, "Permission listener is dead", e);
24340                    }
24341                }
24342            } finally {
24343                mPermissionListeners.finishBroadcast();
24344            }
24345        }
24346    }
24347
24348    private class PackageManagerInternalImpl extends PackageManagerInternal {
24349        @Override
24350        public void setLocationPackagesProvider(PackagesProvider provider) {
24351            synchronized (mPackages) {
24352                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24353            }
24354        }
24355
24356        @Override
24357        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24358            synchronized (mPackages) {
24359                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24360            }
24361        }
24362
24363        @Override
24364        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24365            synchronized (mPackages) {
24366                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24367            }
24368        }
24369
24370        @Override
24371        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24372            synchronized (mPackages) {
24373                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24374            }
24375        }
24376
24377        @Override
24378        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24379            synchronized (mPackages) {
24380                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24381            }
24382        }
24383
24384        @Override
24385        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24386            synchronized (mPackages) {
24387                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24388            }
24389        }
24390
24391        @Override
24392        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24393            synchronized (mPackages) {
24394                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24395                        packageName, userId);
24396            }
24397        }
24398
24399        @Override
24400        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24401            synchronized (mPackages) {
24402                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24403                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24404                        packageName, userId);
24405            }
24406        }
24407
24408        @Override
24409        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24410            synchronized (mPackages) {
24411                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24412                        packageName, userId);
24413            }
24414        }
24415
24416        @Override
24417        public void setKeepUninstalledPackages(final List<String> packageList) {
24418            Preconditions.checkNotNull(packageList);
24419            List<String> removedFromList = null;
24420            synchronized (mPackages) {
24421                if (mKeepUninstalledPackages != null) {
24422                    final int packagesCount = mKeepUninstalledPackages.size();
24423                    for (int i = 0; i < packagesCount; i++) {
24424                        String oldPackage = mKeepUninstalledPackages.get(i);
24425                        if (packageList != null && packageList.contains(oldPackage)) {
24426                            continue;
24427                        }
24428                        if (removedFromList == null) {
24429                            removedFromList = new ArrayList<>();
24430                        }
24431                        removedFromList.add(oldPackage);
24432                    }
24433                }
24434                mKeepUninstalledPackages = new ArrayList<>(packageList);
24435                if (removedFromList != null) {
24436                    final int removedCount = removedFromList.size();
24437                    for (int i = 0; i < removedCount; i++) {
24438                        deletePackageIfUnusedLPr(removedFromList.get(i));
24439                    }
24440                }
24441            }
24442        }
24443
24444        @Override
24445        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24446            synchronized (mPackages) {
24447                // If we do not support permission review, done.
24448                if (!mPermissionReviewRequired) {
24449                    return false;
24450                }
24451
24452                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24453                if (packageSetting == null) {
24454                    return false;
24455                }
24456
24457                // Permission review applies only to apps not supporting the new permission model.
24458                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24459                    return false;
24460                }
24461
24462                // Legacy apps have the permission and get user consent on launch.
24463                PermissionsState permissionsState = packageSetting.getPermissionsState();
24464                return permissionsState.isPermissionReviewRequired(userId);
24465            }
24466        }
24467
24468        @Override
24469        public PackageInfo getPackageInfo(
24470                String packageName, int flags, int filterCallingUid, int userId) {
24471            return PackageManagerService.this
24472                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24473                            flags, filterCallingUid, userId);
24474        }
24475
24476        @Override
24477        public ApplicationInfo getApplicationInfo(
24478                String packageName, int flags, int filterCallingUid, int userId) {
24479            return PackageManagerService.this
24480                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24481        }
24482
24483        @Override
24484        public ActivityInfo getActivityInfo(
24485                ComponentName component, int flags, int filterCallingUid, int userId) {
24486            return PackageManagerService.this
24487                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24488        }
24489
24490        @Override
24491        public List<ResolveInfo> queryIntentActivities(
24492                Intent intent, int flags, int filterCallingUid, int userId) {
24493            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24494            return PackageManagerService.this
24495                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24496                            userId, false /*resolveForStart*/);
24497        }
24498
24499        @Override
24500        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24501                int userId) {
24502            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24503        }
24504
24505        @Override
24506        public void setDeviceAndProfileOwnerPackages(
24507                int deviceOwnerUserId, String deviceOwnerPackage,
24508                SparseArray<String> profileOwnerPackages) {
24509            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24510                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24511        }
24512
24513        @Override
24514        public boolean isPackageDataProtected(int userId, String packageName) {
24515            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24516        }
24517
24518        @Override
24519        public boolean isPackageEphemeral(int userId, String packageName) {
24520            synchronized (mPackages) {
24521                final PackageSetting ps = mSettings.mPackages.get(packageName);
24522                return ps != null ? ps.getInstantApp(userId) : false;
24523            }
24524        }
24525
24526        @Override
24527        public boolean wasPackageEverLaunched(String packageName, int userId) {
24528            synchronized (mPackages) {
24529                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24530            }
24531        }
24532
24533        @Override
24534        public void grantRuntimePermission(String packageName, String name, int userId,
24535                boolean overridePolicy) {
24536            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24537                    overridePolicy);
24538        }
24539
24540        @Override
24541        public void revokeRuntimePermission(String packageName, String name, int userId,
24542                boolean overridePolicy) {
24543            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24544                    overridePolicy);
24545        }
24546
24547        @Override
24548        public String getNameForUid(int uid) {
24549            return PackageManagerService.this.getNameForUid(uid);
24550        }
24551
24552        @Override
24553        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24554                Intent origIntent, String resolvedType, String callingPackage,
24555                Bundle verificationBundle, int userId) {
24556            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24557                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24558                    userId);
24559        }
24560
24561        @Override
24562        public void grantEphemeralAccess(int userId, Intent intent,
24563                int targetAppId, int ephemeralAppId) {
24564            synchronized (mPackages) {
24565                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24566                        targetAppId, ephemeralAppId);
24567            }
24568        }
24569
24570        @Override
24571        public boolean isInstantAppInstallerComponent(ComponentName component) {
24572            synchronized (mPackages) {
24573                return mInstantAppInstallerActivity != null
24574                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24575            }
24576        }
24577
24578        @Override
24579        public void pruneInstantApps() {
24580            mInstantAppRegistry.pruneInstantApps();
24581        }
24582
24583        @Override
24584        public String getSetupWizardPackageName() {
24585            return mSetupWizardPackage;
24586        }
24587
24588        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24589            if (policy != null) {
24590                mExternalSourcesPolicy = policy;
24591            }
24592        }
24593
24594        @Override
24595        public boolean isPackagePersistent(String packageName) {
24596            synchronized (mPackages) {
24597                PackageParser.Package pkg = mPackages.get(packageName);
24598                return pkg != null
24599                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24600                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24601                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24602                        : false;
24603            }
24604        }
24605
24606        @Override
24607        public List<PackageInfo> getOverlayPackages(int userId) {
24608            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24609            synchronized (mPackages) {
24610                for (PackageParser.Package p : mPackages.values()) {
24611                    if (p.mOverlayTarget != null) {
24612                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24613                        if (pkg != null) {
24614                            overlayPackages.add(pkg);
24615                        }
24616                    }
24617                }
24618            }
24619            return overlayPackages;
24620        }
24621
24622        @Override
24623        public List<String> getTargetPackageNames(int userId) {
24624            List<String> targetPackages = new ArrayList<>();
24625            synchronized (mPackages) {
24626                for (PackageParser.Package p : mPackages.values()) {
24627                    if (p.mOverlayTarget == null) {
24628                        targetPackages.add(p.packageName);
24629                    }
24630                }
24631            }
24632            return targetPackages;
24633        }
24634
24635        @Override
24636        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24637                @Nullable List<String> overlayPackageNames) {
24638            synchronized (mPackages) {
24639                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24640                    Slog.e(TAG, "failed to find package " + targetPackageName);
24641                    return false;
24642                }
24643                ArrayList<String> overlayPaths = null;
24644                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24645                    final int N = overlayPackageNames.size();
24646                    overlayPaths = new ArrayList<>(N);
24647                    for (int i = 0; i < N; i++) {
24648                        final String packageName = overlayPackageNames.get(i);
24649                        final PackageParser.Package pkg = mPackages.get(packageName);
24650                        if (pkg == null) {
24651                            Slog.e(TAG, "failed to find package " + packageName);
24652                            return false;
24653                        }
24654                        overlayPaths.add(pkg.baseCodePath);
24655                    }
24656                }
24657
24658                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24659                ps.setOverlayPaths(overlayPaths, userId);
24660                return true;
24661            }
24662        }
24663
24664        @Override
24665        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24666                int flags, int userId) {
24667            return resolveIntentInternal(
24668                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24669        }
24670
24671        @Override
24672        public ResolveInfo resolveService(Intent intent, String resolvedType,
24673                int flags, int userId, int callingUid) {
24674            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24675        }
24676
24677        @Override
24678        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24679            synchronized (mPackages) {
24680                mIsolatedOwners.put(isolatedUid, ownerUid);
24681            }
24682        }
24683
24684        @Override
24685        public void removeIsolatedUid(int isolatedUid) {
24686            synchronized (mPackages) {
24687                mIsolatedOwners.delete(isolatedUid);
24688            }
24689        }
24690
24691        @Override
24692        public int getUidTargetSdkVersion(int uid) {
24693            synchronized (mPackages) {
24694                return getUidTargetSdkVersionLockedLPr(uid);
24695            }
24696        }
24697
24698        @Override
24699        public boolean canAccessInstantApps(int callingUid, int userId) {
24700            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24701        }
24702    }
24703
24704    @Override
24705    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24706        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24707        synchronized (mPackages) {
24708            final long identity = Binder.clearCallingIdentity();
24709            try {
24710                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24711                        packageNames, userId);
24712            } finally {
24713                Binder.restoreCallingIdentity(identity);
24714            }
24715        }
24716    }
24717
24718    @Override
24719    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24720        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24721        synchronized (mPackages) {
24722            final long identity = Binder.clearCallingIdentity();
24723            try {
24724                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24725                        packageNames, userId);
24726            } finally {
24727                Binder.restoreCallingIdentity(identity);
24728            }
24729        }
24730    }
24731
24732    private static void enforceSystemOrPhoneCaller(String tag) {
24733        int callingUid = Binder.getCallingUid();
24734        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24735            throw new SecurityException(
24736                    "Cannot call " + tag + " from UID " + callingUid);
24737        }
24738    }
24739
24740    boolean isHistoricalPackageUsageAvailable() {
24741        return mPackageUsage.isHistoricalPackageUsageAvailable();
24742    }
24743
24744    /**
24745     * Return a <b>copy</b> of the collection of packages known to the package manager.
24746     * @return A copy of the values of mPackages.
24747     */
24748    Collection<PackageParser.Package> getPackages() {
24749        synchronized (mPackages) {
24750            return new ArrayList<>(mPackages.values());
24751        }
24752    }
24753
24754    /**
24755     * Logs process start information (including base APK hash) to the security log.
24756     * @hide
24757     */
24758    @Override
24759    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24760            String apkFile, int pid) {
24761        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24762            return;
24763        }
24764        if (!SecurityLog.isLoggingEnabled()) {
24765            return;
24766        }
24767        Bundle data = new Bundle();
24768        data.putLong("startTimestamp", System.currentTimeMillis());
24769        data.putString("processName", processName);
24770        data.putInt("uid", uid);
24771        data.putString("seinfo", seinfo);
24772        data.putString("apkFile", apkFile);
24773        data.putInt("pid", pid);
24774        Message msg = mProcessLoggingHandler.obtainMessage(
24775                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24776        msg.setData(data);
24777        mProcessLoggingHandler.sendMessage(msg);
24778    }
24779
24780    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24781        return mCompilerStats.getPackageStats(pkgName);
24782    }
24783
24784    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24785        return getOrCreateCompilerPackageStats(pkg.packageName);
24786    }
24787
24788    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24789        return mCompilerStats.getOrCreatePackageStats(pkgName);
24790    }
24791
24792    public void deleteCompilerPackageStats(String pkgName) {
24793        mCompilerStats.deletePackageStats(pkgName);
24794    }
24795
24796    @Override
24797    public int getInstallReason(String packageName, int userId) {
24798        final int callingUid = Binder.getCallingUid();
24799        enforceCrossUserPermission(callingUid, userId,
24800                true /* requireFullPermission */, false /* checkShell */,
24801                "get install reason");
24802        synchronized (mPackages) {
24803            final PackageSetting ps = mSettings.mPackages.get(packageName);
24804            if (filterAppAccessLPr(ps, callingUid, userId)) {
24805                return PackageManager.INSTALL_REASON_UNKNOWN;
24806            }
24807            if (ps != null) {
24808                return ps.getInstallReason(userId);
24809            }
24810        }
24811        return PackageManager.INSTALL_REASON_UNKNOWN;
24812    }
24813
24814    @Override
24815    public boolean canRequestPackageInstalls(String packageName, int userId) {
24816        return canRequestPackageInstallsInternal(packageName, 0, userId,
24817                true /* throwIfPermNotDeclared*/);
24818    }
24819
24820    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24821            boolean throwIfPermNotDeclared) {
24822        int callingUid = Binder.getCallingUid();
24823        int uid = getPackageUid(packageName, 0, userId);
24824        if (callingUid != uid && callingUid != Process.ROOT_UID
24825                && callingUid != Process.SYSTEM_UID) {
24826            throw new SecurityException(
24827                    "Caller uid " + callingUid + " does not own package " + packageName);
24828        }
24829        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24830        if (info == null) {
24831            return false;
24832        }
24833        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24834            return false;
24835        }
24836        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24837        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24838        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24839            if (throwIfPermNotDeclared) {
24840                throw new SecurityException("Need to declare " + appOpPermission
24841                        + " to call this api");
24842            } else {
24843                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24844                return false;
24845            }
24846        }
24847        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24848            return false;
24849        }
24850        if (mExternalSourcesPolicy != null) {
24851            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24852            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24853                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24854            }
24855        }
24856        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24857    }
24858
24859    @Override
24860    public ComponentName getInstantAppResolverSettingsComponent() {
24861        return mInstantAppResolverSettingsComponent;
24862    }
24863
24864    @Override
24865    public ComponentName getInstantAppInstallerComponent() {
24866        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24867            return null;
24868        }
24869        return mInstantAppInstallerActivity == null
24870                ? null : mInstantAppInstallerActivity.getComponentName();
24871    }
24872
24873    @Override
24874    public String getInstantAppAndroidId(String packageName, int userId) {
24875        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24876                "getInstantAppAndroidId");
24877        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24878                true /* requireFullPermission */, false /* checkShell */,
24879                "getInstantAppAndroidId");
24880        // Make sure the target is an Instant App.
24881        if (!isInstantApp(packageName, userId)) {
24882            return null;
24883        }
24884        synchronized (mPackages) {
24885            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24886        }
24887    }
24888
24889    boolean canHaveOatDir(String packageName) {
24890        synchronized (mPackages) {
24891            PackageParser.Package p = mPackages.get(packageName);
24892            if (p == null) {
24893                return false;
24894            }
24895            return p.canHaveOatDir();
24896        }
24897    }
24898
24899    private String getOatDir(PackageParser.Package pkg) {
24900        if (!pkg.canHaveOatDir()) {
24901            return null;
24902        }
24903        File codePath = new File(pkg.codePath);
24904        if (codePath.isDirectory()) {
24905            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24906        }
24907        return null;
24908    }
24909
24910    void deleteOatArtifactsOfPackage(String packageName) {
24911        final String[] instructionSets;
24912        final List<String> codePaths;
24913        final String oatDir;
24914        final PackageParser.Package pkg;
24915        synchronized (mPackages) {
24916            pkg = mPackages.get(packageName);
24917        }
24918        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24919        codePaths = pkg.getAllCodePaths();
24920        oatDir = getOatDir(pkg);
24921
24922        for (String codePath : codePaths) {
24923            for (String isa : instructionSets) {
24924                try {
24925                    mInstaller.deleteOdex(codePath, isa, oatDir);
24926                } catch (InstallerException e) {
24927                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24928                }
24929            }
24930        }
24931    }
24932}
24933
24934interface PackageSender {
24935    void sendPackageBroadcast(final String action, final String pkg,
24936        final Bundle extras, final int flags, final String targetPkg,
24937        final IIntentReceiver finishedReceiver, final int[] userIds);
24938    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
24939        int appId, int... userIds);
24940}
24941